// Stage 7: speco as a lens on pseudo's contracts. extractSpec reads the contracts out of pseudo; weave in // replace mode writes a speco into pseudo in place of what is there; reconcileSpec keeps the claims that have // lost their routine or loop. The laws below make sync settle after one pass and never lose a contract. import test from 'node:test'; import assert from 'node:assert/strict'; import { programs } from './helpers/sync-programs.mjs'; import { studyOf } from '../dist/services/pseudo.js'; import { parseSpec, weave, extractSpec, reconcileSpec } from '../dist/services/speco.js'; globalThis.localStorage = { getItem() { return null; }, setItem() { }, removeItem() { } }; const CONTRACT = /^\s*(REQUIRE|ENSURE|INVARIANT|DECREASES)\b/; const withContracts = () => programs().filter((p) => p.pseudo.split('\n').some((l) => CONTRACT.test(l)) && studyOf(p.pseudo).ok); const stripContracts = (src) => src.split('\n').filter((l) => !CONTRACT.test(l)).join('\n'); const COUNT = `FUNCTION COUNT_BASE(B : CHAR, T : STRING) RETURNS INTEGER DECLARE Total : INTEGER Total <- 0 FOR I <- 0 TO LENGTH(T) IF T[I] == B THEN Total <- Total + 1 ENDIF NEXT I RETURN Total ENDFUNCTION `; const SPEC = 'SPEC COUNT_BASE(B, T)\n ENSURE result = |{ K ∈ [0, |T|) : T[K] = B }|\n LOOP FOR I\n INVARIANT Total = |{ K ∈ [0, I) : T[K] = B }|'; test('there are programs with contracts to hold the laws to', () => { const ids = withContracts().map((p) => p.id); assert.ok(ids.includes('ex:count-base-proved') && ids.includes('ex:match-proved'), ids.join(', ')); assert.ok(ids.length >= 10, `${ids.length} programs with contracts`); }); test('replace mode: what the speco says replaces what the routine and the selected loops said, and insert mode stays as it was', () => { const old = weave(COUNT, parseSpec('SPEC COUNT_BASE(B, T)\n REQUIRE LENGTH(T) >= 0\n ENSURE RESULT >= 0\n LOOP FOR I\n INVARIANT Total >= 0\n DECREASES LENGTH(T) - I')).source; assert.match(old, /REQUIRE LENGTH\(T\) >= 0/); const w = weave(old, parseSpec(SPEC), { replace: true }); assert.deepEqual(w.diagnostics, []); assert.ok(!/REQUIRE|DECREASES|RESULT >= 0|Total >= 0/.test(w.source), w.source); assert.match(w.source, /FUNCTION COUNT_BASE[^\n]*\n\s+ENSURE RESULT == LENGTH\(\{ K IN \[0, LENGTH\(T\)\) : T\[K\] == B \}\)\n/); assert.match(w.source, /FOR I <- 0 TO LENGTH\(T\)\n\s+INVARIANT Total == LENGTH/); assert.ok(studyOf(w.source).ok); // insert mode keeps what is there and adds the new claims const kept = weave(old, parseSpec(SPEC)); assert.match(kept.source, /REQUIRE LENGTH\(T\) >= 0/); assert.match(kept.source, /DECREASES LENGTH\(T\) - I/); assert.match(kept.source, /ENSURE RESULT == LENGTH/); }); test('replace mode: routines and loops the spec does not name are left alone, and a unit with no claims clears its routine', () => { const two = `${COUNT} FUNCTION OTHER(N : INTEGER) RETURNS INTEGER REQUIRE N >= 0 RETURN N ENDFUNCTION `; const w = weave(two, parseSpec('SPEC COUNT_BASE(B, T)\n ENSURE RESULT >= 0'), { replace: true }); assert.match(w.source, /REQUIRE N >= 0/); const cleared = weave(w.source, parseSpec('SPEC COUNT_BASE(B, T)\n REQUIRE TRUE'), { replace: true }); assert.ok(!/ENSURE RESULT >= 0/.test(cleared.source)); assert.match(cleared.source, /REQUIRE TRUE/); }); test('replace mode is idempotent, and its map names the speco line each written line came from', () => { const spec = parseSpec(SPEC); const once = weave(COUNT, spec, { replace: true }); const twice = weave(once.source, spec, { replace: true }); assert.equal(twice.source, once.source); assert.equal(once.map.length, 2); const lines = once.source.split('\n'); for (const m of once.map) assert.ok(/ENSURE|INVARIANT/.test(lines[m.to - 1]) && m.from >= 1); }); test('lens law: extract(weave(P, extract(P))) === extract(P), for every program with contracts', () => { const bad = []; for (const p of withContracts()) { const spec = extractSpec(p.pseudo); const w = weave(p.pseudo, parseSpec(spec), { replace: true }); if (w.diagnostics.length) { bad.push(`${p.id}: ${w.diagnostics[0].message}`); continue; } if (!studyOf(w.source).ok) { bad.push(`${p.id}: the woven pseudo does not read`); continue; } if (extractSpec(w.source) !== spec) bad.push(`${p.id}: extract(weave(P, extract(P))) differs`); const again = weave(w.source, parseSpec(spec), { replace: true }); if (again.source !== w.source) bad.push(`${p.id}: weaving twice changes the pseudo`); } assert.deepEqual(bad, []); }); test('preservation: a spec woven into pseudo with no contracts, then extracted, comes back, for every program with contracts', () => { const bad = []; for (const p of withContracts()) { const spec = extractSpec(p.pseudo); const bare = stripContracts(p.pseudo); const w = weave(bare, parseSpec(spec), { replace: true }); if (w.diagnostics.length) { bad.push(`${p.id}: ${w.diagnostics[0].message}`); continue; } if (extractSpec(w.source) !== spec) bad.push(`${p.id}: the spec did not come back`); // and the contracts it restored are the ones the program had, up to spelling const norm = (t) => t.split('\n').filter((l) => CONTRACT.test(l)).map((l) => l.trim().replace(/\s+/g, '')).join('|'); if (norm(w.source) !== norm(p.pseudo)) bad.push(`${p.id}: the contracts written back differ from the original's`); } assert.deepEqual(bad, []); }); test('orphans: a spec whose routine is gone is kept, says why, and is reported on its line', () => { const prev = `${extractSpec(weave(COUNT, parseSpec(SPEC)).source)}\n\nSPEC GONE(N)\n REQUIRE N >= 0\n`; const r = reconcileSpec(COUNT.replace('COUNT_BASE', 'COUNT_BASE'), prev); assert.match(r.source, /\/\/ kept: the pseudocode has no FUNCTION or PROCEDURE called GONE\nSPEC GONE\(N\)\n REQUIRE N ≥ 0/); assert.equal(r.diagnostics.length, 1); assert.equal(r.diagnostics[0].id, 'spec-orphan'); assert.equal(r.source.split('\n')[r.diagnostics[0].line - 1], 'SPEC GONE(N)'); // the pseudo's own contracts (none here) are the spec's: COUNT_BASE has none, so its claims were deleted there assert.ok(!/SPEC COUNT_BASE/.test(r.source)); // a fixed point assert.equal(reconcileSpec(COUNT, r.source).source, r.source); }); test('orphans: a spec for a loop that is gone stays in its unit, and a routine that comes back takes its claims again', () => { const woven = weave(COUNT, parseSpec(SPEC)).source; const prev = extractSpec(woven); // the FOR loop becomes a WHILE loop: the invariant has no loop to be about const whileVersion = woven.replace(/FOR I <- 0 TO LENGTH\(T\)\n\s+INVARIANT[^\n]*\n/, 'WHILE FALSE\n').replace(' NEXT I', ' ENDWHILE'); const r = reconcileSpec(whileVersion, prev); assert.match(r.source, /ENSURE result/); assert.match(r.source, /\/\/ kept: COUNT_BASE has no loop matching "LOOP FOR I"\n\s+LOOP FOR I\n\s+INVARIANT Total/); assert.equal(r.diagnostics.length, 1); assert.equal(r.source.split('\n')[r.diagnostics[0].line - 1].trim(), 'LOOP FOR I'); assert.equal(reconcileSpec(whileVersion, r.source).source, r.source); // the FOR loop returns, with no invariant yet: the kept claim is its again const back = reconcileSpec(stripContracts(woven), r.source); assert.ok(!/kept:/.test(back.source), back.source); assert.match(back.source, /LOOP FOR I\n\s+INVARIANT Total/); assert.equal(back.diagnostics.length, 0); // a routine that was away and is back, with no contracts yet, takes its kept spec again const gone = reconcileSpec('FUNCTION OTHER(N : INTEGER) RETURNS INTEGER\n RETURN N\nENDFUNCTION\n', prev); assert.match(gone.source, /kept: the pseudocode has no FUNCTION or PROCEDURE called COUNT_BASE/); const returned = reconcileSpec(stripContracts(woven), gone.source); assert.ok(!/kept:/.test(returned.source)); assert.match(returned.source, /^SPEC COUNT_BASE\(B, T\)\n\s+ENSURE result/); // but a contract deleted in the pseudo, from a spec that was not waiting, is gone from the spec too assert.ok(!/SPEC COUNT_BASE/.test(reconcileSpec(stripContracts(woven), prev).source)); }); test('a loop the spec names that the routine does not have is reported on the LOOP line of the speco', () => { const w = weave(COUNT, parseSpec('SPEC COUNT_BASE(B, T)\n ENSURE RESULT >= 0\n\n LOOP WHILE\n INVARIANT Total >= 0')); const d = w.diagnostics.find((x) => x.id === 'no-loop'); assert.ok(d); assert.equal(d.line, 4); // the spec's own text is not touched by weaving: it is the caller's to keep assert.match(w.source, /ENSURE RESULT >= 0/); });