ShtukbaseStandard
package file→ .shtukbase/packages/code-refactoring/checks/deep_nesting.ts

checks/deep_nesting.ts

29 lines, 1.2 KB.

  1. // RF-R05 (Fowler, guard clauses instead of nested conditionals). A function whose blocks nest deeper than
  2. // `maxNesting` levels. See `nesting` in code-lib for what counts as a block in each language.
  3. import { type CheckDef, num, runCheck } from '../../code-lib/checks/lib/run.ts';
  4. import { functions, nesting } from '../../code-lib/checks/lib/units.ts';
  5. export const CHECK: CheckDef = {
  6. pkg: 'code-refactoring',
  7. rule: 'RF-R05',
  8. name: 'deep-nesting',
  9. defaults: { maxNesting: 4 },
  10. scan(srcs, set) {
  11. const max = num(set.maxNesting, 4);
  12. const out = [];
  13. for (const s of srcs) {
  14. const fns = functions(s);
  15. for (const f of fns) {
  16. // a nested function reports its own depth; the outer one skips lines inside it
  17. const n = nesting(s, f);
  18. if (n.depth <= max) continue;
  19. const inner = fns.find((g) => g !== f && g.bodyStart > f.bodyStart && g.bodyEnd <= f.bodyEnd && n.line >= g.line && n.line <= g.endLine);
  20. if (inner) continue;
  21. 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` });
  22. }
  23. }
  24. return out;
  25. },
  26. };
  27. if (import.meta.main) runCheck(CHECK);