ShtukbaseStandard
файл пакета→ .shtukbase/packages/code-unix/checks/swallowed_errors.ts

checks/swallowed_errors.ts

76 строк, 4.5 КБ.

Файл как есть в пакете: код и комментарии в нём не переводятся.

  1. // UNX-R03 (Raymond, Rule of Repair: fail noisily and early). An error caught and dropped without a word:
  2. // TypeScript/JavaScript — an empty `catch {}` / `catch (e) {}`, `.catch(() => {})`, `.catch(() => null)`;
  3. // Python — `except Exception: pass` (or `...`), and a bare `except:` with any body (it catches Ctrl-C too);
  4. // `except SomeError: pass` names the one failure it expects and is reported only with `strictPass: true`;
  5. // Rust — a match arm `Err(_) => {}` / `Err(_) => ()`, and `.ok();` as a statement (the error is thrown away).
  6. // `let _ = call();` in Rust is counted only with `rustLetUnderscore: true` (it is often a deliberate choice).
  7. // A comment inside the empty block counts as a written reason, and the place is not reported.
  8. import { type CheckDef, type Finding, runCheck } from '../../code-lib/checks/lib/run.ts';
  9. import { matchClose, lineOf } from '../../code-lib/checks/lib/lex.ts';
  10. import type { Source } from '../../code-lib/checks/lib/scan.ts';
  11. const hasComment = (s: Source, a: number, b: number) => s.comments.some((c) => c.start >= a && c.start < b);
  12. export function swallowed(s: Source, letUnderscore: boolean, strict: boolean): Finding[] {
  13. const out: Finding[] = [];
  14. const code = s.code;
  15. const at = (k: number, msg: string) => out.push({ rel: s.rel, line: lineOf(s.starts, k), msg });
  16. let m: RegExpExecArray | null;
  17. if (s.lang === 'ts') {
  18. const re = /\bcatch\s*(\([^)]*\))?\s*\{/g;
  19. while ((m = re.exec(code))) {
  20. const open = m.index + m[0].length - 1;
  21. const close = matchClose(code, open);
  22. 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');
  23. }
  24. const re2 = /\.catch\s*\(\s*(?:async\s*)?(?:\(\s*[\w$]*\s*\)|[\w$]+)\s*=>\s*(\{\s*\}|null|undefined|void 0|false)\s*\)/g;
  25. 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');
  26. } else if (s.lang === 'py') {
  27. const re = /^([ \t]*)except\b([^:\n]*):[ \t]*(?:(pass|\.\.\.)[ \t]*$|\n((?:[ \t]*\n)*)([ \t]+)(pass|\.\.\.)[ \t]*(?=\n|$))?/gm;
  28. while ((m = re.exec(code))) {
  29. const bare = !m[2].trim();
  30. const empty = !!(m[3] || m[6]);
  31. // `pass` must be the whole block: the next code line is not deeper
  32. let only = empty;
  33. if (empty && m[6]) {
  34. const rest = code.slice(m.index + m[0].length).split('\n').slice(1).find((l) => l.trim());
  35. if (rest && rest.length - rest.trimStart().length >= m[5].length) only = false;
  36. }
  37. const end = m.index + m[0].length;
  38. if (bare) at(m.index, 'a bare except catches everything, even Ctrl-C and exit: name the error type');
  39. 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`);
  40. }
  41. } else {
  42. const re = /\bErr\s*\(\s*_\w*\s*\)\s*=>\s*(\{\s*\}|\(\s*\))/g;
  43. 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');
  44. const re2 = /\.ok\(\)\s*;/g;
  45. while ((m = re2.exec(code))) {
  46. // only as a whole statement: the line does not assign or return the Option
  47. const l = lineOf(s.starts, m.index);
  48. const stmt = code.slice(s.starts[l - 1], m.index);
  49. if (/^\s*(let\b|return\b|[\w.]+\s*=[^=])/.test(stmt) || /[=(,]\s*$/.test(stmt)) continue;
  50. let k = l - 1;
  51. let whole = stmt;
  52. while (k > 1 && /^\s*\./.test(whole)) whole = code.slice(s.starts[--k - 1], s.starts[k]) + whole; // a call chain over lines
  53. if (/^\s*(let\b|return\b|[\w.]+\s*=[^=])/.test(whole)) continue;
  54. 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');
  55. }
  56. if (letUnderscore) {
  57. const re3 = /\blet\s+_\s*=\s*[^;]*\([^;]*;/g;
  58. while ((m = re3.exec(code))) at(m.index, 'let _ = …; drops the result: handle the error or explain it with a comment');
  59. }
  60. }
  61. return out;
  62. }
  63. export const CHECK: CheckDef = {
  64. pkg: 'code-unix',
  65. rule: 'UNX-R03',
  66. name: 'swallowed-errors',
  67. defaults: { rustLetUnderscore: false, strictPass: false },
  68. scan(srcs, set) {
  69. return srcs.flatMap((s) => swallowed(s, set.rustLetUnderscore === true, set.strictPass === true));
  70. },
  71. };
  72. if (import.meta.main) runCheck(CHECK);