файл пакета→ .shtukbase/packages/code-unix/checks/swallowed_errors.ts
checks/swallowed_errors.ts
76 строк, 4.5 КБ.
Файл как есть в пакете: код и комментарии в нём не переводятся.
- // UNX-R03 (Raymond, Rule of Repair: fail noisily and early). An error caught and dropped without a word:
- // TypeScript/JavaScript — an empty `catch {}` / `catch (e) {}`, `.catch(() => {})`, `.catch(() => null)`;
- // Python — `except Exception: pass` (or `...`), and a bare `except:` with any body (it catches Ctrl-C too);
- // `except SomeError: pass` names the one failure it expects and is reported only with `strictPass: true`;
- // Rust — a match arm `Err(_) => {}` / `Err(_) => ()`, and `.ok();` as a statement (the error is thrown away).
- // `let _ = call();` in Rust is counted only with `rustLetUnderscore: true` (it is often a deliberate choice).
- // A comment inside the empty block counts as a written reason, and the place is not reported.
- import { type CheckDef, type Finding, runCheck } from '../../code-lib/checks/lib/run.ts';
- import { matchClose, lineOf } from '../../code-lib/checks/lib/lex.ts';
- import type { Source } from '../../code-lib/checks/lib/scan.ts';
- const hasComment = (s: Source, a: number, b: number) => s.comments.some((c) => c.start >= a && c.start < b);
- export function swallowed(s: Source, letUnderscore: boolean, strict: boolean): Finding[] {
- const out: Finding[] = [];
- const code = s.code;
- const at = (k: number, msg: string) => out.push({ rel: s.rel, line: lineOf(s.starts, k), msg });
- let m: RegExpExecArray | null;
- if (s.lang === 'ts') {
- const re = /\bcatch\s*(\([^)]*\))?\s*\{/g;
- while ((m = re.exec(code))) {
- const open = m.index + m[0].length - 1;
- const close = matchClose(code, open);
- if (close > 0 && !code.slice(open + 1, close).trim() && !hasComment(s, open, close)) at(m.index, 'an empty catch swallows the error: report it, rethrow it or write why it can be forgotten');
- }
- const re2 = /\.catch\s*\(\s*(?:async\s*)?(?:\(\s*[\w$]*\s*\)|[\w$]+)\s*=>\s*(\{\s*\}|null|undefined|void 0|false)\s*\)/g;
- while ((m = re2.exec(code))) if (!hasComment(s, m.index, m.index + m[0].length)) at(m.index, 'a .catch that does nothing swallows the error: report it or rethrow it');
- } else if (s.lang === 'py') {
- const re = /^([ \t]*)except\b([^:\n]*):[ \t]*(?:(pass|\.\.\.)[ \t]*$|\n((?:[ \t]*\n)*)([ \t]+)(pass|\.\.\.)[ \t]*(?=\n|$))?/gm;
- while ((m = re.exec(code))) {
- const bare = !m[2].trim();
- const empty = !!(m[3] || m[6]);
- // `pass` must be the whole block: the next code line is not deeper
- let only = empty;
- if (empty && m[6]) {
- const rest = code.slice(m.index + m[0].length).split('\n').slice(1).find((l) => l.trim());
- if (rest && rest.length - rest.trimStart().length >= m[5].length) only = false;
- }
- const end = m.index + m[0].length;
- if (bare) at(m.index, 'a bare except catches everything, even Ctrl-C and exit: name the error type');
- else if (only && (strict || /^\s*\(?\s*(Exception|BaseException)\b/.test(m[2])) && !hasComment(s, m.index, end + 1)) at(m.index, `except${m[2]}: pass swallows the error: report it, rethrow it or write why it can be forgotten`);
- }
- } else {
- const re = /\bErr\s*\(\s*_\w*\s*\)\s*=>\s*(\{\s*\}|\(\s*\))/g;
- while ((m = re.exec(code))) if (!hasComment(s, m.index, m.index + m[0].length + 1)) at(m.index, 'Err(_) => {} swallows the error: return it (?), record it or explain it with a comment');
- const re2 = /\.ok\(\)\s*;/g;
- while ((m = re2.exec(code))) {
- // only as a whole statement: the line does not assign or return the Option
- const l = lineOf(s.starts, m.index);
- const stmt = code.slice(s.starts[l - 1], m.index);
- if (/^\s*(let\b|return\b|[\w.]+\s*=[^=])/.test(stmt) || /[=(,]\s*$/.test(stmt)) continue;
- let k = l - 1;
- let whole = stmt;
- while (k > 1 && /^\s*\./.test(whole)) whole = code.slice(s.starts[--k - 1], s.starts[k]) + whole; // a call chain over lines
- if (/^\s*(let\b|return\b|[\w.]+\s*=[^=])/.test(whole)) continue;
- if (!hasComment(s, s.starts[l - 1], m.index + 6)) at(m.index, '.ok(); drops the error: return it (?), record it or explain it with a comment');
- }
- if (letUnderscore) {
- const re3 = /\blet\s+_\s*=\s*[^;]*\([^;]*;/g;
- while ((m = re3.exec(code))) at(m.index, 'let _ = …; drops the result: handle the error or explain it with a comment');
- }
- }
- return out;
- }
- export const CHECK: CheckDef = {
- pkg: 'code-unix',
- rule: 'UNX-R03',
- name: 'swallowed-errors',
- defaults: { rustLetUnderscore: false, strictPass: false },
- scan(srcs, set) {
- return srcs.flatMap((s) => swallowed(s, set.rustLetUnderscore === true, set.strictPass === true));
- },
- };
- if (import.meta.main) runCheck(CHECK);