файл пакета→ .shtukbase/packages/code-refactoring/checks/duplicate_blocks.ts
checks/duplicate_blocks.ts
58 строк, 2.8 КБ.
Файл как есть в пакете: код и комментарии в нём не переводятся.
- // RF-R03 (Fowler, Duplicated Code). The same run of `minLines` significant lines in two places, after masking
- // comments and collapsing spaces (string contents count). Lines of only brackets, a lone word or argument
- // (`budget,`), imports and `use` lines are not significant. Copies are looked for within one language.
- // A block is reported at its later copy, with the place of the first one.
- import { type CheckDef, type Finding, num, runCheck } from '../../code-lib/checks/lib/run.ts';
- import { lineText } from '../../code-lib/checks/lib/scan.ts';
- const TRIVIAL = /^[\s{}()[\];,.?]*$|^[\w.&*:$]+[,)]*[;?]*$|^(import|from|use|export\s+\{|export\s+\*|pub\s+use|mod)\b|^(else|try|finally|break;?|continue;?|return;?|pass|end)$/;
- export const CHECK: CheckDef = {
- pkg: 'code-refactoring',
- rule: 'RF-R03',
- name: 'duplicate-blocks',
- defaults: { minLines: 8 },
- scan(srcs, set) {
- const w = num(set.minLines, 8);
- type Sig = { line: number; text: string };
- const files = srcs.map((s) => {
- // comments stay masked; string contents come back, so `'a' => 1` and `'b' => 1` differ
- const chars = s.code.split('');
- for (const st of s.strings) for (let k = st.start; k <= st.end && k < chars.length; k++) chars[k] = s.raw[k];
- const text = chars.join('');
- const sig: Sig[] = [];
- for (let l = 1; l <= s.starts.length; l++) {
- const t = lineText(s, l, text).replace(/\s+/g, ' ').trim();
- if (!TRIVIAL.test(t)) sig.push({ line: l, text: t });
- }
- return { s, sig };
- });
- const first = new Map<string, { fi: number; idx: number }>();
- const dup = files.map((f) => new Array<{ fi: number; idx: number } | null>(f.sig.length).fill(null));
- files.forEach((f, fi) => {
- for (let idx = 0; idx + w <= f.sig.length; idx++) {
- const key = f.s.lang + '\n' + f.sig.slice(idx, idx + w).map((x) => x.text).join('\n'); // within one language
- if (key.length < w * 12) continue; // too little text to be knowledge
- const seen = first.get(key);
- if (!seen) first.set(key, { fi, idx });
- else if (seen.fi !== fi || idx - seen.idx >= w) dup[fi][idx] = seen;
- }
- });
- const out: Finding[] = [];
- files.forEach((f, fi) => {
- for (let idx = 0; idx < f.sig.length; idx++) {
- const d = dup[fi][idx];
- if (!d || (idx > 0 && dup[fi][idx - 1])) continue;
- let end = idx;
- while (end + 1 < f.sig.length && dup[fi][end + 1]) end++;
- const other = files[d.fi];
- const lastLine = f.sig[Math.min(end + w - 1, f.sig.length - 1)].line;
- out.push({ rel: f.s.rel, line: f.sig[idx].line, msg: `the block of lines ${f.sig[idx].line}–${lastLine} repeats ${other.s.rel}:${other.sig[d.idx].line}: move the common part into a function` });
- idx = end;
- }
- });
- return out;
- },
- };
- if (import.meta.main) runCheck(CHECK);