package file→ .shtukbase/packages/code-functional-core/checks/core_mutation.ts
checks/core_mutation.ts
49 lines, 2.6 KB.
- // FC-R03 (Bernhardt; Seemann). Core functions take values and return new values: they do not change what they
- // were given. Looked for, per parameter `p` of a core function:
- // TypeScript/JavaScript — `p.x = …`, `p[i] = …`, `p.x += …`, `p.x++`, `p.push/pop/shift/unshift/splice/sort/
- // reverse/fill/set/delete/clear/add(`;
- // Python — `p.x = …`, `p[i] = …`, `p.append/extend/insert/pop/remove/clear/update/sort/reverse/setdefault/add/
- // discard(`;
- // Rust — only with `rustMutRefs: true`: a parameter of type `&mut` (other than self, outside trait impls).
- // Off by default: in Rust a `&mut` is written in the signature and checked by the compiler, so the change
- // is not hidden; turn it on for a core that must return new values.
- // Local variables are free to change: only what came from outside counts.
- import { type CheckDef, type Finding, runCheck } from '../../code-lib/checks/lib/run.ts';
- import { lineOf } from '../../code-lib/checks/lib/lex.ts';
- import { body, functions } from '../../code-lib/checks/lib/units.ts';
- import { coreOf } from './lib.ts';
- const esc = (s: string) => s.replace(/\$/g, '\\$');
- export const CHECK: CheckDef = {
- pkg: 'code-functional-core',
- rule: 'FC-R03',
- name: 'core-mutation',
- defaults: { core: [], rustMutRefs: false },
- scan(srcs, set) {
- const { core, named } = coreOf(srcs, set);
- if (!named) return [];
- const out: Finding[] = [];
- for (const s of core)
- for (const f of functions(s)) {
- if (s.lang === 'rs') {
- if (set.rustMutRefs !== true || f.traitImpl) continue;
- f.paramText.forEach((t, k) => {
- 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` });
- });
- continue;
- }
- const b = body(s, f);
- for (const p of f.params) {
- if (!p) continue;
- 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';
- const re = new RegExp(`(?<![\\w$.])${esc(p)}(?:(?:\\.[\\w$]+|\\[[^\\]\\n]*\\])+\\s*(?:[-+*/|&]?=(?!=)|\\+\\+|--)|\\.(?:${methods})\\s*\\()`);
- const m = re.exec(b);
- 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` });
- }
- }
- return out;
- },
- };
- if (import.meta.main) runCheck(CHECK);