ShtukbaseStandard
包文件→ .shtukbase/packages/code-deep-modules/checks/pass_through.ts

checks/pass_through.ts

40 行, 2.2 KB.

文件按包中的原样显示:代码及其注释不做翻译。

  1. // DM-R02 (Ousterhout, pass-through methods). A function whose whole body is one call that hands its own
  2. // parameters on unchanged, in the same order: `f(a, b) { return g(a, b); }`. Such a layer adds an interface
  3. // and no function. Constructors of values (`Self(x)`, `Ok(x)`, `Some(x)`, names in CapitalCase) are skipped,
  4. // so is a function without parameters, a Rust method of `impl Trait for Type` (the trait fixes its shape)
  5. // and a call on a fixed value (`Code::Invalid.error(why)` adds knowledge: which value).
  6. import { type CheckDef, runCheck } from '../../code-lib/checks/lib/run.ts';
  7. import { body, functions, splitTop } from '../../code-lib/checks/lib/units.ts';
  8. /** The callee and arguments when the body is a single forwarding call; null otherwise. */
  9. export function forwarded(text: string, lang: string): { callee: string; args: string[] } | null {
  10. let t = text.trim();
  11. if (lang === 'py') t = t.replace(/^(?:[rbuRBU]?(?:"""\s*"""|'''\s*'''|"\s*"|'\s*'))\s*/, '').trim(); // a docstring
  12. const m = /^(?:return\s+)?(?:await\s+)?((?:self\.|this\.|super\.)?[A-Za-z_$][\w$]*(?:(?:\.|::|\?\.)[A-Za-z_$][\w$]*)*)\s*\(([^()]*)\)(?:\.await)?\??\s*;?$/.exec(t);
  13. if (!m) return null;
  14. return { callee: m[1], args: splitTop(m[2]).map((a) => a.replace(/^&\s*(mut\s+)?|^\*{1,2}|^\.\.\./, '').trim()) };
  15. }
  16. export const CHECK: CheckDef = {
  17. pkg: 'code-deep-modules',
  18. rule: 'DM-R02',
  19. name: 'pass-through',
  20. defaults: {},
  21. scan(srcs) {
  22. const out = [];
  23. for (const s of srcs)
  24. for (const f of functions(s)) {
  25. if (!f.params.length || f.params.some((p) => !p) || f.traitImpl) continue;
  26. const fw = forwarded(body(s, f), s.lang);
  27. if (!fw) continue;
  28. const last = fw.callee.split(/\.|::/).pop() ?? '';
  29. if (/^[A-Z]/.test(last) || ['new', 'from', 'into', 'clone'].includes(last)) continue;
  30. if (/\b[A-Z]\w*\./.test(fw.callee)) continue; // `ErrorCode::Invalid.error(why)`: the helper adds a fixed value
  31. if (fw.args.join(',') !== f.params.join(',')) continue;
  32. out.push({ rel: s.rel, line: f.line, msg: `the function ${f.name} only passes its parameters to ${fw.callee}: remove the layer or give it a job of its own` });
  33. }
  34. return out;
  35. },
  36. };
  37. if (import.meta.main) runCheck(CHECK);