lawspec 0.25.0 → 0.27.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 (156) hide show
  1. package/CHANGELOG.md +109 -1
  2. package/NORMALIZATION-LICENSES.txt +296 -0
  3. package/README.md +13 -4
  4. package/api.mjs +0 -8
  5. package/bin/lawspec.mjs +114 -79
  6. package/build.json +99 -117
  7. package/core.wasm +2 -2
  8. package/core_jsffi.js +5 -0
  9. package/doctor.mjs +14 -4
  10. package/examples/native-payments/clojure/lawspec.json +1 -1
  11. package/examples/native-payments/csharp/lawspec.json +1 -1
  12. package/examples/native-payments/elixir/lawspec.json +1 -1
  13. package/examples/native-payments/erlang/lawspec.json +1 -1
  14. package/examples/native-payments/fsharp/lawspec.json +1 -1
  15. package/examples/native-payments/gleam/lawspec.json +1 -1
  16. package/examples/native-payments/go/lawspec.json +1 -1
  17. package/examples/native-payments/groovy/lawspec.json +1 -1
  18. package/examples/native-payments/haskell/lawspec.json +1 -1
  19. package/examples/native-payments/java/lawspec.json +1 -1
  20. package/examples/native-payments/javascript/lawspec.json +1 -1
  21. package/examples/native-payments/kotlin/lawspec.json +1 -1
  22. package/examples/native-payments/prolog/lawspec.json +20 -0
  23. package/examples/native-payments/prolog/src/domain/payments.pl +23 -0
  24. package/examples/native-payments/prolog/tests/domain/payment_generators.pl +17 -0
  25. package/examples/native-payments/python/lawspec.json +1 -1
  26. package/examples/native-payments/rust/lawspec.json +1 -1
  27. package/examples/native-payments/scala/lawspec.json +1 -1
  28. package/examples/native-payments/swift/lawspec.json +1 -1
  29. package/examples/native-payments/typescript/lawspec.json +1 -1
  30. package/examples/packages/orders/lawspec.json +1 -1
  31. package/examples/packages/orders/orders.lawspec +27 -25
  32. package/examples/packages/shop-domain/src/domain.lawspec +15 -14
  33. package/examples/packages/shop-tax-1/src/api.lawspec +1 -0
  34. package/examples/packages/shop-tax-1/src/rates.lawspec +1 -0
  35. package/examples/packages/shop-tax-2/src/api.lawspec +1 -0
  36. package/examples/packages/shop-tax-2/src/rates.lawspec +1 -0
  37. package/examples/rc1/authorization-snapshots.lawspec +24 -23
  38. package/examples/rc1/banner-filenames.lawspec +7 -6
  39. package/examples/rc1/bit-codec.lawspec +12 -11
  40. package/examples/rc1/bounded-witness-search.lawspec +52 -45
  41. package/examples/rc1/conflicting-requirements.lawspec +8 -7
  42. package/examples/rc1/constructive-witnesses.lawspec +40 -33
  43. package/examples/rc1/documentary-review.lawspec +9 -8
  44. package/examples/rc1/empty-domains.lawspec +16 -15
  45. package/examples/rc1/finite-integer-domains.lawspec +24 -23
  46. package/examples/rc1/law-metadata.lawspec +6 -5
  47. package/examples/rc1/native-payments.lawspec +17 -16
  48. package/examples/rc1/nesting/rrr.lawspec +4 -3
  49. package/examples/rc1/nesting/rru.lawspec +7 -6
  50. package/examples/rc1/nesting/rur.lawspec +7 -6
  51. package/examples/rc1/nesting/ruu.lawspec +10 -9
  52. package/examples/rc1/nesting/urr.lawspec +7 -6
  53. package/examples/rc1/nesting/uru.lawspec +10 -9
  54. package/examples/rc1/nesting/uur.lawspec +10 -9
  55. package/examples/rc1/nesting/uuu.lawspec +13 -12
  56. package/examples/rc1/order-workflow.lawspec +18 -17
  57. package/examples/rc1/parcel-measurements.lawspec +14 -13
  58. package/examples/rc1/picture-records.lawspec +6 -5
  59. package/examples/rc1/picture-tuples.lawspec +6 -5
  60. package/examples/rc1/record-payloads.lawspec +12 -11
  61. package/examples/rc1/recursive-records.lawspec +11 -10
  62. package/examples/rc1/refund-conformance.lawspec +7 -6
  63. package/examples/rc1/refund-policy.lawspec +15 -14
  64. package/examples/rc1/requirement-composition.lawspec +26 -25
  65. package/examples/rc1/structural-records.lawspec +13 -12
  66. package/examples/rc1-authoring.lawspec +6 -5
  67. package/examples/specs/abilities.lawspec +67 -65
  68. package/examples/specs/ability_imports.lawspec +58 -57
  69. package/examples/specs/actors.lawspec +23 -22
  70. package/examples/specs/algebra.lawspec +142 -141
  71. package/examples/specs/approvals.lawspec +19 -18
  72. package/examples/specs/async_bindings.lawspec +10 -9
  73. package/examples/specs/async_fetch.lawspec +12 -11
  74. package/examples/specs/atoi_codec.lawspec +16 -15
  75. package/examples/specs/boolean_flags.lawspec +10 -9
  76. package/examples/specs/builtins.lawspec +73 -72
  77. package/examples/specs/canonical_url.lawspec +14 -13
  78. package/examples/specs/collections.lawspec +153 -154
  79. package/examples/specs/composition.lawspec +70 -66
  80. package/examples/specs/concurrent_collections.lawspec +8 -7
  81. package/examples/specs/consistency.lawspec +4 -3
  82. package/examples/specs/contracts.lawspec +80 -79
  83. package/examples/specs/crypto.lawspec +26 -25
  84. package/examples/specs/ctc.lawspec +148 -0
  85. package/examples/specs/currying.lawspec +32 -31
  86. package/examples/specs/data_types.lawspec +50 -49
  87. package/examples/specs/distribution.lawspec +57 -56
  88. package/examples/specs/domain_modeling.lawspec +68 -47
  89. package/examples/specs/durations.lawspec +39 -38
  90. package/examples/specs/equivalent.lawspec +25 -24
  91. package/examples/specs/failures.lawspec +64 -63
  92. package/examples/specs/finite_data.lawspec +32 -31
  93. package/examples/specs/flow_stack.lawspec +64 -63
  94. package/examples/specs/gadt_expressions.lawspec +50 -49
  95. package/examples/specs/generation.lawspec +115 -114
  96. package/examples/specs/handler_bindings.lawspec +42 -40
  97. package/examples/specs/handles.lawspec +2 -1
  98. package/examples/specs/harness.lawspec +45 -43
  99. package/examples/specs/harness_testing.lawspec +18 -13
  100. package/examples/specs/indexed_arithmetic.lawspec +401 -126
  101. package/examples/specs/indexed_families.lawspec +182 -66
  102. package/examples/specs/keywords.lawspec +22 -21
  103. package/examples/specs/limits.lawspec +7 -6
  104. package/examples/specs/list_contracts.lawspec +121 -120
  105. package/examples/specs/list_refinements.lawspec +43 -42
  106. package/examples/specs/lists.lawspec +45 -44
  107. package/examples/specs/matchers.lawspec +79 -78
  108. package/examples/specs/matching.lawspec +43 -42
  109. package/examples/specs/mixed_inputs.lawspec +25 -24
  110. package/examples/specs/models.lawspec +44 -43
  111. package/examples/specs/parse_port.lawspec +28 -27
  112. package/examples/specs/payments.lawspec +55 -54
  113. package/examples/specs/railway.lawspec +59 -58
  114. package/examples/specs/records.lawspec +149 -148
  115. package/examples/specs/records_inner.lawspec +5 -4
  116. package/examples/specs/recursive_refinements.lawspec +30 -29
  117. package/examples/specs/refined_definitions.lawspec +24 -23
  118. package/examples/specs/refinements.lawspec +58 -57
  119. package/examples/specs/resilience.lawspec +161 -160
  120. package/examples/specs/resources.lawspec +61 -60
  121. package/examples/specs/scalar_adapters.lawspec +60 -59
  122. package/examples/specs/scalar_catalog.lawspec +165 -164
  123. package/examples/specs/scalars.lawspec +78 -77
  124. package/examples/specs/scheduling_order.lawspec +8 -7
  125. package/examples/specs/scheduling_overlap.lawspec +5 -4
  126. package/examples/specs/sequences.lawspec +66 -65
  127. package/examples/specs/sessions.lawspec +13 -12
  128. package/examples/specs/slug.lawspec +16 -15
  129. package/examples/specs/sum_refinements.lawspec +42 -41
  130. package/examples/specs/tables.lawspec +29 -28
  131. package/examples/specs/total_functions.lawspec +71 -70
  132. package/examples/specs/workflows.lawspec +101 -100
  133. package/examples-command.mjs +7 -7
  134. package/explain.mjs +6 -4
  135. package/expression-presentation.mjs +8 -8
  136. package/files.mjs +1 -1
  137. package/index.d.ts +10 -528
  138. package/launcher.mjs +9 -2
  139. package/lsp.mjs +10 -6
  140. package/native-evidence.mjs +25 -12
  141. package/native-examples.mjs +3 -3
  142. package/package.json +2 -1
  143. package/starter-rc1.lawspec +6 -5
  144. package/starter.lawspec +16 -15
  145. package/templates.mjs +88 -5
  146. package/test-command.mjs +40 -4
  147. package/migrate.mjs +0 -135
  148. package/migration-bindings.mjs +0 -86
  149. package/migration-cases.mjs +0 -45
  150. package/migration-collections.mjs +0 -54
  151. package/migration-correspondence.mjs +0 -275
  152. package/migration-generation.mjs +0 -99
  153. package/migration-laws.mjs +0 -102
  154. package/migration-records.mjs +0 -166
  155. package/migration-source.mjs +0 -247
  156. package/migration-write.mjs +0 -156
