ShtukbaseStandard
package file→ .shtukbase/packages/code-functional-core/checks/core_mutation.ts

checks/core_mutation.ts

49 lines, 2.6 KB.

  1. // FC-R03 (Bernhardt; Seemann). Core functions take values and return new values: they do not change what they
  2. // were given. Looked for, per parameter `p` of a core function:
  3. // TypeScript/JavaScript — `p.x = …`, `p[i] = …`, `p.x += …`, `p.x++`, `p.push/pop/shift/unshift/splice/sort/
  4. // reverse/fill/set/delete/clear/add(`;
  5. // Python — `p.x = …`, `p[i] = …`, `p.append/extend/insert/pop/remove/clear/update/sort/reverse/setdefault/add/
  6. // discard(`;
  7. // Rust — only with `rustMutRefs: true`: a parameter of type `&mut` (other than self, outside trait impls).
  8. // Off by default: in Rust a `&mut` is written in the signature and checked by the compiler, so the change
  9. // is not hidden; turn it on for a core that must return new values.
  10. // Local variables are free to change: only what came from outside counts.
  11. import { type CheckDef, type Finding, runCheck } from '../../code-lib/checks/lib/run.ts';
  12. import { lineOf } from '../../code-lib/checks/lib/lex.ts';
  13. import { body, functions } from '../../code-lib/checks/lib/units.ts';
  14. import { coreOf } from './lib.ts';
  15. const esc = (s: string) => s.replace(/\$/g, '\\$');
  16. export const CHECK: CheckDef = {
  17. pkg: 'code-functional-core',
  18. rule: 'FC-R03',
  19. name: 'core-mutation',
  20. defaults: { core: [], rustMutRefs: false },
  21. scan(srcs, set) {
  22. const { core, named } = coreOf(srcs, set);
  23. if (!named) return [];
  24. const out: Finding[] = [];
  25. for (const s of core)
  26. for (const f of functions(s)) {
  27. if (s.lang === 'rs') {
  28. if (set.rustMutRefs !== true || f.traitImpl) continue;
  29. f.paramText.forEach((t, k) => {
  30. if (/:\s*&\s*('\w+\s+)?mut\b/.test(t)) out.push({ rel: s.rel, line: f.line, msg: `the function ${f.name} changes the parameter ${f.params[k]} (&mut): return a new value` });
  31. });
  32. continue;
  33. }
  34. const b = body(s, f);
  35. for (const p of f.params) {
  36. if (!p) continue;
  37. const methods = s.lang === 'ts' ? 'push|pop|shift|unshift|splice|sort|reverse|fill|set|delete|clear|add' : 'append|extend|insert|pop|remove|clear|update|sort|reverse|setdefault|add|discard';
  38. const re = new RegExp(`(?<![\\w$.])${esc(p)}(?:(?:\\.[\\w$]+|\\[[^\\]\\n]*\\])+\\s*(?:[-+*/|&]?=(?!=)|\\+\\+|--)|\\.(?:${methods})\\s*\\()`);
  39. const m = re.exec(b);
  40. if (m) out.push({ rel: s.rel, line: lineOf(s.starts, f.bodyStart + m.index), msg: `the function ${f.name} changes the parameter ${p}: return a new value and leave the given one as it was` });
  41. }
  42. }
  43. return out;
  44. },
  45. };
  46. if (import.meta.main) runCheck(CHECK);