lawspec 0.24.0 → 0.25.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +67 -1
- package/README.md +29 -22
- package/UNICODE-LICENSE.txt +39 -0
- package/api.mjs +14 -23
- package/bin/lawspec.mjs +186 -65
- package/build.json +255 -159
- package/builtin-data-names.mjs +73 -0
- package/core.wasm +2 -2
- package/examples/native-payments/clojure/lawspec.json +13 -2
- package/examples/native-payments/csharp/lawspec.json +13 -2
- package/examples/native-payments/elixir/lawspec.json +14 -3
- package/examples/native-payments/erlang/lawspec.json +14 -3
- package/examples/native-payments/fsharp/lawspec.json +14 -3
- package/examples/native-payments/gleam/lawspec.json +14 -3
- package/examples/native-payments/go/lawspec.json +14 -3
- package/examples/native-payments/groovy/lawspec.json +14 -3
- package/examples/native-payments/haskell/lawspec.json +14 -3
- package/examples/native-payments/java/lawspec.json +14 -3
- package/examples/native-payments/javascript/lawspec.json +14 -3
- package/examples/native-payments/kotlin/lawspec.json +14 -3
- package/examples/native-payments/python/lawspec.json +14 -3
- package/examples/native-payments/rust/lawspec.json +14 -3
- package/examples/native-payments/scala/lawspec.json +14 -3
- package/examples/native-payments/swift/lawspec.json +14 -3
- package/examples/native-payments/typescript/lawspec.json +14 -3
- package/examples/packages/orders/lawspec.json +25 -5
- package/examples/packages/orders/orders.lawspec +36 -34
- package/examples/packages/shop-domain/src/domain.lawspec +23 -21
- package/examples/packages/shop-tax-1/src/rates.lawspec +4 -4
- package/examples/packages/shop-tax-2/src/rates.lawspec +5 -4
- package/examples/rc1/authorization-snapshots.lawspec +112 -0
- package/examples/rc1/banner-filenames.lawspec +63 -0
- package/examples/rc1/bit-codec.lawspec +56 -0
- package/examples/rc1/bounded-witness-search.lawspec +144 -0
- package/examples/rc1/conflicting-requirements.lawspec +30 -0
- package/examples/rc1/constructive-witnesses.lawspec +113 -0
- package/examples/rc1/documentary-review.lawspec +42 -0
- package/examples/rc1/empty-domains.lawspec +46 -0
- package/examples/rc1/finite-integer-domains.lawspec +75 -0
- package/examples/rc1/law-metadata.lawspec +29 -0
- package/examples/rc1/native-payments.lawspec +107 -0
- package/examples/rc1/nesting/rrr.lawspec +33 -0
- package/examples/rc1/nesting/rru.lawspec +56 -0
- package/examples/rc1/nesting/rur.lawspec +57 -0
- package/examples/rc1/nesting/ruu.lawspec +77 -0
- package/examples/rc1/nesting/urr.lawspec +52 -0
- package/examples/rc1/nesting/uru.lawspec +72 -0
- package/examples/rc1/nesting/uur.lawspec +73 -0
- package/examples/rc1/nesting/uuu.lawspec +95 -0
- package/examples/rc1/order-workflow.lawspec +126 -0
- package/examples/rc1/parcel-measurements.lawspec +92 -0
- package/examples/rc1/picture-records.lawspec +51 -0
- package/examples/rc1/picture-tuples.lawspec +47 -0
- package/examples/rc1/record-payloads.lawspec +56 -0
- package/examples/rc1/recursive-records.lawspec +64 -0
- package/examples/rc1/refund-conformance.lawspec +44 -0
- package/examples/rc1/refund-policy.lawspec +88 -0
- package/examples/rc1/requirement-composition.lawspec +89 -0
- package/examples/rc1/structural-records.lawspec +53 -0
- package/examples/rc1-authoring.lawspec +56 -0
- package/examples-command.mjs +11 -5
- package/explain.mjs +112 -0
- package/expression-presentation.mjs +333 -0
- package/files.mjs +16 -0
- package/index.d.ts +929 -11
- package/lsp.mjs +231 -0
- package/migrate.mjs +135 -0
- package/migration-bindings.mjs +86 -0
- package/migration-cases.mjs +45 -0
- package/migration-collections.mjs +54 -0
- package/migration-correspondence.mjs +275 -0
- package/migration-generation.mjs +99 -0
- package/migration-laws.mjs +102 -0
- package/migration-records.mjs +166 -0
- package/migration-source.mjs +247 -0
- package/migration-write.mjs +156 -0
- package/native-evidence.mjs +187 -0
- package/native-examples.mjs +8 -1
- package/node-events-reporter.mjs +23 -0
- package/package.json +8 -1
- package/positional-fields.mjs +13 -0
- package/proof.d.ts +35 -0
- package/proof.mjs +174 -0
- package/starter-rc1.lawspec +25 -0
- package/templates.mjs +2 -2
- package/test-command.mjs +107 -35
- package/typed-presentation.mjs +165 -0
package/lsp.mjs
ADDED
|
@@ -0,0 +1,231 @@
|
|
|
1
|
+
// Generated from templates/npm/lsp.mjs by lawspec-dev generate. Do not edit.
|
|
2
|
+
import { readFile, readdir, stat } from 'node:fs/promises';
|
|
3
|
+
import { fileURLToPath, pathToFileURL } from 'node:url';
|
|
4
|
+
import path from 'node:path';
|
|
5
|
+
import { createCompiler } from './api.mjs';
|
|
6
|
+
|
|
7
|
+
export function utf16Position(text, location) {
|
|
8
|
+
const line = Math.max(0, location.line - 1);
|
|
9
|
+
const content = text.split('\n')[line] ?? '';
|
|
10
|
+
let column = 1, character = 0;
|
|
11
|
+
for (const value of content) {
|
|
12
|
+
if (column >= location.column) break;
|
|
13
|
+
column += value === '\t' ? 8 - ((column - 1) % 8) : 1;
|
|
14
|
+
character += value.length;
|
|
15
|
+
}
|
|
16
|
+
return { line, character };
|
|
17
|
+
}
|
|
18
|
+
const endPosition = text => {
|
|
19
|
+
const lines = text.split('\n');
|
|
20
|
+
return { line: lines.length - 1, character: lines.at(-1).length };
|
|
21
|
+
};
|
|
22
|
+
const within = (position, range) => (position.line > range.start.line || position.line === range.start.line && position.character >= range.start.character)
|
|
23
|
+
&& (position.line < range.end.line || position.line === range.end.line && position.character < range.end.character);
|
|
24
|
+
|
|
25
|
+
// A framed JSON-RPC transport keeps UTF-8 byte lengths distinct from editor
|
|
26
|
+
// UTF-16 positions. It accepts fragmented and coalesced messages.
|
|
27
|
+
export async function serveLanguage(input = process.stdin, output = process.stdout, suppliedCompiler) {
|
|
28
|
+
const compiler = suppliedCompiler ?? await createCompiler();
|
|
29
|
+
const documents = new Map();
|
|
30
|
+
let workspace = process.cwd(), buffer = Buffer.alloc(0), queue = Promise.resolve(), shuttingDown = false;
|
|
31
|
+
let last = { sources: [], result: null }, warnMatches = false;
|
|
32
|
+
let finish;
|
|
33
|
+
const ended = new Promise(resolve => { finish = resolve; });
|
|
34
|
+
const send = value => {
|
|
35
|
+
const payload = Buffer.from(JSON.stringify(value));
|
|
36
|
+
output.write(`Content-Length: ${payload.length}\r\n\r\n`);
|
|
37
|
+
output.write(payload);
|
|
38
|
+
};
|
|
39
|
+
async function projectSources() {
|
|
40
|
+
const sources = new Map();
|
|
41
|
+
async function visit(file) {
|
|
42
|
+
const info = await stat(file);
|
|
43
|
+
if (info.isDirectory()) for (const name of (await readdir(file)).sort()) await visit(path.join(file, name));
|
|
44
|
+
else if (file.endsWith('.lawspec')) sources.set(file, { path: file, content: await readFile(file, 'utf8') });
|
|
45
|
+
}
|
|
46
|
+
let config;
|
|
47
|
+
try { config = JSON.parse(await readFile(path.join(workspace, 'lawspec.json'), 'utf8')); }
|
|
48
|
+
catch (error) { if (error.code !== 'ENOENT') throw error; }
|
|
49
|
+
if(config&&(config.version!==2||config.languageProfile!=='1.0-rc.1'))
|
|
50
|
+
throw new Error('The language server requires configuration version 2 and languageProfile 1.0-rc.1; run lawspec migrate --from 0.24 first.');
|
|
51
|
+
for (const entry of config?.sources ?? []) await visit(path.resolve(workspace, entry));
|
|
52
|
+
for (const [uri, document] of documents) sources.set(fileURLToPath(uri), { path: fileURLToPath(uri), content: document.text });
|
|
53
|
+
return [...sources.values()];
|
|
54
|
+
}
|
|
55
|
+
function location(location, sources = last.sources) {
|
|
56
|
+
const source = sources.find(s => s.path === location.file);
|
|
57
|
+
if (!source) return null;
|
|
58
|
+
return { uri: pathToFileURL(source.path).href, position: utf16Position(source.content, location) };
|
|
59
|
+
}
|
|
60
|
+
function span(span) {
|
|
61
|
+
const start = location(span.start ?? span.spanStart), end = location(span.end ?? span.spanEnd);
|
|
62
|
+
return start && end ? { uri: start.uri, range: { start: start.position, end: end.position } } : null;
|
|
63
|
+
}
|
|
64
|
+
async function check() {
|
|
65
|
+
const sources = await projectSources();
|
|
66
|
+
const result = await compiler.check({ sources, languageProfile: '1.0-rc.1', verification: { layers: [] }, ...(warnMatches ? {warnMatches:true} : {}) });
|
|
67
|
+
last = { sources, result };
|
|
68
|
+
for (const [uri, document] of documents) {
|
|
69
|
+
const file = fileURLToPath(uri);
|
|
70
|
+
const diagnostics = [...(result.diagnostics ?? []), ...(warnMatches ? result.warnings ?? [] : [])].filter(d => !d.at || d.at.file === file).map(d => {
|
|
71
|
+
const start = d.at ? utf16Position(document.text, d.at) : { line: 0, character: 0 };
|
|
72
|
+
const content = document.text.split('\n')[start.line] ?? '';
|
|
73
|
+
const end = { ...start, character: Math.min(content.length, start.character + ([...content.slice(start.character)][0]?.length ?? 0)) };
|
|
74
|
+
const range = d.span ? span(d.span)?.range ?? {start,end} : {start,end};
|
|
75
|
+
return { range, severity: d.severity === 'warning' ? 2 : 1, code: d.code, source: 'LawSpec', message: d.message };
|
|
76
|
+
});
|
|
77
|
+
send({ jsonrpc: '2.0', method: 'textDocument/publishDiagnostics', params: { uri, version: document.version, diagnostics } });
|
|
78
|
+
}
|
|
79
|
+
}
|
|
80
|
+
function declarations() {
|
|
81
|
+
const result = last.result;
|
|
82
|
+
if (!result) return [];
|
|
83
|
+
const entries = [];
|
|
84
|
+
for (const unit of result.units ?? []) for (const d of unit.declarations) {
|
|
85
|
+
const origin = d.origin?.kind === 'source' ? span(d.origin.span) : null;
|
|
86
|
+
if (origin) entries.push({ id: d.id, name: d.name, kind: 12, detail: JSON.stringify(d.type), ...origin });
|
|
87
|
+
}
|
|
88
|
+
for (const d of result.dataTypes ?? []) {
|
|
89
|
+
const origin = d.origin?.kind === 'source' ? span(d.origin.span) : null;
|
|
90
|
+
if (origin) entries.push({ id: d.id, name: d.name, kind: 23, detail: 'Type', ...origin });
|
|
91
|
+
}
|
|
92
|
+
for (const law of result.laws ?? []) {
|
|
93
|
+
const origin = location(law.location);
|
|
94
|
+
if (origin) entries.push({ id: law.id, name: law.name, kind: 12, detail: law.description || 'Law', uri: origin.uri,
|
|
95
|
+
range: { start: origin.position, end: { ...origin.position, character: origin.position.character + 3 } } });
|
|
96
|
+
}
|
|
97
|
+
return entries;
|
|
98
|
+
}
|
|
99
|
+
function documentaryLinks() {
|
|
100
|
+
return (last.result?.laws ?? []).flatMap(law => (law.references ?? [])
|
|
101
|
+
.filter(reference => reference?.kind === 'law' || reference?.kind === 'function'));
|
|
102
|
+
}
|
|
103
|
+
function documentaryDeclaration(id) {
|
|
104
|
+
const reference = documentaryLinks().find(reference => reference.target.id === id);
|
|
105
|
+
const target = reference?.target, origin = target && span(target.span);
|
|
106
|
+
return origin ? { id, name: target.name, detail: reference.kind === 'law' ? 'Law' : 'Function', ...origin } : null;
|
|
107
|
+
}
|
|
108
|
+
function uses() {
|
|
109
|
+
const result = last.result;
|
|
110
|
+
if (!result) return [];
|
|
111
|
+
const entries = [];
|
|
112
|
+
function walk(value) {
|
|
113
|
+
if (!value || typeof value !== 'object') return;
|
|
114
|
+
if (value.node?.kind === 'call' && value.origin?.kind === 'source') {
|
|
115
|
+
const origin = span(value.origin.span);
|
|
116
|
+
if (origin) entries.push({ id: value.node.declaration, ...origin });
|
|
117
|
+
}
|
|
118
|
+
for (const child of Object.values(value)) if (typeof child === 'object') {
|
|
119
|
+
if (Array.isArray(child)) child.forEach(walk); else walk(child);
|
|
120
|
+
}
|
|
121
|
+
}
|
|
122
|
+
walk(result.laws); walk(result.definitions);
|
|
123
|
+
for (const reference of documentaryLinks()) {
|
|
124
|
+
const origin = span(reference.target.referenceSpan);
|
|
125
|
+
if (origin) entries.push({ id: reference.target.id, ...origin });
|
|
126
|
+
}
|
|
127
|
+
return entries;
|
|
128
|
+
}
|
|
129
|
+
function selected(params) {
|
|
130
|
+
const candidates = [...uses(), ...declarations()].filter(d => d.uri === params.textDocument.uri && within(params.position, d.range));
|
|
131
|
+
candidates.sort((a, b) => (a.range.end.line - a.range.start.line) - (b.range.end.line - b.range.start.line)
|
|
132
|
+
|| (a.range.end.character - a.range.start.character) - (b.range.end.character - b.range.start.character));
|
|
133
|
+
return candidates[0];
|
|
134
|
+
}
|
|
135
|
+
async function handle(message) {
|
|
136
|
+
const params = message.params ?? {};
|
|
137
|
+
let result = null;
|
|
138
|
+
switch (message.method) {
|
|
139
|
+
case 'initialize':
|
|
140
|
+
if (params.initializationOptions?.warnMatches !== undefined && typeof params.initializationOptions.warnMatches !== 'boolean')
|
|
141
|
+
throw new Error('warnMatches must be a Boolean');
|
|
142
|
+
warnMatches = params.initializationOptions?.warnMatches ?? false;
|
|
143
|
+
workspace = params.rootUri ? fileURLToPath(params.rootUri) : params.rootPath ?? workspace;
|
|
144
|
+
result = { capabilities: { textDocumentSync: 1, positionEncoding: 'utf-16', documentFormattingProvider: true,
|
|
145
|
+
documentSymbolProvider: true, hoverProvider: true, definitionProvider: true, referencesProvider: true },
|
|
146
|
+
serverInfo: { name: 'LawSpec', version: '1.0-rc.1' } };
|
|
147
|
+
break;
|
|
148
|
+
case 'initialized': break;
|
|
149
|
+
case 'workspace/didChangeConfiguration': {
|
|
150
|
+
const next = params.settings?.lawspec?.warnMatches;
|
|
151
|
+
if (next !== undefined && typeof next !== 'boolean') throw new Error('lawspec.warnMatches must be a Boolean');
|
|
152
|
+
warnMatches = next ?? false;
|
|
153
|
+
await check(); break;
|
|
154
|
+
}
|
|
155
|
+
case 'shutdown': shuttingDown = true; break;
|
|
156
|
+
case 'exit': input.pause(); finish(); return;
|
|
157
|
+
case 'textDocument/didOpen': documents.set(params.textDocument.uri, params.textDocument); await check(); break;
|
|
158
|
+
case 'textDocument/didChange': {
|
|
159
|
+
const document = documents.get(params.textDocument.uri);
|
|
160
|
+
if (params.contentChanges.some(change => change.range)) throw new Error('LawSpec requires full-document synchronization');
|
|
161
|
+
if (document && params.contentChanges.length) documents.set(params.textDocument.uri, {
|
|
162
|
+
...document, text: params.contentChanges.at(-1).text, version: params.textDocument.version });
|
|
163
|
+
await check(); break;
|
|
164
|
+
}
|
|
165
|
+
case 'textDocument/didClose': documents.delete(params.textDocument.uri);
|
|
166
|
+
send({ jsonrpc: '2.0', method: 'textDocument/publishDiagnostics', params: { uri: params.textDocument.uri, diagnostics: [] } }); break;
|
|
167
|
+
case 'textDocument/formatting': {
|
|
168
|
+
const document = documents.get(params.textDocument.uri);
|
|
169
|
+
if (!document) { result = []; break; }
|
|
170
|
+
const sourcePath = fileURLToPath(params.textDocument.uri);
|
|
171
|
+
const response = await compiler.format({ sources: await projectSources(), languageProfile: '1.0-rc.1', verification: { layers: [] } });
|
|
172
|
+
if (response.diagnostics?.length) { result = []; break; }
|
|
173
|
+
const formatted = response.formattedSources.find(s => s.path === sourcePath);
|
|
174
|
+
result = formatted && formatted.content !== document.text
|
|
175
|
+
? [{ range: { start: { line: 0, character: 0 }, end: endPosition(document.text) }, newText: formatted.content }] : [];
|
|
176
|
+
break;
|
|
177
|
+
}
|
|
178
|
+
case 'textDocument/documentSymbol': result = declarations().filter(d => d.uri === params.textDocument.uri)
|
|
179
|
+
.map(d => ({ name: d.name, detail: d.detail, kind: d.kind, range: d.range, selectionRange: d.range })); break;
|
|
180
|
+
case 'textDocument/hover': {
|
|
181
|
+
const use = selected(params), declaration = use && (declarations().find(d => d.id === use.id) ?? documentaryDeclaration(use.id));
|
|
182
|
+
result = declaration ? { contents: { kind: 'plaintext', value: `${declaration.name}\n${declaration.detail}` }, range: use.range } : null;
|
|
183
|
+
break;
|
|
184
|
+
}
|
|
185
|
+
case 'textDocument/definition': {
|
|
186
|
+
const use = selected(params), declaration = use && (declarations().find(d => d.id === use.id) ?? documentaryDeclaration(use.id));
|
|
187
|
+
result = declaration ? { uri: declaration.uri, range: declaration.range } : null;
|
|
188
|
+
break;
|
|
189
|
+
}
|
|
190
|
+
case 'textDocument/references': {
|
|
191
|
+
const use = selected(params);
|
|
192
|
+
const declared = use && (declarations().find(d => d.id === use.id) ?? documentaryDeclaration(use.id));
|
|
193
|
+
result = use ? [...uses(), ...(params.context?.includeDeclaration && declared ? [declared] : [])].filter(d => d.id === use.id)
|
|
194
|
+
.map(d => ({ uri: d.uri, range: d.range })) : [];
|
|
195
|
+
break;
|
|
196
|
+
}
|
|
197
|
+
case '$/cancelRequest': break;
|
|
198
|
+
default: if (message.id !== undefined) send({ jsonrpc: '2.0', id: message.id, error: { code: -32601, message: 'Method not found' } }); return;
|
|
199
|
+
}
|
|
200
|
+
if (message.id !== undefined) send({ jsonrpc: '2.0', id: message.id, result });
|
|
201
|
+
}
|
|
202
|
+
input.on('data', data => {
|
|
203
|
+
buffer = Buffer.concat([buffer, data]);
|
|
204
|
+
for (;;) {
|
|
205
|
+
const headerEnd = buffer.indexOf('\r\n\r\n');
|
|
206
|
+
if (headerEnd < 0) break;
|
|
207
|
+
const length = /^Content-Length:\s*(\d+)\s*$/im.exec(buffer.subarray(0, headerEnd).toString());
|
|
208
|
+
if (!length || Number(length[1]) > 16 * 1024 * 1024) {
|
|
209
|
+
send({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Invalid Content-Length' } }); input.pause(); finish(); break;
|
|
210
|
+
}
|
|
211
|
+
const end = headerEnd + 4 + Number(length[1]);
|
|
212
|
+
if (buffer.length < end) break;
|
|
213
|
+
const body = buffer.subarray(headerEnd + 4, end); buffer = buffer.subarray(end);
|
|
214
|
+
queue = queue.then(async () => {
|
|
215
|
+
let message;
|
|
216
|
+
try { message = JSON.parse(body.toString()); }
|
|
217
|
+
catch { send({ jsonrpc: '2.0', id: null, error: { code: -32700, message: 'Parse error' } }); return; }
|
|
218
|
+
try {
|
|
219
|
+
if (shuttingDown && !['exit', 'shutdown'].includes(message.method)) throw new Error('Server is shutting down');
|
|
220
|
+
await handle(message);
|
|
221
|
+
} catch (error) {
|
|
222
|
+
if (message.id !== undefined) send({ jsonrpc: '2.0', id: message.id, error: { code: -32603, message: error.message } });
|
|
223
|
+
else send({ jsonrpc: '2.0', method: 'window/logMessage', params: { type: 1, message: error.message } });
|
|
224
|
+
}
|
|
225
|
+
});
|
|
226
|
+
}
|
|
227
|
+
});
|
|
228
|
+
input.once('end', finish);
|
|
229
|
+
await ended;
|
|
230
|
+
await queue;
|
|
231
|
+
}
|
package/migrate.mjs
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
1
|
+
// Generated from templates/npm/migrate.mjs by lawspec-dev generate. Do not edit.
|
|
2
|
+
// Migration starts from the typed legacy baseline. A report is not permission
|
|
3
|
+
// to write an unvalidated transformation or silently alter native payload APIs.
|
|
4
|
+
import {planLegacySourceEdits} from './migration-laws.mjs';
|
|
5
|
+
import {compareMigrationSnapshots} from './migration-correspondence.mjs';
|
|
6
|
+
import {planNativeBindings} from './migration-bindings.mjs';
|
|
7
|
+
import {planMigrationGeneration} from './migration-generation.mjs';
|
|
8
|
+
|
|
9
|
+
export const legacyLawLayers = ['proof', 'exhaustive', 'property', 'examples', 'runtime', 'model'];
|
|
10
|
+
export async function migrationReport(compiler, config, input) {
|
|
11
|
+
if(config?.version!==1||!Array.isArray(config.targets))return {from:'0.24',to:'1.0-rc.1',validated:false,
|
|
12
|
+
diagnostics:[{code:'migration-configuration',message:'Migration requires a version 1 configuration with a targets array.',at:null}]};
|
|
13
|
+
const {nativeBindings:inputBindings,...sourceInput}=input;
|
|
14
|
+
const legacyInput={...sourceInput,schemaVersion:5,languageProfile:'1.0-rc.1',from:'0.24'};
|
|
15
|
+
const baseline = await compiler.migrationBaseline({...legacyInput,verification:{layers:[...legacyLawLayers]}});
|
|
16
|
+
if (baseline.diagnostics?.length) return { from: '0.24', to: '1.0-rc.1', validated: false, diagnostics: baseline.diagnostics };
|
|
17
|
+
if (!Array.isArray(baseline.sourceSyntax)) throw new Error('The compiler did not return the checked source syntax inventory');
|
|
18
|
+
const packageInputs = input.packages ?? [];
|
|
19
|
+
const allSources = [...input.sources, ...packageInputs.flatMap(pkg => pkg.sources)];
|
|
20
|
+
const files = new Set(allSources.map(source => source.path));
|
|
21
|
+
const owned = origin => origin?.kind === 'source' && files.has(origin.span.start.file);
|
|
22
|
+
const declarations = baseline.units.flatMap(unit => unit.declarations.filter(d => owned(d.origin)).map(d => ({ unit: unit.id, ...d })));
|
|
23
|
+
const definitions = baseline.definitions.filter(d => declarations.some(declaration => declaration.id === d.id));
|
|
24
|
+
const laws = baseline.laws.filter(law => files.has(law.location.file));
|
|
25
|
+
const types = baseline.dataTypes.filter(d => owned(d.origin));
|
|
26
|
+
const payloads = types.flatMap(type => type.constructors.filter(c => c.fields.length).map(constructor => ({
|
|
27
|
+
type: type.id, constructor: constructor.id, fields: constructor.fields,
|
|
28
|
+
change: type.constructors.length===1 && constructor.name===type.name
|
|
29
|
+
? 'declare explicit nominal record syntax and preserve its constructor field binding'
|
|
30
|
+
: constructor.fields.length > 1 ? 'group fields into one explicit record payload and reconcile its native field binding' : 'declare an explicit typed payload and reconcile its native field binding',
|
|
31
|
+
})));
|
|
32
|
+
let sourcePreview;
|
|
33
|
+
try {
|
|
34
|
+
if(files.size !== allSources.length) throw new Error('Project and package source paths must be unique.');
|
|
35
|
+
const edited = planLegacySourceEdits(allSources,baseline,baseline.sourceSyntax,baseline.sourceFields);
|
|
36
|
+
const edits = new Map(edited.map(source => [source.path,source]));
|
|
37
|
+
sourcePreview = {scope:'checked computations, nominal records and alternative payloads, ordered collection names, unsigned integers, cases, laws, explicit universal scopes and expectation-first tables',
|
|
38
|
+
sources:input.sources.map(source => edits.get(source.path)),
|
|
39
|
+
packages:packageInputs.map(pkg => ({...pkg,sources:pkg.sources.map(source => edits.get(source.path))})),diagnostics:[]};
|
|
40
|
+
} catch (error) {
|
|
41
|
+
sourcePreview = {scope:'checked computations, nominal records and alternative payloads, ordered collection names, unsigned integers, cases, laws, explicit universal scopes and expectation-first tables',sources:[],
|
|
42
|
+
diagnostics:[{code:'migration-source',message:error.message,at:null}]};
|
|
43
|
+
}
|
|
44
|
+
const migratedSources=sourcePreview.sources.map(({path,content})=>({path,content}));
|
|
45
|
+
const migratedPackages=(sourcePreview.packages??[]).map(pkg=>({...pkg,
|
|
46
|
+
sources:pkg.sources.map(({path,content})=>({path,content}))}));
|
|
47
|
+
const migratedContext=packageInputs.length?{packages:migratedPackages}:{};
|
|
48
|
+
if (!sourcePreview.diagnostics.length) {
|
|
49
|
+
const checked = await compiler.check({...sourceInput,...migratedContext,schemaVersion:5,languageProfile:'1.0-rc.1',verification:{layers:[]},migrationSnapshot:true,
|
|
50
|
+
sources:migratedSources});
|
|
51
|
+
sourcePreview.canonicalCheck = {status:checked.diagnostics.length?'rejected':'accepted',diagnostics:checked.diagnostics,
|
|
52
|
+
intrinsicDefinitionChecks:checked.verification?.intrinsicDefinitionChecks===true,
|
|
53
|
+
lawVerification:'no-selected-checks',coreSnapshot:checked.migrationSemantics??{status:'unavailable',reason:'The compiler did not return a Core migration snapshot.'}};
|
|
54
|
+
} else sourcePreview.canonicalCheck = {status:'unavailable',diagnostics:sourcePreview.diagnostics};
|
|
55
|
+
let payloadComparison={status:'unavailable',reason:'The canonical preview or compiler-side payload comparison is unavailable.'};
|
|
56
|
+
if(sourcePreview.canonicalCheck.status==='accepted'&&typeof compiler.migrationComparison==='function') {
|
|
57
|
+
const compared=await compiler.migrationComparison({...sourceInput,schemaVersion:5,languageProfile:'1.0-rc.1',from:'0.24',verification:{layers:[]},
|
|
58
|
+
migrated:{...sourceInput,...migratedContext,schemaVersion:5,languageProfile:'1.0-rc.1',verification:{layers:[]},
|
|
59
|
+
sources:migratedSources}});
|
|
60
|
+
payloadComparison=compared.migrationComparison??{status:'unavailable',
|
|
61
|
+
reason:'The compiler did not admit both inputs for payload comparison.',diagnostics:compared.diagnostics};
|
|
62
|
+
}
|
|
63
|
+
const correspondence={...compareMigrationSnapshots(baseline.migrationSemantics,sourcePreview.canonicalCheck?.coreSnapshot,
|
|
64
|
+
payloadComparison.executableTransport,payloadComparison.definitionTemplates,payloadComparison.lawTemplates,payloadComparison.sourceUnits),
|
|
65
|
+
payloads:payloadComparison};
|
|
66
|
+
const bindingPreview=sourcePreview.canonicalCheck.status==='accepted' ?
|
|
67
|
+
await planNativeBindings(compiler,config,input,migratedSources,
|
|
68
|
+
baseline.migrationSemantics,sourcePreview.canonicalCheck.coreSnapshot,migratedContext) :
|
|
69
|
+
{status:'not-established',scope:'explicit native binding configuration',
|
|
70
|
+
configurationCount:config.targets.length+(input.nativeBindings!==undefined?1:0),targets:[],
|
|
71
|
+
proposedTargets:config.targets,reason:'Native binding planning requires an admitted canonical source preview.'};
|
|
72
|
+
correspondence.nativeBindings={status:bindingPreview.status,scope:bindingPreview.scope,
|
|
73
|
+
configurationCount:bindingPreview.configurationCount};
|
|
74
|
+
const generationPreview=await planMigrationGeneration(compiler,config,{...input,generation:baseline.generation},
|
|
75
|
+
migratedSources,baseline.migrationSemantics,
|
|
76
|
+
sourcePreview.canonicalCheck.coreSnapshot,bindingPreview,migratedContext);
|
|
77
|
+
correspondence.targetGeneration={status:generationPreview.status,scope:generationPreview.scope,
|
|
78
|
+
configurationCount:generationPreview.configurationCount};
|
|
79
|
+
correspondence.nativeBoundary=generationPreview.nativeBoundary;
|
|
80
|
+
const pending=[
|
|
81
|
+
['program','Complete checked Core correspondence has not been established.'],
|
|
82
|
+
['definitionPlane','Checked definition and contract correspondence has not been established.'],
|
|
83
|
+
['lawBodies','Complete policy-erased Core correspondence has not been established.'],
|
|
84
|
+
['sourceTemplates','Complete checked source-template correspondence has not been established.'],
|
|
85
|
+
['nativeBindings','Native constructor, field and representation bindings require project-wide correspondence.'],
|
|
86
|
+
];
|
|
87
|
+
const domainPending=correspondence.domainPolicies.status!=='matched'||
|
|
88
|
+
correspondence.sourceTemplates.domainPolicies?.status!=='matched';
|
|
89
|
+
const sourceMatched=sourcePreview.canonicalCheck.status==='accepted'&&
|
|
90
|
+
sourcePreview.canonicalCheck.intrinsicDefinitionChecks===true&&sourcePreview.diagnostics.length===0&&
|
|
91
|
+
!domainPending&&pending.every(([name])=>correspondence[name].status==='matched');
|
|
92
|
+
const count=generationPreview.configurationCount;
|
|
93
|
+
const targetsMatched=count===0 ? generationPreview.status==='not-requested'&&
|
|
94
|
+
generationPreview.nativeBoundary.status==='not-requested'&&generationPreview.targets.length===0 :
|
|
95
|
+
generationPreview.status==='accepted'&&generationPreview.nativeBoundary.status==='matched'&&
|
|
96
|
+
generationPreview.targets.length===count&&generationPreview.targets.every(row=>row.status==='accepted'&&
|
|
97
|
+
row.nativeBoundary.status==='matched');
|
|
98
|
+
const validated=sourceMatched&&targetsMatched&&bindingPreview.configurationCount===count;
|
|
99
|
+
const assumptions=['existing compiler validation, transport and target emitters',
|
|
100
|
+
'unchanged native implementations under their original binding assumptions'];
|
|
101
|
+
correspondence.generatedBehavior={status:count===0?'not-requested':validated?
|
|
102
|
+
'matched-under-existing-assumptions':'not-established',
|
|
103
|
+
scope:'preservation of checked source semantics and configured native interfaces; no native execution',
|
|
104
|
+
assumptions,nativeExecution:'not-performed',nativeConformance:'not-established',
|
|
105
|
+
lawVerification:'not-established-by-migration'};
|
|
106
|
+
correspondence.status=validated?'matched-under-existing-assumptions':'not-established';
|
|
107
|
+
correspondence.scope='complete checked source migration and configured target interfaces';
|
|
108
|
+
return {
|
|
109
|
+
from: '0.24', to: '1.0-rc.1', validated, diagnostics: [],
|
|
110
|
+
validation:{status:validated?'validated-under-existing-assumptions':'not-established',
|
|
111
|
+
scope:'all supplied project sources, configuration and configured targets',assumptions,
|
|
112
|
+
nativeConformance:'not-established',lawVerification:'not-established-by-migration'},
|
|
113
|
+
proposedConfiguration: { ...config, targets:bindingPreview.proposedTargets, version: 2, languageProfile: '1.0-rc.1', verification: { layers: [...legacyLawLayers] } },
|
|
114
|
+
baseline: { declarations, definitions, laws, types, obligations: baseline.evidence, sourceSyntax:baseline.sourceSyntax,sourceFields:baseline.sourceFields,
|
|
115
|
+
coreSnapshot:baseline.migrationSemantics??{status:'unavailable',reason:'The compiler did not return a Core migration snapshot.'} },
|
|
116
|
+
sourcePreview,
|
|
117
|
+
correspondence,
|
|
118
|
+
domainPolicyChanges: laws.map(law => ({law:law.id,from:law.inputDomain,to:'universal',
|
|
119
|
+
requirement:'Preserve domain correspondence, including empty and dependent domains, when validating this migration.'})),
|
|
120
|
+
constructorChanges: payloads,
|
|
121
|
+
nativeBindings: config.targets.map(target => ({ target: target.language, bindings: target.nativeBindings ?? null })),
|
|
122
|
+
bindingPreview,
|
|
123
|
+
generationPreview,
|
|
124
|
+
blockers: [...pending.filter(([name])=>correspondence[name].status!=='matched').map(([,reason])=>reason),
|
|
125
|
+
...bindingPreview.targets.filter(target=>target.status!=='matched').map(target=>'Native bindings for '+(target.target||'input')+': '+target.reason),
|
|
126
|
+
...generationPreview.targets.filter(target=>target.status!=='accepted').map(target=>'Target generation for '+(target.target||'input')+': '+target.reason),
|
|
127
|
+
...generationPreview.targets.filter(target=>target.status==='accepted'&&target.nativeBoundary.status!=='matched')
|
|
128
|
+
.map(target=>'Native boundary for '+(target.target||'input')+': '+target.nativeBoundary.reason),
|
|
129
|
+
...(domainPending ? ['Legacy nonempty input-domain handling and canonical universal quantification require explicit correspondence checks; no empty-domain equivalence is assumed.'] : []),
|
|
130
|
+
...(sourcePreview.canonicalCheck.status==='rejected' ? ['The partial preview does not yet pass canonical compilation; inspect sourcePreview.canonicalCheck.diagnostics.'] : []),
|
|
131
|
+
...sourcePreview.diagnostics.map(diagnostic => 'Source preview unavailable: ' + diagnostic.message),
|
|
132
|
+
...(!sourcePreview.canonicalCheck.intrinsicDefinitionChecks?['Mandatory definition validation was not established.']:[])],
|
|
133
|
+
filesWritten: [],
|
|
134
|
+
};
|
|
135
|
+
}
|
|
@@ -0,0 +1,86 @@
|
|
|
1
|
+
// Generated from templates/npm/migration-bindings.mjs by lawspec-dev generate. Do not edit.
|
|
2
|
+
// Native configuration correspondence is independent of external execution.
|
|
3
|
+
// The compiler owns payload adaptation and native binding resolution.
|
|
4
|
+
import {targets} from './templates.mjs';
|
|
5
|
+
import {createHash} from 'node:crypto';
|
|
6
|
+
|
|
7
|
+
const fingerprints=['programDigest','definitionPlaneDigest','lawBodiesDigest'];
|
|
8
|
+
const templates=['declarationsDigest','definitionTemplatesDigest','lawTemplatesDigest','lawBodiesDigest'];
|
|
9
|
+
const canonical=value=>Array.isArray(value)?value.map(canonical):value&&typeof value==='object'
|
|
10
|
+
?Object.fromEntries(Object.keys(value).sort().map(key=>[key,canonical(value[key])])):value;
|
|
11
|
+
export const bindingDigest=value=>createHash('sha256').update(JSON.stringify(canonical(value))).digest('hex');
|
|
12
|
+
const digest=value=>typeof value==='string'&&/^[0-9a-f]{64}$/.test(value);
|
|
13
|
+
const equal=(a,b)=>{
|
|
14
|
+
if(a===b)return true;
|
|
15
|
+
if(!a||!b||typeof a!=='object'||typeof b!=='object'||Array.isArray(a)!==Array.isArray(b))return false;
|
|
16
|
+
const left=Object.keys(a).sort(),right=Object.keys(b).sort();
|
|
17
|
+
return left.length===right.length&&left.every((key,i)=>key===right[i]&&equal(a[key],b[key]));
|
|
18
|
+
};
|
|
19
|
+
const pending=reason=>({status:'not-established',reason});
|
|
20
|
+
const bindingObligations=rows=>Array.isArray(rows)&&rows.every(row=>row&&typeof row.owner==='string'&&
|
|
21
|
+
typeof row.declaration==='string'&&row.claim===null&&
|
|
22
|
+
(row.stage==='binding' ? row.status==='runtime-checked' :
|
|
23
|
+
['codec','generator','native-function'].includes(row.stage)&&row.status==='assumed'));
|
|
24
|
+
|
|
25
|
+
|
|
26
|
+
export function checkBindingProposal(before,after,requested,target,evidence) {
|
|
27
|
+
if(evidence?.status==='unavailable'&&typeof evidence.reason==='string')return pending(evidence.reason);
|
|
28
|
+
const unavailable='The compiler did not return a complete binding proposal for these sources, bindings, target and machine width.';
|
|
29
|
+
if(before?.status!=='available'||after?.status!=='available'||before.machineBits!==after.machineBits||
|
|
30
|
+
evidence?.version!==1||evidence.algorithm!=='sha256'||evidence.target!==target||
|
|
31
|
+
evidence.machineBits!==before.machineBits||evidence.originalsUnchanged!==true||
|
|
32
|
+
!equal(evidence.inputBindings,requested??{})||
|
|
33
|
+
!fingerprints.every(field=>digest(before[field])&&digest(after[field])&&
|
|
34
|
+
evidence.before?.[field]===before[field]&&evidence.after?.[field]===after[field])||
|
|
35
|
+
!templates.every(field=>digest(before.sourceTemplates?.[field])&&digest(after.sourceTemplates?.[field])&&
|
|
36
|
+
evidence.sourceTemplates?.before?.[field]===before.sourceTemplates[field]&&
|
|
37
|
+
evidence.sourceTemplates?.after?.[field]===after.sourceTemplates[field])) return pending(unavailable);
|
|
38
|
+
if(evidence.obligations?.status!=='matched'||!bindingObligations(evidence.obligations.before)||
|
|
39
|
+
!equal(evidence.obligations.before,evidence.obligations.after)||
|
|
40
|
+
evidence.status!=='matched'||evidence.beforeValidated!==true||evidence.afterValidated!==true||
|
|
41
|
+
evidence.proposalComplete!==true||evidence.bindings?.status!=='matched'||
|
|
42
|
+
!digest(evidence.originalBindingsDigest)||!digest(evidence.bindings.before)||evidence.bindings.before!==evidence.bindings.after||
|
|
43
|
+
!evidence.proposedNativeBindings||typeof evidence.proposedNativeBindings!=='object'||
|
|
44
|
+
Array.isArray(evidence.proposedNativeBindings)||!Array.isArray(evidence.requirements)||evidence.requirements.length||
|
|
45
|
+
evidence.nativeConformance!=='not-established'||evidence.targetGeneration!=='not-established'||
|
|
46
|
+
evidence.lawVerification!=='not-established-by-binding-correspondence'||
|
|
47
|
+
bindingDigest(evidence.proposedNativeBindings)!==evidence.bindings.after)
|
|
48
|
+
return pending(evidence.requirements?.join(' ')||evidence.reason||'Native binding adaptation remains incomplete.');
|
|
49
|
+
return {status:'matched',basis:'compiler-checked-native-binding-proposal',
|
|
50
|
+
scope:'explicit binding configuration; external behavior and generated APIs remain separate'};
|
|
51
|
+
}
|
|
52
|
+
|
|
53
|
+
export async function planNativeBindings(compiler,config,input,sources,before,after,migratedContext={}) {
|
|
54
|
+
const scopes=config.targets.map((target,index)=>({target,index,language:target.language,
|
|
55
|
+
bindings:target.nativeBindings}));
|
|
56
|
+
if(input.nativeBindings!==undefined)
|
|
57
|
+
scopes.push({index:null,language:input.target??'',bindings:input.nativeBindings});
|
|
58
|
+
const rows=[];
|
|
59
|
+
for(const scope of scopes) {
|
|
60
|
+
const {language,bindings,index}=scope;
|
|
61
|
+
if(language&&!targets.includes(language)) {
|
|
62
|
+
rows.push({target:language,index,...pending('Unknown migration target: '+language)});continue;
|
|
63
|
+
}
|
|
64
|
+
if(typeof compiler.migrationBindings!=='function') {
|
|
65
|
+
rows.push({target:language,index,...pending('This compiler does not expose checked native binding migration.')});continue;
|
|
66
|
+
}
|
|
67
|
+
const options={...input,schemaVersion:5,languageProfile:'1.0-rc.1',verification:{layers:[]}};
|
|
68
|
+
const {nativeBindings:ignored,...canonical}=options;
|
|
69
|
+
const result=await compiler.migrationBindings({...options,from:'0.24',target:language,
|
|
70
|
+
nativeBindings:bindings??{},migrated:{...canonical,...migratedContext,sources}});
|
|
71
|
+
const evidence=result.migrationBindings;
|
|
72
|
+
const checked=result.diagnostics?.length ? pending(result.diagnostics.map(item=>item.message).join(' ')) :
|
|
73
|
+
checkBindingProposal(before,after,bindings,language,evidence);
|
|
74
|
+
rows.push({target:language,index,...checked,evidence,
|
|
75
|
+
diagnostics:result.diagnostics??[],...(checked.status==='matched'?{proposedNativeBindings:evidence.proposedNativeBindings}:{})});
|
|
76
|
+
}
|
|
77
|
+
const matched=rows.every(row=>row.status==='matched');
|
|
78
|
+
return {status:matched?'matched':'not-established',
|
|
79
|
+
scope:'every configured explicit native binding request; native execution and generated APIs remain separate',
|
|
80
|
+
configurationCount:rows.length,targets:rows,
|
|
81
|
+
proposedTargets:config.targets.map((target,index)=>{
|
|
82
|
+
const row=rows.find(row=>row.index===index);
|
|
83
|
+
return row?.status==='matched'&&target.nativeBindings!==undefined
|
|
84
|
+
? {...target,nativeBindings:row.proposedNativeBindings}:{...target};
|
|
85
|
+
})};
|
|
86
|
+
}
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
// Generated from templates/npm/migration-cases.mjs by lawspec-dev generate. Do not edit.
|
|
2
|
+
// Selection edits use actual case/branch ranges, including nested selections
|
|
3
|
+
// in the selected expression. No contextual identifier is treated as a block.
|
|
4
|
+
export function planLegacyCases(document,nodes) {
|
|
5
|
+
const contains = (outer,inner) => outer.start <= inner.start && inner.end <= outer.end;
|
|
6
|
+
const replace = (token,content,reason) => {
|
|
7
|
+
if (!token) throw new Error('Checked case has no token for '+reason);
|
|
8
|
+
document.edit(token.start,token.end,content,reason);
|
|
9
|
+
};
|
|
10
|
+
const cases = nodes.filter(node=>node.kind==='case');
|
|
11
|
+
for (const selected of cases) {
|
|
12
|
+
const branches = nodes.filter(node=>node.kind==='case-branch' && contains(selected,node) &&
|
|
13
|
+
!cases.some(inner=>inner!==selected && contains(selected,inner) && contains(inner,node)));
|
|
14
|
+
if (!branches.length) throw new Error('Checked case has no source branches');
|
|
15
|
+
const tokens = document.code(selected.start,selected.end);
|
|
16
|
+
const prefix = document.code(selected.start,Math.min(...branches.map(branch=>branch.start)));
|
|
17
|
+
if (tokens[0]?.text!=='match' || prefix.at(-1)?.text!=='with' || tokens.at(-1)?.text!=='end')
|
|
18
|
+
throw new Error('Checked case has no legacy delimiters');
|
|
19
|
+
replace(tokens[0],'first matching case of','case opener');
|
|
20
|
+
replace(prefix.at(-1),':','case delimiter');
|
|
21
|
+
replace(tokens.at(-1),'end case','case closer');
|
|
22
|
+
for (const branch of branches) {
|
|
23
|
+
const tokens = document.code(branch.start,branch.end);
|
|
24
|
+
const arrow = tokens.find(token=>token.text==='->');
|
|
25
|
+
if (tokens[0]?.text!=='|' || !arrow) throw new Error('Checked case branch has no legacy delimiters');
|
|
26
|
+
if (nodes.some(node=>node.kind==='expression.name' && node.name==='it' &&
|
|
27
|
+
node.start>=arrow.end && contains(branch,node)))
|
|
28
|
+
throw new Error('A legacy case branch referring to it needs an explicit rename before introducing scoped it');
|
|
29
|
+
replace(tokens[0],'when','case branch');
|
|
30
|
+
replace(arrow,'then','case branch delimiter');
|
|
31
|
+
}
|
|
32
|
+
}
|
|
33
|
+
// Payload-free alternatives keep their parameters and index equations.
|
|
34
|
+
// Their header/closer edits do not establish semantic or native correspondence;
|
|
35
|
+
// the compiler still has to admit and compare both complete inputs.
|
|
36
|
+
for (const type of nodes.filter(node=>node.kind==='declaration.type')) {
|
|
37
|
+
if (nodes.some(node=>node.kind==='constructor-field' && contains(type,node))) continue;
|
|
38
|
+
const tokens = document.code(type.start,type.end);
|
|
39
|
+
const delimiter = tokens.find(token=>token.text==='is');
|
|
40
|
+
if (tokens[0]?.text!=='type' || !delimiter || tokens.at(-1)?.text!=='end')
|
|
41
|
+
throw new Error('Checked alternative type has no legacy delimiters');
|
|
42
|
+
replace(delimiter,'is one of','alternative type delimiter');
|
|
43
|
+
replace(tokens.at(-1),'end type','type closer');
|
|
44
|
+
}
|
|
45
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
// Generated from templates/npm/migration-collections.mjs by lawspec-dev generate. Do not edit.
|
|
2
|
+
// Names are changed only after the existing compiler has resolved their
|
|
3
|
+
// namespace or free-reference identity. Lexical bindings are never guessed.
|
|
4
|
+
const orderedSet='lawspec.collections::type::Set';
|
|
5
|
+
const operations=new Map(['Of','Member','Insert','Remove','Union','Intersection','Difference']
|
|
6
|
+
.map(suffix=>['lawspec.collections::set'+suffix,'sortedSet'+suffix]));
|
|
7
|
+
const numericNames=new Map([['BigUInt','Whole'],['Natural','Whole'],['BigInt','Integer']]);
|
|
8
|
+
|
|
9
|
+
export function planLegacyCollectionNames(document,source) {
|
|
10
|
+
const {nodes,bindings,references}=source;
|
|
11
|
+
if (!Array.isArray(bindings)||!Array.isArray(references))
|
|
12
|
+
throw new Error('Collection migration requires checked namespaces and free references');
|
|
13
|
+
const contains=(outer,inner)=>outer.start<=inner.start&&inner.end<=outer.end;
|
|
14
|
+
const lookup=(namespace,name)=>bindings.find(binding=>binding.namespace===namespace&&binding.name===name);
|
|
15
|
+
const rename=(range,name,replacement,reason)=>{
|
|
16
|
+
const tokens=document.code(range.start,range.end);
|
|
17
|
+
if (tokens.map(token=>token.text).join('')!==name)
|
|
18
|
+
throw new Error('Checked name does not match its original source tokens: '+name);
|
|
19
|
+
const last=tokens.at(-1);
|
|
20
|
+
document.edit(last.start,last.end,replacement,reason);
|
|
21
|
+
};
|
|
22
|
+
for (const node of nodes.filter(node=>node.kind==='type-name')) {
|
|
23
|
+
const refinement=lookup('refinement',node.name);
|
|
24
|
+
const builtinNatural=node.name==='Natural'&&source.builtinNatural&&refinement?.target==='Natural';
|
|
25
|
+
if (numericNames.has(node.name) && !lookup('type',node.name) && (!refinement||builtinNatural))
|
|
26
|
+
rename(node,node.name,numericNames.get(node.name),'exact numeric type name');
|
|
27
|
+
if (lookup('type',node.name)?.target===orderedSet) {
|
|
28
|
+
if (lookup('refinement',node.name)) throw new Error('A collection type and refinement share a source spelling: '+node.name);
|
|
29
|
+
rename(node,node.name,'SortedSet','ordered set type name');
|
|
30
|
+
}
|
|
31
|
+
}
|
|
32
|
+
for (const node of nodes.filter(node=>node.kind==='type-parameter-kind'&&node.name==='Natural'))
|
|
33
|
+
rename(node,node.name,'Whole','zero-inclusive index kind');
|
|
34
|
+
for (const reference of references) {
|
|
35
|
+
const replacement=operations.get(reference.declaration);
|
|
36
|
+
if (!replacement) continue;
|
|
37
|
+
const range=document.range({kind:'source',span:reference.span});
|
|
38
|
+
if (!range) throw new Error('Checked collection reference belongs to another source');
|
|
39
|
+
rename(range,reference.name,replacement,'ordered set operation');
|
|
40
|
+
}
|
|
41
|
+
for (const item of nodes.filter(node=>['import-item','export-item'].includes(node.kind))) {
|
|
42
|
+
if (item.name.startsWith('`')) continue;
|
|
43
|
+
let name=item.name;
|
|
44
|
+
if (item.kind==='import-item') {
|
|
45
|
+
const parent=nodes.find(node=>node.kind==='import'&&contains(node,item));
|
|
46
|
+
const alias=parent&&nodes.find(node=>node.kind==='import-alias'&&node.start===parent.start&&node.end===parent.end);
|
|
47
|
+
if (!alias) throw new Error('Checked import item has no parsed alias');
|
|
48
|
+
name=alias.name+'.'+name;
|
|
49
|
+
}
|
|
50
|
+
const type=lookup('type',name),value=lookup('value',name);
|
|
51
|
+
const replacement=type?.target===orderedSet?'SortedSet':operations.get(value?.declaration);
|
|
52
|
+
if (replacement) rename(item,item.name,replacement,'ordered set import or export');
|
|
53
|
+
}
|
|
54
|
+
}
|