Skip to content

Commit 9f387b1

Browse files
committed
fix(codemod-split-engine): prune an import only a moved docblock linked, and prove the prune
noUnusedLocals counts a JSDoc {@link X} as a read, so five engine.ts import bindings went unused once their docblocks moved. --hand-docs now prunes them (and the // lines directly above a declaration that goes whole); the proof recomputes the prune from the head and requires every pruned name to be linked by a moved docblock. Re-run on main a26abbc: the tree equals a fresh --write there. Co-Authored-By: Claude <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_01Utp6CYHBS7P5hkUQrNHkHZ
1 parent 5ff9712 commit 9f387b1

2 files changed

Lines changed: 57 additions & 20 deletions

File tree

‎packages/objectql/src/engine.ts‎

Lines changed: 2 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -281,9 +281,9 @@ import { declaredOptionLabels } from './formula-option-labels.js';
281281
import { bindHooksToEngine, type BindHooksOptions } from './hook-binder.js';
282282
import { validateRecord, validateRecordInScope, normalizeMultiValueFields, normalizeBlankTypedValues, normalizeNumericStringValues, coerceBooleanFields, ValidationError } from './validation/record-validator.js';
283283
import type { AdmittedValueShapeViolation, AdmittedValueShapeViolationSink, ValidationMessageContext } from './validation/record-validator.js';
284-
import type { RelatedFieldBinding, RelatedRecordBinding } from './validation/rule-validator.js';
284+
import type { RelatedRecordBinding } from './validation/rule-validator.js';
285285
import { createBatchSummaryAccumulator } from './summary-batch-accumulation.js';
286-
import { collectReferenceTraversals, evaluateValidationRules, emitValidationAdvisories, optionVisibilityReadsPermissions, readsPermissionPredicate, needsPriorRecord, stripReadonlyWhenFields, stripReadonlyWhenFieldsMulti, hasReadonlyWhenInPayload, hasParentScopedReadonlyWhenInPayload, hasParentScopedRequiredWhen, stripReadonlyFields, stripRuntimeOwnedFields, staticReadonlyInsertSubject, preserveAuditIgnoredOnInsertWarning } from './validation/rule-validator.js';
286+
import { evaluateValidationRules, emitValidationAdvisories, needsPriorRecord, stripReadonlyWhenFields, stripReadonlyWhenFieldsMulti, hasReadonlyWhenInPayload, hasParentScopedReadonlyWhenInPayload, hasParentScopedRequiredWhen, stripReadonlyFields, stripRuntimeOwnedFields, staticReadonlyInsertSubject, preserveAuditIgnoredOnInsertWarning } from './validation/rule-validator.js';
287287
// [#14088] The before-phase write recorder — the provenance channel the static
288288
// `readonly` strip needs to tell a hook's write from a caller's echo of the
289289
// SAME value. Armed and sealed in `update()`; the module owns the argument for
@@ -333,9 +333,6 @@ import { resolveOneHopRelated, resolvePredicateRelated, resolvePreviewParents, s
333333
// (`ReadableIdsPermissionFormulaHost`). Imported after every module those bodies import, so
334334
// the engine's module evaluation order is what it was.
335335
import { composeReadableIdsChain, findUnservableControlledByParentMasters, permissionResolution, readableIdsScopeOf, reportFormulaFault, resolveDefaultPermissions, resolveFormulaPermissions, resolveOptionPermissions } from './engine-readable-ids-permission-formula.js';
336-
// [#25522 cut 16] Type-only, for the `{@link}`s on `composeReadableIdsAtBoundary`'s and
337-
// `composeReadableIdsChain`'s docblocks: the constant moved with its reader in cut 15.
338-
import type { READABLE_IDS_MAX_CHAIN_DEPTH } from './engine-readable-ids-permission-formula.js';
339336
// [#25522 cut 19] The delete cascade's collection walk, the in-cascade
340337
// `restrict` judge, the `DELETE_RESTRICTED` refusal, the reference-probe
341338
// filter and the reference-check elevation record; the methods of the same

‎scripts/codemod-split-engine.mjs‎

Lines changed: 55 additions & 15 deletions
Original file line numberDiff line numberDiff line change
@@ -1641,10 +1641,12 @@ function usedImportNames(tm, text) {
16411641
/**
16421642
* Drop every import binding `used` lacks. A declaration left with no binding
16431643
* goes whole (its own text and the line break after it; the comments above it
1644-
* stay); one left with some keeps them, a one-line `{ … }` on one line, a
1645-
* multi-line one as one binding per line. Pure. Returns `{ text, removed }`.
1644+
* stay, unless `dropAttachedComments`: then the `//` lines directly above it,
1645+
* with no blank line between, go with it); one left with some keeps them, a
1646+
* one-line `{ … }` on one line, a multi-line one as one binding per line.
1647+
* Pure. Returns `{ text, removed }`.
16461648
*/
1647-
function pruneImports(tm, text, used) {
1649+
function pruneImports(tm, text, used, { dropAttachedComments = false } = {}) {
16481650
const ts = tm.ts;
16491651
const sf = parseSourceFile(HOST_PATH, text);
16501652
const edits = [];
@@ -1666,7 +1668,18 @@ function pruneImports(tm, text, used) {
16661668
const keepNamed = named.filter((e) => used.has(e.name.text));
16671669
if (!keepDefault && !keepNs && keepNamed.length === 0) {
16681670
const end = text[st.getEnd()] === '\n' ? st.getEnd() + 1 : st.getEnd();
1669-
edits.push({ start: st.getStart(sf), end, text: '' });
1671+
let start = st.getStart(sf);
1672+
if (dropAttachedComments) {
1673+
// Walk up the `//` lines that touch the declaration (no blank line between).
1674+
for (;;) {
1675+
const prevEnd = start - 1;
1676+
if (prevEnd <= 0 || text[prevEnd] !== '\n') break;
1677+
const lineStart = text.lastIndexOf('\n', prevEnd - 1) + 1;
1678+
if (!/^\s*\/\/.*$/.test(text.slice(lineStart, prevEnd))) break;
1679+
start = lineStart;
1680+
}
1681+
}
1682+
edits.push({ start, end, text: '' });
16701683
continue;
16711684
}
16721685
if (nb && ts.isNamedImports(nb) && dropNamed.length > 0) {
@@ -2720,10 +2733,14 @@ async function mainScoped(tm, argv) {
27202733
* (re-indented), the placeholder back on its function, and taking the marker
27212734
* phrase and the header note out rebuilds the base `engine.ts` and every base
27222735
* hand module byte-for-byte (a base an earlier slice landed in is undone the
2723-
* same way first, so a slice is proved on its own). A one-character edit in a
2724-
* moved docblock, a block dropped on either side, a public docblock moved, or
2725-
* any other byte changed in those files fails it. The public `.d.ts` bar is a
2726-
* report reading on two built dists, as for the first two passes.
2736+
* same way first, so a slice is proved on its own), once the import bindings
2737+
* only a moved docblock's `{@link}` read (`noUnusedLocals` counts a link) are
2738+
* pruned from the base with the `//` lines directly above a declaration that
2739+
* goes whole; every pruned name must be one a moved docblock links. A
2740+
* one-character edit in a moved docblock, a block dropped on either side, a
2741+
* public docblock moved, or any other byte changed in those files fails it.
2742+
* The public `.d.ts` bar is a report reading on two built dists, as for the
2743+
* first two passes.
27272744
*/
27282745
const HAND_DOCS_CARD = '#30053';
27292746

@@ -2868,7 +2885,16 @@ function generateHandDocs(tm, engineText, moduleTexts, planned) {
28682885
}
28692886
modules.set(file, applyEdits(text, edits));
28702887
}
2871-
return { host: applyEdits(engineText, hostEdits), modules };
2888+
const moved = applyEdits(engineText, hostEdits);
2889+
// A JSDoc `{@link X}` is a read `noUnusedLocals` counts, so an import binding
2890+
// only a moved docblock linked is dropped, with the `//` lines that explain it.
2891+
const { text: host, removed: pruned } = pruneImports(tm, moved, usedImportNames(tm, moved), { dropAttachedComments: true });
2892+
return { host, modules, pruned };
2893+
}
2894+
2895+
/** The names a docblock links (`{@link X}`, `{@linkcode X}`, `@see X`; the leftmost name of a dotted one). */
2896+
function linkedNames(doc) {
2897+
return new Set([...doc.matchAll(/\{@link(?:code|plain)?\s+([A-Za-z_$][\w$]*)|@see\s+([A-Za-z_$][\w$]*)/g)].map((m) => m[1] ?? m[2]));
28722898
}
28732899

28742900
/**
@@ -2902,7 +2928,7 @@ function undoHandDocs(tm, engineText, moduleTexts, className = CLASS_NAME) {
29022928
const edits = perModule.get(s.module) ?? [];
29032929
edits.push({ start: fn.leadStart, end: fn.start, text: `${placeholderDoc(s.name, className)}\n` });
29042930
perModule.set(s.module, edits);
2905-
moved.push({ name: s.name, module: s.module, lines: sole.doc.split('\n').length });
2931+
moved.push({ name: s.name, module: s.module, lines: sole.doc.split('\n').length, doc: sole.doc });
29062932
}
29072933
const modules = new Map();
29082934
for (const [file, text] of moduleTexts) {
@@ -2935,7 +2961,13 @@ function verifyHandDocs(tm, baseText, headText, baseModules, headModules, { clas
29352961
let i = 0; while (i < Math.max(x.length, y.length) && x[i] === y[i]) i += 1;
29362962
return `line ${i + 1}: undone base ${JSON.stringify(x[i] ?? null)} | undone head ${JSON.stringify(y[i] ?? null)}`;
29372963
};
2938-
if (head.host !== base.host) failures.push(`undoing the moves does NOT rebuild the base ${HOST_BASENAME} (${firstDiff(base.host, head.host)})`);
2964+
// The one edit the undo does not read back from the head is the import
2965+
// prune: recomputed from the head and applied to the base, and every binding
2966+
// it drops must be a name a moved docblock links.
2967+
const { text: prunedBase, removed: pruned } = pruneImports(tm, base.host, usedImportNames(tm, headText), { dropAttachedComments: true });
2968+
const links = new Set(head.moved.flatMap((m) => [...linkedNames(m.doc)]));
2969+
for (const name of pruned) if (!links.has(name)) failures.push(`${name}: the head no longer imports it, and no moved docblock links it`);
2970+
if (head.host !== prunedBase) failures.push(`undoing the moves does NOT rebuild the base ${HOST_BASENAME} (${firstDiff(prunedBase, head.host)})`);
29392971
const files = [...new Set([...baseModules.keys(), ...headModules.keys()])].sort();
29402972
for (const file of files) {
29412973
const b = base.modules.get(file); const h = head.modules.get(file);
@@ -2944,7 +2976,7 @@ function verifyHandDocs(tm, baseText, headText, baseModules, headModules, { clas
29442976
}
29452977
const baseMoved = new Set(base.moved.map((m) => m.name));
29462978
return {
2947-
failures, moved: head.moved.filter((m) => !baseMoved.has(m.name)), baseMoved: base.moved.length,
2979+
failures, moved: head.moved.filter((m) => !baseMoved.has(m.name)), baseMoved: base.moved.length, pruned,
29482980
modules: files.length, linesBefore: lineCount(baseText), linesAfter: lineCount(headText),
29492981
};
29502982
}
@@ -2970,7 +3002,8 @@ function printVerifyHandDocs(v) {
29703002
for (const f of v.failures) console.error(` ✗ ${f}`);
29713003
console.log(`hand docblocks: ${v.moved.length} moved (${v.moved.reduce((n, m) => n + m.lines, 0)} lines) across ${new Set(v.moved.map((m) => m.module)).size} module(s), ${v.baseMoved} already moved at base; ` +
29723004
`${HOST_BASENAME} ${v.linesBefore} -> ${v.linesAfter} lines; undoing every move ${v.failures.some((f) => f.startsWith('undoing')) ? 'does NOT rebuild' : 'rebuilds'} the base, ` +
2973-
`undone the same way, for ${HOST_BASENAME} and its ${v.modules} hand module(s) byte-for-byte`);
3005+
`undone the same way, for ${HOST_BASENAME} and its ${v.modules} hand module(s) byte-for-byte, once the ${v.pruned.length} import binding(s) ` +
3006+
`only a moved docblock linked are pruned from the base (${v.pruned.join(', ') || 'none'})`);
29743007
}
29753008

29763009
/** The hand modules `engine.ts`'s hand stubs name, read through `read(file)` (null: absent). */
@@ -3129,7 +3162,7 @@ const SELF_TEST_BATTERIES = Object.freeze({
31293162
'import prune': 4,
31303163
'refusals': 6,
31313164
'scoped classes (second pass)': 16,
3132-
'hand-series docblocks (third pass)': 16,
3165+
'hand-series docblocks (third pass)': 18,
31333166
});
31343167
const SELF_TEST_BATTERY_FLOOR = 5;
31353168

@@ -3384,6 +3417,8 @@ export class ScopedContext {
33843417
function handFixtureEngine() {
33853418
return `import { privateDoc, publicDoc, noDoc, richer } from './engine-alpha.js';
33863419
import { betaPrivate } from './engine-beta.js';
3420+
// Type-only, for the link on betaPrivate's docblock.
3421+
import type { LinkedOnly } from './engine-beta.js';
33873422
33883423
export class ObjectQL {
33893424
private n = 1;
@@ -3415,7 +3450,7 @@ export class ObjectQL {
34153450
return richer();
34163451
}
34173452
3418-
/** A beta docblock. */
3453+
/** A beta docblock, {@link LinkedOnly}. */
34193454
private betaPrivate(): number {
34203455
// [#29460] The body lives in \`engine-beta.ts\`; it reads no member.
34213456
return betaPrivate();
@@ -3753,6 +3788,11 @@ async function selfTest() {
37533788
check('a marker that says moved over a docblock still on the class fails', fails(
37543789
out.host.replace('`engine-alpha.ts` (see `AlphaHost`). PUBLIC', `\`engine-alpha.ts\`${HAND_DOC_MOVED} (see \`AlphaHost\`). PUBLIC`), []));
37553790
check('a module missing its header note fails', fails(out.host, [['engine-alpha.ts', alpha.replace(`\n${HAND_DOCS_NOTE}`, '')]]));
3791+
check('an import only a moved docblock links is pruned with the // lines above it (not before its docblock moves), and the proof names it',
3792+
out.pruned.join() === 'LinkedOnly' && v.pruned.join() === 'LinkedOnly' && !out.host.includes('LinkedOnly }') &&
3793+
!out.host.includes('for the link on') && slice.host.includes('for the link on'), `${out.pruned} | ${v.pruned}`);
3794+
check('a binding the head dropped that no moved docblock links fails',
3795+
fails(out.host.replace("import { betaPrivate } from './engine-beta.js';\n", ''), []));
37563796
check('--modules naming a module no stub delegates to refuses',
37573797
refused(() => planHandDocs(tm, input, mods, { modules: ['engine-gone.ts'] })));
37583798
}

0 commit comments

Comments
 (0)