包文件→ .shtukbase/packages/code-refactoring/checks/deep_nesting.ts
checks/deep_nesting.ts
29 行, 1.2 KB.
文件按包中的原样显示:代码及其注释不做翻译。
- // RF-R05 (Fowler, guard clauses instead of nested conditionals). A function whose blocks nest deeper than
- // `maxNesting` levels. See `nesting` in code-lib for what counts as a block in each language.
- import { type CheckDef, num, runCheck } from '../../code-lib/checks/lib/run.ts';
- import { functions, nesting } from '../../code-lib/checks/lib/units.ts';
- export const CHECK: CheckDef = {
- pkg: 'code-refactoring',
- rule: 'RF-R05',
- name: 'deep-nesting',
- defaults: { maxNesting: 4 },
- scan(srcs, set) {
- const max = num(set.maxNesting, 4);
- const out = [];
- for (const s of srcs) {
- const fns = functions(s);
- for (const f of fns) {
- // a nested function reports its own depth; the outer one skips lines inside it
- const n = nesting(s, f);
- if (n.depth <= max) continue;
- const inner = fns.find((g) => g !== f && g.bodyStart > f.bodyStart && g.bodyEnd <= f.bodyEnd && n.line >= g.line && n.line <= g.endLine);
- if (inner) continue;
- out.push({ rel: s.rel, line: n.line, msg: `the function ${f.name}: nesting ${n.depth} (threshold ${max}): use an early exit instead of nested conditions, extract a function` });
- }
- }
- return out;
- },
- };
- if (import.meta.main) runCheck(CHECK);