fix(gates): 死码判据改符号级可达性,堵住 barrel 再导出盲区(OPEN-16)
- 任何含 export…from 的模块按桶处理(不只 index.ts;constants.ts 是具名再导出门面) - 桶的再导出边不再无条件传播;按名 import 才解析到落点,export * / namespace / 副作用导入保守判活 - 解析前剥离注释(字符串感知),避免注释里的示例导入骗过 export…from 正则 - 新增 dead-modules.selftest.mjs(6 情景),check:dead 改为「自证 + 报告」 - 真树浮出 5 个 barrel-only 模块,登记 OPEN-18,未擅删
This commit is contained in:
1 parent
353fbde8da
commit
e1e950035d
3 files changed
+329
-10
No files matched your search
+2
-1
@@ -56,7 +56,8 @@
|
||||
"check:accents:selftest": "node scripts/check-accents.mjs --selftest",
|
||||
"check:grammar:selftest": "node scripts/check-visual-grammar.mjs --selftest",
|
||||
"check:visual": "npm run check:grammar:selftest && npm run check:grammar && npm run check:accents:selftest && npm run check:accents",
|
||||
"check:dead": "node scripts/dead-modules.mjs",
|
||||
"check:dead:selftest": "node scripts/dead-modules.selftest.mjs",
|
||||
"check:dead": "npm run check:dead:selftest && node scripts/dead-modules.mjs",
|
||||
"check:motion": "tsx scripts/utils/check-motion-constraints.ts",
|
||||
"check:motion:test": "jest --roots '<rootDir>/scripts/utils/__tests__'",
|
||||
"check:a11y": "npm run check:contrast && npm run check:headings && npm run check:brand-token",
|
||||
|
||||
+191
-9
@@ -42,6 +42,41 @@ const files = ROOTS.flatMap((r) => walk(r));
|
||||
const texts = new Map(files.map((f) => [path.normalize(f), readFileSync(f, 'utf8')]));
|
||||
const EXT = ['', '.ts', '.tsx', '.js', '.mjs', '/index.ts', '/index.tsx'];
|
||||
|
||||
/**
|
||||
* 注释剥离(字符串感知)。不剥离会把注释里的示例代码当成真语句:
|
||||
* `src/lib/constants.ts` 的注释里写着 `` `import { getHeroTheme } from '@/lib/constants'` ``,
|
||||
* 其中 `}` 会让 `export { … } from` 的正则提前收口,真正的 `from './constants/index'`
|
||||
* 因此漏匹配、门面被误判成无再导出 —— 判死码的判据自己被一段注释骗了。
|
||||
*/
|
||||
function stripComments(src) {
|
||||
let out = '';
|
||||
let i = 0;
|
||||
let mode = null; // "'" | '"' | '`' | '//' | '/*'
|
||||
while (i < src.length) {
|
||||
const c = src[i];
|
||||
const n = src[i + 1];
|
||||
if (mode === null) {
|
||||
if (c === '/' && n === '/') { mode = '//'; i += 2; continue; }
|
||||
if (c === '/' && n === '*') { mode = '/*'; i += 2; continue; }
|
||||
if (c === "'" || c === '"' || c === '`') { mode = c; out += c; i += 1; continue; }
|
||||
out += c; i += 1; continue;
|
||||
}
|
||||
if (mode === '//') { if (c === '\n') { mode = null; out += c; } i += 1; continue; }
|
||||
if (mode === '/*') {
|
||||
if (c === '*' && n === '/') { mode = null; i += 2; continue; }
|
||||
if (c === '\n') out += c;
|
||||
i += 1; continue;
|
||||
}
|
||||
out += c;
|
||||
if (c === '\\') { if (i + 1 < src.length) { out += src[i + 1]; i += 2; continue; } }
|
||||
if (c === mode) mode = null;
|
||||
i += 1;
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const scan = new Map([...texts].map(([f, txt]) => [f, stripComments(txt)]));
|
||||
|
||||
/** specifier → 站内落点文件(解析不到=第三方包或资源文件,返回 null) */
|
||||
function resolve(spec, fromFile) {
|
||||
let base;
|
||||
@@ -68,15 +103,163 @@ function resolve(spec, fromFile) {
|
||||
* 动态导入的 specifier 是字符串字面量,这里一并抓(模式串无法静态解析,按字面量解析)。
|
||||
*/
|
||||
const IMPORT_RE = /(?:from|import|require)\s*\(?\s*['"]([^'"]+)['"]/g;
|
||||
const edgesFrom = (file) => {
|
||||
const txt = texts.get(file);
|
||||
if (txt === undefined) return [];
|
||||
const out = [];
|
||||
for (const m of txt.matchAll(IMPORT_RE)) {
|
||||
const t = resolve(m[1], file);
|
||||
if (t && texts.has(t)) out.push(t);
|
||||
const IMPORT_STMT_RE = /\bimport\s+(?:type\s+)?(\{[^}]*\}|\*\s+as\s+\w+|\w+)\s*from\s*['"]([^'"]+)['"]/g;
|
||||
const REEXPORT_RE = /\bexport\s+(?:type\s+)?(\{[^}]*\}|\*\s+as\s+\w+|\*)\s*from\s*['"]([^'"]+)['"]/g;
|
||||
const SIDE_IMPORT_RE = /\bimport\s+['"]([^'"]+)['"]|\bimport\s*\(\s*['"]([^'"]+)['"]\s*\)|\brequire\s*\(\s*['"]([^'"]+)['"]\s*\)/g;
|
||||
|
||||
const isBarrel = (f) => /(^|\/)index\.ts$/.test(f);
|
||||
|
||||
/**
|
||||
* 「桶」不等于文件名 index.ts:`src/lib/constants.ts` 就是一份具名再导出门面
|
||||
* (`export { PRODUCTS } from './constants/index'`)。只认 index.ts 会让门面
|
||||
* 被当成普通模块 ⇒ 它的再导出边无条件传播,symbol 级判据又退回瞎的。
|
||||
* 判据改为「该文件含 export … from 语句」,并在符号解析时沿桶链递归。
|
||||
*/
|
||||
const hubFiles = new Set();
|
||||
for (const [f, txt] of scan) {
|
||||
if (isBarrel(f) || [...txt.matchAll(REEXPORT_RE)].length > 0) hubFiles.add(f);
|
||||
}
|
||||
const isHub = (f) => hubFiles.has(f);
|
||||
|
||||
/**
|
||||
* 桶的再导出表。符号级可达性的前提:
|
||||
* `export { X } from './x'` 只是**通道**,不等于有人用了 X。
|
||||
* 只有某个可达模块真的按名 import 了 X,落点文件 ./x 才算活。
|
||||
* `export *` 无法静态枚举符号,按保守方向算活(宁可漏判死码,不可误删活码)。
|
||||
* 这条判据对应 OPEN-16:barrel 再导出曾让 `detail/` 下 3 个零渲染点组件
|
||||
* 被算作"有引用",删掉实例之后判据仍然是瞎的。
|
||||
*/
|
||||
const barrelExports = new Map(); // barrel -> Map<对外符号, Set<落点文件>>
|
||||
const barrelStars = new Map(); // barrel -> Set<star 落点>
|
||||
for (const f of texts.keys()) {
|
||||
if (!isHub(f)) continue;
|
||||
const table = new Map();
|
||||
const stars = new Set();
|
||||
for (const m of scan.get(f).matchAll(REEXPORT_RE)) {
|
||||
const target = resolve(m[2], f);
|
||||
if (!target || !texts.has(target)) continue;
|
||||
const clause = m[1].trim();
|
||||
if (clause.startsWith('{')) {
|
||||
for (const piece of clause.slice(1, -1).split(',')) {
|
||||
const p = piece.trim();
|
||||
if (!p) continue;
|
||||
// `export { A as B }` 对外提供的是 B
|
||||
const exported = p.split(/\s+as\s+/).pop().trim();
|
||||
if (!exported) continue;
|
||||
if (!table.has(exported)) table.set(exported, new Set());
|
||||
table.get(exported).add(target);
|
||||
}
|
||||
} else {
|
||||
stars.add(target);
|
||||
}
|
||||
}
|
||||
barrelExports.set(f, table);
|
||||
barrelStars.set(f, stars);
|
||||
}
|
||||
|
||||
/** 在桶里查一个符号的真实落点;`export *` 链递归展开。查不到=符号可能定义在桶自身。 */
|
||||
function resolveBarrelSymbol(barrelFile, name, seen = new Set()) {
|
||||
const out = new Set();
|
||||
if (seen.has(barrelFile)) return out;
|
||||
seen.add(barrelFile);
|
||||
const direct = barrelExports.get(barrelFile)?.get(name);
|
||||
if (direct) {
|
||||
for (const src of direct) {
|
||||
out.add(src);
|
||||
// 门面 → 子桶是常见形状(constants.ts → constants/index.ts):继续往里找落点
|
||||
if (isHub(src)) for (const x of resolveBarrelSymbol(src, name, seen)) out.add(x);
|
||||
}
|
||||
return out;
|
||||
}
|
||||
for (const src of barrelStars.get(barrelFile) || []) {
|
||||
if (isHub(src)) {
|
||||
out.add(src); // 桶 → 桶仍是真实的模块依赖
|
||||
for (const x of resolveBarrelSymbol(src, name, seen)) out.add(x);
|
||||
} else {
|
||||
out.add(src);
|
||||
}
|
||||
}
|
||||
return out;
|
||||
}
|
||||
|
||||
const expandBarrel = (set, barrelFile, seen = new Set()) => {
|
||||
if (seen.has(barrelFile)) return;
|
||||
seen.add(barrelFile);
|
||||
for (const srcs of barrelExports.get(barrelFile)?.values() || []) {
|
||||
for (const src of srcs) {
|
||||
set.add(src);
|
||||
if (isHub(src)) expandBarrel(set, src, seen);
|
||||
}
|
||||
}
|
||||
for (const src of barrelStars.get(barrelFile) || []) {
|
||||
set.add(src);
|
||||
if (isHub(src)) expandBarrel(set, src, seen);
|
||||
}
|
||||
};
|
||||
|
||||
const edgeCache = new Map();
|
||||
/**
|
||||
* 出边。**桶的再导出边不算**——那是 OPEN-16 的盲区:桶把组件 export 出去,
|
||||
* 闭包就把它们全算成"可达",哪怕没有任何模块真的 import 过那个符号。
|
||||
* 桶只保留自己的 import;消费者对桶的按名 import 由 resolveBarrelSymbol
|
||||
* 展开成到落点文件的直接边。副作用/动态导入桶按执行语义整桶算活。
|
||||
*/
|
||||
const edgesFrom = (file) => {
|
||||
if (edgeCache.has(file)) return edgeCache.get(file);
|
||||
const txt = scan.get(file);
|
||||
if (txt === undefined) {
|
||||
edgeCache.set(file, []);
|
||||
return [];
|
||||
}
|
||||
|
||||
const out = new Set();
|
||||
if (!isHub(file)) {
|
||||
for (const m of txt.matchAll(IMPORT_RE)) {
|
||||
const t = resolve(m[1], file);
|
||||
if (t && texts.has(t)) out.add(t);
|
||||
}
|
||||
} else {
|
||||
for (const m of txt.matchAll(IMPORT_STMT_RE)) {
|
||||
const t = resolve(m[2], file);
|
||||
if (t && texts.has(t)) out.add(t);
|
||||
}
|
||||
// 桶 → 桶 是真实的模块依赖(门面 → 子桶),保留;桶 → 叶子不传播(OPEN-16)
|
||||
for (const m of txt.matchAll(REEXPORT_RE)) {
|
||||
const t = resolve(m[2], file);
|
||||
if (t && texts.has(t) && isHub(t)) out.add(t);
|
||||
}
|
||||
}
|
||||
|
||||
// 任何文件对桶的按名导入:连到符号落点;桶本身也保留为模块依赖
|
||||
for (const m of txt.matchAll(IMPORT_STMT_RE)) {
|
||||
const target = resolve(m[2], file);
|
||||
if (!target || !texts.has(target) || !isHub(target)) continue;
|
||||
out.add(target);
|
||||
const clause = m[1].trim();
|
||||
if (clause.startsWith('{')) {
|
||||
for (const piece of clause.slice(1, -1).split(',')) {
|
||||
const p = piece.trim();
|
||||
if (!p) continue;
|
||||
const imported = p.split(/\s+as\s+/)[0].trim();
|
||||
if (!imported) continue;
|
||||
for (const src of resolveBarrelSymbol(target, imported)) out.add(src);
|
||||
}
|
||||
} else {
|
||||
// default / namespace:无法知道用了哪个符号,整桶算活
|
||||
expandBarrel(out, target);
|
||||
}
|
||||
}
|
||||
|
||||
// 副作用 / 动态导入 / require 桶:执行语义会拉入整桶再导出
|
||||
for (const m of txt.matchAll(SIDE_IMPORT_RE)) {
|
||||
const target = resolve(m[1] || m[2] || m[3], file);
|
||||
if (!target || !texts.has(target)) continue;
|
||||
out.add(target);
|
||||
if (isHub(target)) expandBarrel(out, target);
|
||||
}
|
||||
|
||||
edgeCache.set(file, [...out]);
|
||||
return edgeCache.get(file);
|
||||
};
|
||||
|
||||
/**
|
||||
@@ -125,7 +308,6 @@ for (const f of texts.keys()) for (const t of edgesFrom(f)) {
|
||||
}
|
||||
|
||||
const testFile = (f) => /\.test\.|__tests__/.test(f);
|
||||
const barrel = (f) => /(^|\/)index\.ts$/.test(f);
|
||||
|
||||
const all = [...texts.keys()].filter((f) => !reachable.has(f)).sort();
|
||||
|
||||
@@ -168,7 +350,7 @@ for (const cat of ['convention', 'generated', 'library', 'test', 'dead']) {
|
||||
if (cat === 'dead' || cat === 'library') {
|
||||
for (const f of list) {
|
||||
const refBy = [...(importers.get(f) || [])];
|
||||
const onlyDeadOrTests = refBy.length === 0 || refBy.every((r) => testFile(r) || barrel(r) || !reachable.has(r));
|
||||
const onlyDeadOrTests = refBy.length === 0 || refBy.every((r) => testFile(r) || isHub(r) || !reachable.has(r));
|
||||
console.log(` ${f} ← ${refBy.length === 0 ? '零引用' : onlyDeadOrTests ? '仅测试/死链引用' : '被可达文件引用?!'}`);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,136 @@
|
||||
#!/usr/bin/env node
|
||||
/**
|
||||
* dead-modules 自证(OPEN-16)。判据对桶再导出的处理必须双向可证:
|
||||
* 正向:只被桶再导出、没有任何模块按名 import ⇒ 判死
|
||||
* 反向:页面按名经桶 import / 直接 import ⇒ 判活
|
||||
* 保守:export *、namespace import ⇒ 判活(宁可漏判,不可误删)
|
||||
* 做法:临时目录建 5 个默认根(脚本无参数运行需要它们存在),子进程跑真脚本,
|
||||
* 解析 `[dead]` 桶后的清单做断言。夹具不手写第二份路径判据——断言的是行为。
|
||||
*/
|
||||
import { mkdtempSync, mkdirSync, writeFileSync, rmSync } from 'node:fs';
|
||||
import { tmpdir } from 'node:os';
|
||||
import path from 'node:path';
|
||||
import { execFileSync } from 'node:child_process';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
|
||||
const script = path.join(path.dirname(fileURLToPath(import.meta.url)), 'dead-modules.mjs');
|
||||
const roots = ['src', 'scripts', 'e2e', 'config', 'prisma'];
|
||||
|
||||
function makeFixture(files) {
|
||||
const dir = mkdtempSync(path.join(tmpdir(), 'dead-modules-selftest-'));
|
||||
for (const root of roots) mkdirSync(path.join(dir, root), { recursive: true });
|
||||
for (const [rel, content] of Object.entries(files)) {
|
||||
const p = path.join(dir, rel);
|
||||
mkdirSync(path.dirname(p), { recursive: true });
|
||||
writeFileSync(p, content);
|
||||
}
|
||||
return dir;
|
||||
}
|
||||
|
||||
function run(dir) {
|
||||
try {
|
||||
return { code: 0, out: execFileSync(process.execPath, [script], { cwd: dir, encoding: 'utf8' }) };
|
||||
} catch (e) {
|
||||
return { code: e.status ?? 1, out: `${e.stdout || ''}${e.stderr || ''}` };
|
||||
}
|
||||
}
|
||||
|
||||
function deadEntries(out) {
|
||||
const lines = out.split('\n');
|
||||
const start = lines.findIndex((l) => l.startsWith('[dead]'));
|
||||
if (start < 0) return [];
|
||||
const list = [];
|
||||
for (let i = start + 1; i < lines.length; i++) {
|
||||
const line = lines[i];
|
||||
if (!line.startsWith(' ')) break;
|
||||
list.push(line.trim().split(/\s+←/)[0].trim());
|
||||
}
|
||||
return list;
|
||||
}
|
||||
|
||||
const barrel = "export { Alive } from './alive';\nexport { Dead } from './dead';\n";
|
||||
const components = {
|
||||
'src/components/alive.tsx': 'export const Alive = () => null;\n',
|
||||
'src/components/dead.tsx': 'export const Dead = () => null;\n',
|
||||
'src/components/index.ts': barrel,
|
||||
};
|
||||
const page = (body) => ({ 'src/app/page.tsx': `${body}\nexport default function Page() { return null; }\n` });
|
||||
|
||||
const cases = [
|
||||
{
|
||||
name: '仅桶再导出 ⇒ 判死',
|
||||
files: { ...components, ...page("import { Alive } from '../components';") },
|
||||
dead: ['src/components/dead.tsx'],
|
||||
alive: ['src/components/alive.tsx', 'src/components/index.ts'],
|
||||
},
|
||||
{
|
||||
name: '页面按名经桶导入 ⇒ 判活',
|
||||
files: { ...components, ...page("import { Alive, Dead } from '../components';") },
|
||||
dead: [],
|
||||
alive: ['src/components/dead.tsx'],
|
||||
},
|
||||
{
|
||||
name: '直接导入 ⇒ 判活',
|
||||
files: { ...components, ...page("import { Dead } from '../components/dead';") },
|
||||
dead: [],
|
||||
alive: ['src/components/dead.tsx'],
|
||||
},
|
||||
{
|
||||
name: 'export * ⇒ 保守判活',
|
||||
files: {
|
||||
'src/components/star.tsx': 'export const Star = () => null;\n',
|
||||
'src/components/index.ts': "export * from './star';\n",
|
||||
...page("import { Star } from '../components';"),
|
||||
},
|
||||
dead: [],
|
||||
alive: ['src/components/star.tsx'],
|
||||
},
|
||||
{
|
||||
name: '命名空间导入 ⇒ 整桶保守判活',
|
||||
files: { ...components, ...page("import * as UI from '../components';") },
|
||||
dead: [],
|
||||
alive: ['src/components/dead.tsx'],
|
||||
},
|
||||
{
|
||||
name: '门面 → 子桶链 ⇒ 按名解析到落点(注释里的伪导入不算)',
|
||||
files: {
|
||||
// 注释里的 import 必须被剥离:不剥离会让 Dead 被当成活码(constants.ts 的真实事故形态)
|
||||
'src/lib/constants.ts': "// 示例:import { Dead } from './dead';\nexport { Alive } from './constants/index';\n",
|
||||
'src/lib/constants/index.ts': "export { Alive } from './alive';\nexport { Dead } from './dead';\n",
|
||||
'src/lib/constants/alive.ts': 'export const Alive = 1;\n',
|
||||
'src/lib/constants/dead.ts': 'export const Dead = 2;\n',
|
||||
'src/app/page.tsx': "import { Alive } from '@/lib/constants';\nexport default function Page() { return null; }\n",
|
||||
},
|
||||
dead: ['src/lib/constants/dead.ts'],
|
||||
alive: ['src/lib/constants/alive.ts', 'src/lib/constants.ts', 'src/lib/constants/index.ts'],
|
||||
},
|
||||
];
|
||||
|
||||
let failed = 0;
|
||||
for (const c of cases) {
|
||||
const dir = makeFixture(c.files);
|
||||
try {
|
||||
const { code, out } = run(dir);
|
||||
const dead = deadEntries(out);
|
||||
const problems = [];
|
||||
if (code !== 0) problems.push(`退出码 ${code}(期望 0)`);
|
||||
for (const f of c.dead) if (!dead.includes(f)) problems.push(`应判死未判死:${f}`);
|
||||
for (const f of c.alive) if (dead.includes(f)) problems.push(`误判死:${f}`);
|
||||
if (problems.length) {
|
||||
failed++;
|
||||
console.log(`❌ ${c.name}`);
|
||||
for (const p of problems) console.log(` - ${p}`);
|
||||
console.log(` 实测 dead: ${dead.join(', ') || '(空)'}`);
|
||||
} else {
|
||||
console.log(`✅ ${c.name}`);
|
||||
}
|
||||
} finally {
|
||||
rmSync(dir, { recursive: true, force: true });
|
||||
}
|
||||
}
|
||||
|
||||
if (failed) {
|
||||
console.error(`\nSELFTEST FAILED:${failed}/${cases.length} 个情景未通过`);
|
||||
process.exit(1);
|
||||
}
|
||||
console.log(`\nSELFTEST PASSED:${cases.length}/${cases.length}`);
|
||||
Reference in new issue
Block a user