@@ -1,99 +0,0 @@
1
- // Generated from templates/npm/migration-generation.mjs by lawspec-dev generate. Do not edit.
2
- // Generation is an independent migration gate. A compiler's accepted emission
3
- // receipt never means that a target compiler or an external implementation ran.
4
- import {bindingDigest,checkBindingProposal} from './migration-bindings.mjs';
5
-
6
- const pending=reason=>({status:'not-established',reason});
7
- const digest=value=>typeof value==='string'&&/^[0-9a-f]{64}$/.test(value);
8
- const sourceInputs=input=>Object.fromEntries(['sources','packages','package','dependencies']
9
- .filter(key=>input[key]!==undefined).map(key=>[key,input[key]]));
10
- const safePath=value=>typeof value==='string'&&value.length>0&&!/[\\\0]/.test(value)&&
11
- value.split('/').every(part=>part&&part!=='.'&&part!=='..')&&!/^[A-Za-z]:/.test(value);
12
- const acceptedSide=side=>side?.status==='accepted'&&Array.isArray(side.diagnostics)&&side.diagnostics.length===0&&
13
- Array.isArray(side.files)&&side.files.length>0&&side.files.every(file=>file&&safePath(file.path)&&
14
- ['user','generated'].includes(file.ownership)&&['source','test'].includes(file.placement)&&
15
- Object.keys(file).every(key=>['path','ownership','placement','contentDigest','adapterReferenceDigest'].includes(key))&&
16
- digest(file.contentDigest)&&(file.adapterReferenceDigest===undefined||digest(file.adapterReferenceDigest)))&&
17
- new Set(side.files.map(file=>file.path)).size===side.files.length&&digest(side.artifactDigest)&&
18
- bindingDigest(side.files)===side.artifactDigest;
19
-
20
- export function checkGenerationReceipt(before,after,request,bindingProposal,evidence){
21
- if(!request?.migrated||!request.generation||!evidence?.generation)
22
- return pending('A complete generation request and receipt are required.');
23
- const proposal=evidence?.bindingProposal;
24
- const binding=checkBindingProposal(before,after,request.nativeBindings,request.target,proposal);
25
- if(binding.status!=='matched'||bindingDigest(proposal)!==bindingDigest(bindingProposal))
26
- return pending('Generation does not carry the matching checked binding proposal.');
27
- if(evidence?.version!==1||evidence.algorithm!=='sha256'||evidence.target!==request.target||
28
- evidence.machineBits!==(request.machineBits??64)||evidence.sourceDir!==(request.sourceDir??null)||
29
- evidence.testDir!==(request.testDir??null)||evidence.minify!==(request.minify??false)||
30
- bindingDigest(evidence.generation)!==bindingDigest(request.generation)||evidence.planning!=='legacy-harnesses'||
31
- evidence.sourceInputs?.before!==bindingDigest(sourceInputs(request))||
32
- evidence.sourceInputs?.after!==bindingDigest(sourceInputs(request.migrated))||
33
- evidence.nativeConformance!=='not-established'||evidence.lawVerification!=='not-established-by-generation')
34
- return pending('Generation receipt does not match these exact sources, dependencies, target, width, layout and limits.');
35
- if(evidence.status!=='accepted'||!acceptedSide(evidence.before)||!acceptedSide(evidence.after)){
36
- const failures=['before','after'].flatMap(side=>evidence[side]?.diagnostics?.map(item=>`${side}: ${item.code}: ${item.message}`)??[]);
37
- return pending(failures.join(' ')||evidence.after?.reason||'Complete target generation was not accepted on both inputs.');
38
- }
39
- return {status:'accepted',basis:'compiler-emission-of-both-checked-programs',
40
- scope:'legacy harness plans and complete artifact manifests; target compilation and native behavior remain separate'};
41
- }
42
-
43
- const boundaryAssumptions=['existing compiler emitters',
44
- 'unchanged native implementations under their original binding assumptions'];
45
- const boundaryKeys=['configuration','types','calls','handlers','unboundAdapters','unmappedData'];
46
- const availableBoundary=side=>side?.status==='available'&&side.contract&&
47
- typeof side.contract==='object'&&!Array.isArray(side.contract)&&
48
- Object.keys(side.contract).length===boundaryKeys.length&&
49
- boundaryKeys.every(key=>key==='configuration'?side.contract[key]&&typeof side.contract[key]==='object'&&
50
- !Array.isArray(side.contract[key]):Array.isArray(side.contract[key]))&&
51
- digest(side.digest)&&bindingDigest(side.contract)===side.digest;
52
-
53
- export function checkNativeBoundaryReceipt(before,after,request,bindingProposal,evidence){
54
- const generation=checkGenerationReceipt(before,after,request,bindingProposal,evidence);
55
- if(generation.status!=='accepted')return pending(generation.reason);
56
- const boundary=evidence.nativeBoundary;
57
- if(boundary?.version!==1||boundary.algorithm!=='sha256'||boundary.policy!=='resolved-native-contract-v1'||
58
- boundary.nativeConformance!=='not-established'||
59
- boundary.lawVerification!=='not-established-by-boundary-correspondence'||
60
- bindingDigest(boundary.assumptions??null)!==bindingDigest(boundaryAssumptions)||
61
- !availableBoundary(boundary.before)||!availableBoundary(boundary.after))
62
- return pending(boundary?.after?.reason||boundary?.before?.reason||
63
- 'A complete resolved native boundary comparison with its original assumptions is required.');
64
- const configuration={...bindingProposal.proposedNativeBindings,types:[]};
65
- if(bindingDigest(boundary.after.contract.configuration)!==bindingDigest(configuration)||
66
- boundary.status!=='matched'||boundary.before.digest!==boundary.after.digest)
67
- return pending('Resolved native call contracts or generated adapter layouts differ across the migration.');
68
- return {status:'matched',basis:'compiler-resolved-native-contract-correspondence',
69
- scope:boundary.scope,assumptions:[...boundaryAssumptions],
70
- nativeConformance:'not-established',lawVerification:'not-established-by-boundary-correspondence'};
71
- }
72
-
73
- export async function planMigrationGeneration(compiler,config,input,sources,before,after,bindingPreview,migratedContext={}){
74
- const rows=[];
75
- for(const binding of bindingPreview.targets){
76
- const target=binding.index===null?input:config.targets[binding.index];
77
- if(binding.status!=='matched'||!binding.target||typeof compiler.migrationGeneration!=='function'){
78
- const unavailable=pending(binding.reason||
79
- 'A concrete target, matching binding proposal and generation-capable compiler are required.');
80
- rows.push({target:binding.target,index:binding.index,...unavailable,nativeBoundary:{...unavailable}});continue;
81
- }
82
- const options={...input,schemaVersion:5,languageProfile:'1.0-rc.1',verification:{layers:[]},
83
- target:binding.target,sourceDir:target.sourceDir,testDir:target.testDir,minify:input.minify===true};
84
- const request={...options,from:'0.24',nativeBindings:binding.evidence.inputBindings,
85
- migrated:{...options,...migratedContext,sources,nativeBindings:binding.proposedNativeBindings}};
86
- const result=await compiler.migrationGeneration(request),evidence=result.migrationGeneration;
87
- const checked=result.diagnostics?.length?pending(result.diagnostics.map(item=>item.message).join(' ')):
88
- checkGenerationReceipt(before,after,request,binding.evidence,evidence);
89
- const nativeBoundary=checked.status==='accepted'?
90
- checkNativeBoundaryReceipt(before,after,request,binding.evidence,evidence):pending(checked.reason);
91
- rows.push({target:binding.target,index:binding.index,...checked,nativeBoundary,evidence,diagnostics:result.diagnostics??[]});
92
- }
93
- const count=bindingPreview.configurationCount;
94
- return {status:count===0?'not-requested':rows.length===count&&rows.every(row=>row.status==='accepted')?'accepted':'not-established',
95
- scope:'every configured target; emitted artifacts, not native execution',configurationCount:count,targets:rows,
96
- nativeBoundary:{status:count===0?'not-requested':rows.length===count&&rows.every(row=>row.nativeBoundary.status==='matched')?
97
- 'matched':'not-established',configurationCount:count,
98
- scope:'resolved native call contracts and generated adapter layouts under unchanged native implementation assumptions'}};
99
- }
@@ -1,102 +0,0 @@
1
- // Generated from templates/npm/migration-laws.mjs by lawspec-dev generate. Do not edit.
2
- // Law edits consume the original parser's checked source inventory. They
3
- // deliberately target the current minor grammar; its remaining plain closers
4
- // are superseded by the following milestone's all-named-ending requirement.
5
- import {MigrationDocument,planLegacyComputationEdits} from './migration-source.mjs';
6
- import {planLegacyCases} from './migration-cases.mjs';
7
- import {planLegacyRecords,legacyRecordShapes} from './migration-records.mjs';
8
- import {planLegacyCollectionNames} from './migration-collections.mjs';
9
-
10
- function phrase(name) {
11
- if (!name || name.trim() !== name || /[\r\n]/.test(name))
12
- throw new Error('Legacy quoted names with empty bodies or edge whitespace need an explicit rename');
13
- return '"|' + name.replace(/[\\|]/g,character => '\\'+character) + '|';
14
- }
15
-
16
- export function planLegacySourceEdits(sources, baseline, sourceSyntax, sourceFields) {
17
- const computations = planLegacyComputationEdits(sources,baseline,sourceSyntax);
18
- const documents = new Map(sources.map(source => [source.path,new MigrationDocument(source)]));
19
- for (const source of computations) documents.get(source.path).edits.push(...source.edits);
20
- // The legacy resolver uses the bare target Natural for its implicit
21
- // refinement and same-spelled user refinements. Do not assume the builtin
22
- // meaning if any admitted source explicitly declares that refinement.
23
- const builtinNatural=!sourceSyntax.some(source=>source.nodes.some(node=>
24
- node.kind==='declaration.refinement'&&node.name==='Natural'));
25
- const indexed=sourceSyntax.filter(source=>documents.has(source.path)).map(source=>{
26
- const document=documents.get(source.path);
27
- const nodes=source.nodes.map(node=>({...node,...document.range({kind:'source',span:node.span})}));
28
- if (nodes.some(node=>!Number.isInteger(node.start))) throw new Error('Source inventory belongs to a different migration document');
29
- return {...source,nodes,builtinNatural,
30
- constructorShapes:sourceFields?.status==='available' ? sourceFields.constructors : null,
31
- fieldUses:sourceFields?.status==='available' ? sourceFields.uses.filter(use=>use.span.start.file===source.path) : null};
32
- });
33
- const shapes=legacyRecordShapes(indexed);
34
- for (const source of indexed) {
35
- const document = documents.get(source.path);
36
- if (!document) continue;
37
- const nodes=source.nodes;
38
- const contains = (outer,inner) => outer.start <= inner.start && inner.end <= outer.end;
39
- const code = node => document.code(node.start,node.end);
40
- const first = node => code(node)[0];
41
- const replaceToken = (token,content,reason) => {
42
- if (!token) throw new Error('Checked source node has no token for '+reason);
43
- document.edit(token.start,token.end,content,reason);
44
- };
45
- const headerDelimiter = (node,word) => {
46
- let depth = 0;
47
- return code(node).find(token => {
48
- if (['(','[','{'].includes(token.text)) depth++;
49
- if ([')',']','}'].includes(token.text)) depth--;
50
- return depth === 0 && token.text === word;
51
- });
52
- };
53
- planLegacyCollectionNames(document,source);
54
- planLegacyRecords(document,source,shapes);
55
- planLegacyCases(document,nodes);
56
- for (const node of nodes) {
57
- if (node.kind === 'quoted-name') {
58
- // Scenarios and benchmark labels retain their existing quoted syntax.
59
- if (nodes.some(parent => ['declaration.scenario','benchmark'].includes(parent.kind) && contains(parent,node))) continue;
60
- const token = first(node);
61
- if (token?.kind !== 'quoted') throw new Error('Checked quoted name has no legacy delimiter');
62
- const marker = nodes.some(parent => ['import','export'].includes(parent.kind) && contains(parent,node)) ? 'law ' : '';
63
- replaceToken(token,marker+phrase(node.name),'quoted law or example name');
64
- }
65
- if (node.kind === 'law-reference')
66
- document.edit(node.start,node.start,'apply law ','reusable law application');
67
- if (node.kind === 'section') {
68
- const tokens = code(node);
69
- const delimiter = tokens[1];
70
- if (tokens[0]?.text !== node.name || !['is','are'].includes(delimiter?.text))
71
- throw new Error('Checked law section has no legacy delimiter');
72
- replaceToken(delimiter,':','law section delimiter');
73
- }
74
- if (node.kind === 'example') {
75
- replaceToken(headerDelimiter(node,'is'),':','example delimiter');
76
- }
77
- if (node.kind === 'quantifier.forall') {
78
- const tokens = code(node);
79
- if (tokens[0]?.text !== '`for all`') throw new Error('Checked universal quantifier has no legacy opener');
80
- replaceToken(tokens[0],'for all','universal quantifier');
81
- replaceToken(headerDelimiter(node,'.'),'=>','universal binder delimiter');
82
- // Source inventory is in completion order, so nested quantifiers at
83
- // the same offset close inside out, after any inner conditional.
84
- document.edit(tokens.at(-1).end,tokens.at(-1).end,' end','universal scope','universal:'+node.start);
85
- }
86
- }
87
- // Expectations move as one lossless source range. Comments, line breaks,
88
- // recorded names and child expression edits accompany the moved text.
89
- for (const table of nodes.filter(node => node.kind === 'table')) {
90
- const expectations = nodes.filter(node => node.kind === 'table-expectation' && contains(table,node));
91
- if (!expectations.length) throw new Error('A legacy table without expectations needs an explicit authoring decision');
92
- const start = Math.min(...expectations.map(node => node.start));
93
- const end = Math.max(...expectations.map(node => node.end));
94
- const opener = first(table);
95
- if (opener?.text !== 'table') throw new Error('Checked table has no legacy opener');
96
- replaceToken(headerDelimiter(table,'is'),':','table delimiter');
97
- document.moveBefore(start,end,opener.start,'expectation-first table');
98
- document.edit(opener.start,opener.start,'in ','expectation table introducer');
99
- }
100
- }
101
- return [...documents.values()].map(document => document.result());
102
- }
@@ -1,166 +0,0 @@
1
- // Generated from templates/npm/migration-records.mjs by lawspec-dev generate. Do not edit.
2
- // Declarations supply shapes; the checked resolver supplies identities across
3
- // imports and re-exports. No client-side import resolver is used here.
4
- const contains = (outer,inner) => outer.start<=inner.start && inner.end<=outer.end;
5
- function declarations(source) {
6
- const {nodes}=source;
7
- return nodes.filter(node=>node.kind==='declaration.type').flatMap(type=>{
8
- // Parameters and constructor equations stay in place. Admission and the
9
- // compiler's checked transport decide whether this preview is equivalent.
10
- const constructors=nodes.filter(node=>node.kind==='constructor' && contains(type,node));
11
- const declared=constructors.map(constructor=>({...constructor,fields:nodes.filter(node=>node.kind==='constructor-field' && contains(constructor,node))}));
12
- if (!declared.some(constructor=>constructor.fields.length)) return [];
13
- let nominal=false;
14
- if (declared.length===1 && declared[0].name===type.name) {
15
- const binding=source.bindings.find(binding=>binding.namespace==='constructor' && binding.name===declared[0].name);
16
- const shape=source.constructorShapes?.find(shape=>shape.constructor===binding?.target);
17
- if (typeof shape?.nominalRecord!=='boolean')
18
- throw new Error('Nominal record migration requires checked constructor classification: '+declared[0].name);
19
- nominal=shape.nominalRecord;
20
- }
21
- return [{type,declared,nominal}];
22
- });
23
- }
24
- export function legacyRecordShapes(sources) {
25
- const shapes=new Map();
26
- for (const source of sources) {
27
- if (!Array.isArray(source.bindings)) throw new Error('Record migration requires checked namespace bindings');
28
- for (const {declared,nominal} of declarations(source)) for (const constructor of declared) {
29
- const binding=source.bindings.find(binding=>binding.namespace==='constructor' && binding.name===constructor.name);
30
- if (!binding) throw new Error('Checked constructor has no resolver identity: '+constructor.name);
31
- if (shapes.has(binding.target)) throw new Error('Duplicate checked constructor identity: '+binding.target);
32
- // message is an existing typed failure-matcher field. Preserve that
33
- // explicit role inside a record even when it is the only payload field.
34
- const grouped=!nominal&&(constructor.fields.length>1||constructor.fields.some(field=>field.name==='message'));
35
- shapes.set(binding.target,{name:constructor.name,fields:constructor.fields.map(field=>field.name),record:nominal,grouped,wrap:nominal||grouped});
36
- }
37
- }
38
- return shapes;
39
- }
40
- export function planLegacyRecords(document,source,shapes) {
41
- const nodes=source.nodes;
42
- const contains = (outer,inner) => outer.start<=inner.start && inner.end<=outer.end;
43
- const code = node => document.code(node.start,node.end);
44
- const replace = (token,content,reason) => {
45
- if (!token) throw new Error('Checked constructor has no token for '+reason);
46
- document.edit(token.start,token.end,content,reason);
47
- };
48
- const shapeOf = name => shapes.get(source.bindings.find(binding=>binding.namespace==='constructor' && binding.name===name)?.target);
49
- const fieldNodes=nodes.filter(node=>['field-access','field-update'].includes(node.kind));
50
- if(fieldNodes.length && !Array.isArray(source.fieldUses))
51
- throw new Error('Field migration requires checked source field identities');
52
- const updates=new Map();
53
- for(const use of source.fieldUses??[]) {
54
- const range=document.range({kind:'source',span:use.span});
55
- const node=fieldNodes.find(node=>node.kind===use.kind && node.start===range?.start && node.end===range?.end);
56
- if(!node || node.name!==use.field) throw new Error('Checked field identity has no matching source suffix');
57
- const shape=shapes.get(use.constructor);
58
- if(!shape || shape.record) continue;
59
- if(shape.fields[use.index]!==use.field) throw new Error('Checked field identity does not match its constructor position');
60
- const tokens=code(node);
61
- if(use.kind==='field-access') {
62
- if(tokens[0]?.text!=='.' || tokens[1]?.text!==use.field)
63
- throw new Error('Checked field access has no source label');
64
- replace(tokens[1],shape.grouped?'value.'+use.field:'value','explicit payload field access');
65
- } else if(!shape.grouped) {
66
- if(tokens[0]?.text!==use.field) throw new Error('Checked field update has no source label');
67
- replace(tokens[0],'value','explicit payload field update');
68
- } else {
69
- const selected=document.range({kind:'source',span:use.base});
70
- const expression=document.range({kind:'source',span:use.expression});
71
- if(!selected || !expression) throw new Error('Checked grouped payload update has no base expression span');
72
- const key=expression.start+':'+expression.end;
73
- const previous=updates.get(key);
74
- if(previous && previous.constructor!==use.constructor) throw new Error('Payload update resolves to inconsistent constructors');
75
- updates.set(key,{constructor:use.constructor,selected,expression});
76
- }
77
- }
78
- for(const {constructor,selected,expression} of updates.values()) {
79
- const bindings=source.bindings.filter(binding=>binding.namespace==='constructor' && binding.target===constructor);
80
- const names=[...new Set(bindings.map(binding=>binding.name))].sort((a,b)=>a.length-b.length || (a<b?-1:a>b?1:0));
81
- if(!names.length) throw new Error('Grouped payload update requires an accessible checked constructor: '+constructor);
82
- const first=code(selected)[0],last=code(selected).at(-1),end=code(expression).at(-1);
83
- if(!first || !last || !end) throw new Error('Checked grouped payload update has no source tokens');
84
- document.edit(first.start,first.start,names[0]+' (','payload update construction');
85
- document.edit(last.end,last.end,'.value','payload update selected record');
86
- document.edit(end.end,end.end,')','payload update construction closer');
87
- }
88
- const sourceTag = node => {
89
- if (!node?.name) return null;
90
- const tokens=code(node),count=node.name.split('.').length*2-1;
91
- return tokens.slice(0,count).map(token=>token.text).join('')===node.name
92
- ? {start:tokens[0].start,end:tokens[count-1].end} : null;
93
- };
94
- for (const {type,declared,nominal} of declarations(source)) {
95
- const tokens = code(type);
96
- const delimiter = tokens.find(token=>token.text==='is');
97
- if (tokens[0]?.text!=='type' || !delimiter || tokens.at(-1)?.text!=='end')
98
- throw new Error('Checked payload declaration has no legacy delimiters');
99
- replace(delimiter,nominal?'is a record{':'is one of','payload type delimiter');
100
- replace(tokens.at(-1),'end type','type closer');
101
- for (const constructor of declared) {
102
- const fields = constructor.fields;
103
- const tag = code(constructor)[0];
104
- if (tag?.text!==constructor.name) throw new Error('Checked payload has no constructor token');
105
- if (nominal) {
106
- const preceding = tokens.filter(token=>token.end<=tag.start).at(-1);
107
- if (preceding?.text==='|') replace(preceding,'','nominal record alternative marker');
108
- replace(tag,'','nominal record constructor');
109
- const last = code(fields.at(-1)).at(-1);
110
- document.edit(last.end,last.end,'}','record type closer');
111
- } else if (fields.length===1 && !shapeOf(constructor.name)?.grouped) {
112
- const tokens = code(fields[0]);
113
- replace(tokens[0],'','single payload label');
114
- if (tokens[1]?.text==='::') replace(tokens[1],'of type','explicit payload annotation');
115
- else if (tokens[1]?.text!=='of' || tokens[2]?.text!=='type') throw new Error('Checked payload has no source annotation');
116
- } else if (fields.length>0) {
117
- document.edit(tag.end,tag.end,' of type record{','explicit record payload');
118
- const last = code(fields.at(-1)).at(-1);
119
- document.edit(last.end,last.end,'}','record payload closer');
120
- }
121
- }
122
- }
123
- const uniqueRanges = values => [...new Map(values.map(value=>[value.start+':'+value.end,value])).values()];
124
- const children = (parent,kind) => {
125
- const values = uniqueRanges(nodes.filter(node=>node.start>parent.start && contains(parent,node) && kind(node)));
126
- return values.filter(node=>!values.some(outer=>outer!==node && contains(outer,node)))
127
- .sort((left,right)=>left.start-right.start);
128
- };
129
- const wrap = (tag,arguments_,shape,reason) => {
130
- if (arguments_.length!==shape.fields.length) throw new Error('Checked constructor arguments do not match its source fields: '+shape.name);
131
- document.edit(tag.end,tag.end,' record{',reason+' opener');
132
- for (const [index,argument] of arguments_.entries()) {
133
- const tokens = code(argument);
134
- if (!tokens.length) throw new Error('Checked record argument has no source value');
135
- document.edit(tokens[0].start,tokens[0].start,(index?', ':'')+shape.fields[index]+' = ',reason+' field');
136
- }
137
- const last = code(arguments_.at(-1)).at(-1);
138
- document.edit(last.end,last.end,'}',reason+' closer');
139
- };
140
- // Parenthesized nodes repeat their child's constructor role. Only the node
141
- // whose physical opener is that constructor owns the inserted record; the
142
- // enclosing parentheses and annotations stay exactly where they were.
143
- const expressions = nodes.filter(node=>node.kind==='application.constructor' && shapeOf(node.name)?.wrap && sourceTag(node));
144
- for (const expression of expressions.filter(node=>!expressions.some(outer=>outer!==node && outer.start===node.start && outer.end>node.end))) {
145
- const shape = shapeOf(expression.name);
146
- const tag = sourceTag(expression);
147
- wrap(tag,children(expression,node=>node.kind.startsWith('expression.') || node.kind==='application' || node.kind==='application.constructor'),shape,'record construction');
148
- }
149
- for (const literal of nodes.filter(node=>node.kind==='literal' && shapeOf(node.name)?.wrap && sourceTag(node))) {
150
- const shape = shapeOf(literal.name);
151
- const tag = sourceTag(literal);
152
- wrap(tag,children(literal,node=>node.kind==='literal'),shape,'record literal');
153
- }
154
- for (const branch of nodes.filter(node=>node.kind==='case-branch' && shapeOf(node.name)?.wrap)) {
155
- const shape = shapeOf(branch.name);
156
- const tokens = code(branch);
157
- const arrow = tokens.find(token=>token.text==='->');
158
- const tag = nodes.find(node=>node.kind==='pattern-constructor' && contains(branch,node) && node.name===branch.name && node.end<=arrow?.start);
159
- const bindings = nodes.filter(node=>node.kind==='pattern-binding' && contains(branch,node) && node.end<=arrow?.start);
160
- if (!tag || !arrow) throw new Error('Checked record pattern has no source branch');
161
- wrap(sourceTag(tag),bindings,shape,'record pattern');
162
- }
163
- for (const pattern of nodes.filter(node=>node.kind==='matcher-pattern' && shapeOf(node.name)?.wrap && sourceTag(node))) {
164
- wrap(sourceTag(pattern),children(pattern,node=>node.kind==='matcher-field'),shapeOf(pattern.name),'record matcher pattern');
165
- }
166
- }
@@ -1,247 +0,0 @@
1
- // Generated from templates/npm/migration-source.mjs by lawspec-dev generate. Do not edit.
2
- // Source edits use the checked legacy compiler's declaration/expression spans.
3
- // This module plans edits; semantic correspondence and project writes belong
4
- // to the migration coordinator, not this lexical layer.
5
- export function migrationTokens(content) {
6
- const result = [];
7
- for (let offset = 0; offset < content.length;) {
8
- const start = offset;
9
- let kind;
10
- const rest = content.slice(offset);
11
- if (rest.startsWith('--')) {
12
- kind = 'comment';
13
- offset = content.indexOf('\n', offset);
14
- if (offset < 0) offset = content.length;
15
- } else if (/^\s/u.test(rest)) {
16
- kind = 'trivia';
17
- offset += /^\s+/u.exec(rest)[0].length;
18
- } else if (rest[0] === '"' || rest[0] === '`') {
19
- const delimiter = rest[0];
20
- kind = delimiter === '"' ? 'string' : 'quoted';
21
- offset++;
22
- let closed = false;
23
- while (offset < content.length) {
24
- const character = content[offset++];
25
- if (delimiter === '"' && character === '\\') {
26
- if (offset >= content.length) throw new Error('Unterminated migration string escape');
27
- offset++;
28
- } else if (character === delimiter) { closed = true; break; }
29
- }
30
- if (!closed) throw new Error('Unterminated migration ' + kind);
31
- } else {
32
- const word = /^[\p{L}\p{N}_]+/u.exec(rest);
33
- if (word) { kind = 'word'; offset += word[0].length; }
34
- else {
35
- kind = 'symbol';
36
- const symbol = /^(?:::|->|==|!=|<=|>=|&&|\|\||\+\+|>>=|<\$>|<!>|<\|>|>=>|<\*>|\?\?|\|>)/.exec(rest);
37
- offset += symbol ? symbol[0].length : String.fromCodePoint(content.codePointAt(offset)).length;
38
- }
39
- }
40
- result.push({kind, start, end: offset, text: content.slice(start, offset)});
41
- }
42
- return result;
43
- }
44
-
45
- // Megaparsec columns count Unicode code points and expand tabs to eight-column
46
- // stops; JavaScript offsets count UTF-16 units. Neither is a byte offset.
47
- export function migrationOffset(content, location) {
48
- if (!Number.isInteger(location.line) || !Number.isInteger(location.column) || location.line < 1 || location.column < 1)
49
- throw new Error('Invalid migration source location');
50
- let offset = 0;
51
- for (let line = 1; line < location.line; line++) {
52
- const newline = content.indexOf('\n', offset);
53
- if (newline < 0) throw new Error('Migration source line is out of bounds');
54
- offset = newline + 1;
55
- }
56
- let column = 1;
57
- while (column < location.column && offset < content.length && content[offset] !== '\n') {
58
- const character = String.fromCodePoint(content.codePointAt(offset));
59
- const next = character === '\t' ? column + 8 - (column - 1) % 8 : column + 1;
60
- if (next > location.column) throw new Error('Migration source location is inside a tab');
61
- column = next;
62
- offset += character.length;
63
- }
64
- if (column !== location.column) throw new Error('Migration source column is out of bounds');
65
- return offset;
66
- }
67
-
68
- export class MigrationDocument {
69
- constructor(source) {
70
- this.path = source.path;
71
- this.content = source.content;
72
- this.tokens = migrationTokens(source.content);
73
- this.edits = [];
74
- }
75
- range(origin) {
76
- if (origin?.kind !== 'source' || origin.span.start.file !== this.path || origin.span.end.file !== this.path) return null;
77
- const start = migrationOffset(this.content, origin.span.start);
78
- const end = migrationOffset(this.content, origin.span.end);
79
- if (end < start) throw new Error('Reversed migration source span');
80
- return {start, end};
81
- }
82
- code(start = 0, end = this.content.length) {
83
- return this.tokens.filter(token => token.start >= start && token.end <= end && !['trivia','comment'].includes(token.kind));
84
- }
85
- edit(start, end, content, reason, identity = reason + ':' + start + ':' + end) {
86
- if (!Number.isInteger(start) || !Number.isInteger(end) || start < 0 || end < start || end > this.content.length)
87
- throw new Error('Migration edit is out of bounds');
88
- const same = this.edits.find(edit => edit.identity === identity);
89
- if (same) {
90
- if (same.start !== start || same.end !== end || same.content !== content) throw new Error('Inconsistent migration edit identity');
91
- return;
92
- }
93
- for (const previous of this.edits) {
94
- if (Math.max(start, previous.start) < Math.min(end, previous.end) ||
95
- (start === end && previous.start < start && start < previous.end) ||
96
- (previous.start === previous.end && start < previous.start && previous.start < end))
97
- throw new Error('Overlapping migration edits');
98
- }
99
- this.edits.push({start, end, content, reason, identity, before: this.content.slice(start,end)});
100
- }
101
- moveBefore(start, end, before, reason) {
102
- if (before >= start || end <= start) throw new Error('Migration move must precede a nonempty source range');
103
- // Render already checked child edits before relocating the range. The
104
- // retained segments continue to point into the original document, rather
105
- // than pretending that a moved expectation is newly authored source.
106
- const inside = this.edits.filter(edit => edit.start >= start && edit.end <= end);
107
- const fragment = new MigrationDocument({path:this.path,content:this.content.slice(start,end)});
108
- for (const edit of inside) fragment.edit(edit.start-start,edit.end-start,edit.content,edit.reason,edit.identity);
109
- const rendered = fragment.result();
110
- this.edits = this.edits.filter(edit => !inside.includes(edit));
111
- this.edit(start,end,'',reason + ' source');
112
- this.edit(before,before,rendered.content,reason);
113
- const insertion = this.edits.at(-1);
114
- insertion.sourceSegments = rendered.segments.map(segment => ({...segment,
115
- originalStart:segment.originalStart+start,originalEnd:segment.originalEnd+start}));
116
- insertion.nestedEdits = inside;
117
- }
118
- result() {
119
- const edits = this.edits.map((edit, order) => ({...edit, order})).sort((a,b) =>
120
- a.start - b.start || a.end - b.end || a.order - b.order);
121
- const segments = [];
122
- let output = '', offset = 0;
123
- for (const edit of edits) {
124
- if (edit.start < offset) throw new Error('Migration edit ordering overlaps');
125
- const retained = this.content.slice(offset, edit.start);
126
- segments.push({start:output.length, end:output.length + retained.length, originalStart:offset, originalEnd:edit.start, retained:true});
127
- output += retained;
128
- if (edit.sourceSegments) segments.push(...edit.sourceSegments.map(segment => ({...segment,
129
- start:segment.start+output.length,end:segment.end+output.length})));
130
- else segments.push({start:output.length, end:output.length + edit.content.length, originalStart:edit.start, originalEnd:edit.end, retained:false, reason:edit.reason});
131
- output += edit.content;
132
- offset = edit.end;
133
- }
134
- segments.push({start:output.length, end:output.length + this.content.length - offset, originalStart:offset, originalEnd:this.content.length, retained:true});
135
- output += this.content.slice(offset);
136
- return {path:this.path, content:output, edits:edits.map(({order, ...edit}) => edit), segments};
137
- }
138
- }
139
-
140
- function walk(value, visit) {
141
- if (!value || typeof value !== 'object') return;
142
- visit(value);
143
- for (const child of Object.values(value)) {
144
- if (Array.isArray(child)) child.forEach(item => walk(item, visit));
145
- else if (child && typeof child === 'object') walk(child, visit);
146
- }
147
- }
148
-
149
- export function planLegacyComputationEdits(sources, baseline, sourceSyntax = []) {
150
- if (baseline.diagnostics?.length) throw new Error('Migration requires a checked legacy baseline');
151
- const documents = new Map(sources.map(source => [source.path,new MigrationDocument(source)]));
152
- if (documents.size !== sources.length) throw new Error('Duplicate migration source path');
153
- for (const source of sourceSyntax) {
154
- if (source.version !== 1 || !Array.isArray(source.nodes)) throw new Error('Unsupported checked source syntax inventory');
155
- for (const node of source.nodes) if (!node.span?.start?.file || !node.span?.end?.file)
156
- throw new Error('Malformed checked source syntax span');
157
- }
158
- const parsedDeclarations = sourceSyntax.flatMap(source => source.nodes.filter(node => node.kind === 'declaration.definition')
159
- .map(node => {
160
- if (!Array.isArray(node.uses)) throw new Error('A checked source definition has no effect context');
161
- return {origin:{kind:'source',span:node.span},uses:node.uses};
162
- }));
163
- const declarations = [...parsedDeclarations,...(baseline.units ?? []).flatMap(unit => unit.declarations ?? [])];
164
- for (const declaration of declarations) {
165
- const document = documents.get(declaration.origin?.span?.start?.file);
166
- const range = document?.range(declaration.origin);
167
- if (!range) continue;
168
- const tokens = document.code(range.start, range.end);
169
- if (tokens[0]?.text !== 'definition') continue;
170
- const kind = declaration.uses?.length || declaration.async ? 'procedure' : 'function';
171
- document.edit(tokens[0].start,tokens[0].end,kind,'computation declaration');
172
- let depth = 0, annotation;
173
- for (const token of tokens.slice(2)) {
174
- if (['(','[','{'].includes(token.text)) depth++;
175
- else if ([')',']','}'].includes(token.text)) depth--;
176
- else if (depth === 0 && token.text === '::') { annotation = token; break; }
177
- else if (depth === 0 && token.text === 'is') break;
178
- }
179
- if (!annotation || tokens.at(-1)?.text !== 'end') throw new Error('Checked definition span does not identify its result and closer');
180
- document.edit(annotation.start,annotation.end,'->','computation result');
181
- const closer = tokens.at(-1);
182
- document.edit(closer.start,closer.end,'end ' + kind,'computation closer');
183
- }
184
- for (const source of sourceSyntax) for (const node of source.nodes) {
185
- const document = documents.get(node.span?.start?.file);
186
- const range = document?.range({kind:'source',span:node.span});
187
- if (!range) continue;
188
- if (node.kind === 'if') {
189
- const tokens = document.code(range.start,range.end);
190
- if (tokens[0]?.text !== 'if' || !tokens.at(-1)) throw new Error('Checked conditional syntax has no source block');
191
- document.edit(tokens.at(-1).end,tokens.at(-1).end,' end if','conditional closer','conditional:' + tokens[0].start);
192
- }
193
- if (node.kind === 'operator.value-equality') {
194
- const tokens = document.code(range.start,range.end);
195
- if (tokens.length !== 1 || tokens[0].text !== '==') throw new Error('Checked equality syntax has no operator token');
196
- document.edit(tokens[0].start,tokens[0].end,'=','typed equality');
197
- }
198
- }
199
- walk(baseline, expression => {
200
- if (expression.node?.kind === 'binary' && expression.node.operator === '==') {
201
- const document = documents.get(expression.origin?.span?.start?.file);
202
- const parent = document?.range(expression.origin);
203
- if (parent) {
204
- // Lowered constructors and intrinsic calls may have generated origins;
205
- // their source-bearing descendants still bound the operator. Never
206
- // choose among multiple candidates or infer a type from token spelling.
207
- const ranges = value => {
208
- const found = [];
209
- walk(value, child => {
210
- const range = document.range(child.origin);
211
- if (range && range.start >= parent.start && range.end <= parent.end) found.push(range);
212
- });
213
- return found;
214
- };
215
- const start = Math.max(parent.start,...ranges(expression.node.left).map(range => range.end));
216
- const end = Math.min(parent.end,...ranges(expression.node.right).map(range => range.start));
217
- const operators = start <= end ? document.code(start,end).filter(token => token.text === '==') : [];
218
- if (operators.length === 1) {
219
- const operator = operators[0];
220
- document.edit(operator.start,operator.end,'=','typed equality');
221
- }
222
- }
223
- }
224
- if (expression.node?.kind !== 'if') return;
225
- const document = documents.get(expression.origin?.span?.start?.file);
226
- const range = document?.range(expression.origin);
227
- const condition = document?.range(expression.node.condition?.origin);
228
- const alternative = document?.range(expression.node.else?.origin);
229
- if (!range || !condition || !alternative) return;
230
- const prefix = document.code(range.start,condition.start);
231
- const opener = prefix.find(token => token.text === 'if');
232
- if (!opener) return; // A select call or generated condition is not an if block.
233
- if (prefix.some(token => token.start < opener.start && token.text !== '(')) return;
234
- const last = document.code(alternative.start,alternative.end).at(-1);
235
- if (!last) throw new Error('Checked conditional has no source alternative');
236
- document.edit(last.end,last.end,' end if','conditional closer','conditional:' + opener.start);
237
- });
238
- for (const document of documents.values()) for (const token of document.tokens) {
239
- if (token.kind !== 'string' || !token.text.startsWith('"|')) continue;
240
- // Decimal escapes terminate at the next backslash. Escape any immediately
241
- // following decimal digits too, so a literal such as "|123" stays exact.
242
- const digits = /^\d*/.exec(token.text.slice(2))[0];
243
- const escaped = '"\\124' + [...digits].map(digit => '\\' + digit.charCodeAt(0)).join('') + token.text.slice(2 + digits.length);
244
- document.edit(token.start,token.end,escaped,'literal reserved prefix');
245
- }
246
- return [...documents.values()].map(document => document.result());
247
- }