@voidh4x0r/slopgate 0.1.2 → 0.1.4
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +30 -0
- package/README.md +6 -5
- package/dist/files.js +13 -26
- package/dist/mcp.js +6 -0
- package/dist/rules/helpers.d.ts +2 -0
- package/dist/rules/helpers.js +18 -7
- package/dist/rules/python.js +56 -4
- package/dist/rules/typescript.js +107 -13
- package/dist/types.d.ts +2 -0
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
|
@@ -9,6 +9,36 @@ All notable changes to this project are documented here. The format follows [Kee
|
|
|
9
9
|
- Go and Rust grammars.
|
|
10
10
|
- VS Code diagnostics.
|
|
11
11
|
|
|
12
|
+
## [0.1.4] - 2026-11-22
|
|
13
|
+
|
|
14
|
+
### Fixed
|
|
15
|
+
- `ts/noop-test` recognises the Tape/TAP assertion API again (`t.equal`, `t.deepEqual`, `t.strictEqual`, `t.doesNotThrow`, …), fixing a regression introduced in 0.1.1; a framework matrix test now pins the accepted assertion families.
|
|
16
|
+
- `ts/unreachable` no longer reports hoisted `function`/generator declarations or bare `var` statements after a `return`; `let`/`const` and initialised `var` are still reported.
|
|
17
|
+
- `ts/stub-function` reports class-method `throw new Error("Not implemented")` at medium confidence; standalone/exported throw-stubs remain high.
|
|
18
|
+
- `py/stub-body` skips `dummy_multiprocessing/`-style prefixed directories when the module docstring identifies a no-op shim, while `dummy_data/` remains reported.
|
|
19
|
+
- `py/swallowed-exception` only accepts standalone explanatory comments; a trailing comment on a preceding code line no longer demotes. Above-`try` comments need paired failure/intent wording (or a strong phrase such as "harmless"), and TODO/FIXME/refactor comments do not count. Inline comments on the handler line still count.
|
|
20
|
+
- `ts/dead-branch` now has the same nearby-comment demotion as `py/dead-branch`.
|
|
21
|
+
|
|
22
|
+
### Changed
|
|
23
|
+
- 228 tests, including fourth-round regression fixtures for `tape-assert`, `hoisted-fn`, `assert-forms`, `above-heuristic`, `above-trailing`, `between-asymmetry` and `dummy-dir-shim`.
|
|
24
|
+
- Benchmark unchanged at **29 high-confidence findings across 991,705 lines of CPython, 96.6% labeled precision (28/29), 14/14 seeded defects, 0 high findings on 601 JavaScript files**; `staleLabels: []`, `unlabeledHigh: []`.
|
|
25
|
+
- Docs now state that the nine JS packages do not exercise Tape/TAP or bundled output, and record the Electron-asar corpus findings as the motivation for the 0.2.0 JS corpus expansion.
|
|
26
|
+
|
|
27
|
+
## [0.1.3] - 2026-11-22
|
|
28
|
+
|
|
29
|
+
### Fixed
|
|
30
|
+
- MCP `scan_path` and `scan_diff` now return a tool error (`isError: true`) when zero files match, matching the CLI's exit 2 instead of reporting a clean run.
|
|
31
|
+
- `py/swallowed-exception` counts an explanatory comment immediately above `try` (keyword-filtered so a generic "parse the payload" comment does not hide a silent handler), and no longer includes a trailing comment on the last try-body line (off-by-one in the window start).
|
|
32
|
+
- `py/stub-body` skips `dummy_threading.py`-style modules again: exact no-op directories plus file stems starting `dummy_`/`noop_`/`_dummy_`; `dummy_data/` and `shims/` real stubs remain reported.
|
|
33
|
+
- `ts/noop-test` recognises renamed `node:assert` imports (namespace, default, named aliases and `require` bindings) as assertions.
|
|
34
|
+
- The extension language/dialect tables are merged into one map, so an extension cannot be present in one table and silently dropped from discovery.
|
|
35
|
+
- Added a docs test that fails when README or the demo artwork version disagrees with `package.json`; RELEASE now lists the docs update.
|
|
36
|
+
|
|
37
|
+
### Changed
|
|
38
|
+
- 193 tests, including third-round regression fixtures for `window`, `renamed-assert` and `dummy-variants`.
|
|
39
|
+
- Benchmark re-run: **29 high-confidence findings across 991,705 lines of CPython, 96.6% labeled precision (28/29), 14/14 seeded defects detected, 0 high findings on 601 JavaScript files.** One 0.1.2 label became stale after the comment-window change and was pruned; the file now has 18 labels covering 29 occurrences, with `staleLabels: []` and `unlabeledHigh: []`.
|
|
40
|
+
- Docs: MCP zero-file behaviour, the four comment placements, dummy naming variants, and renamed assert imports are documented.
|
|
41
|
+
|
|
12
42
|
## [0.1.2] - 2026-11-22
|
|
13
43
|
|
|
14
44
|
### Fixed
|
package/README.md
CHANGED
|
@@ -14,7 +14,7 @@ AI writes code that *looks* right. `slopgate` finds the parts that only look rig
|
|
|
14
14
|
```console
|
|
15
15
|
$ npx @voidh4x0r/slopgate .
|
|
16
16
|
|
|
17
|
-
slopgate 0.1.
|
|
17
|
+
slopgate 0.1.4 · 4 files · 39ms
|
|
18
18
|
|
|
19
19
|
app.py
|
|
20
20
|
4:1 error high py/phantom-import `helper` is imported but not declared in any manifest and not present in this repository
|
|
@@ -72,7 +72,7 @@ Measured on **1,115,177 lines** of real code — the CPython standard library (a
|
|
|
72
72
|
| High-confidence findings | **29** (0.03 per 1,000 lines), in 18 of 1,845 CPython files |
|
|
73
73
|
| Labeled precision of high-confidence findings | **96.6%** (28/29 manually reviewed) |
|
|
74
74
|
| Recall on 14 seeded defects | **14/14** |
|
|
75
|
-
| High-confidence findings on 601 JavaScript files (`eslint`, `express`, `execa`, `semver`, `chalk`, `commander`, `debug`, `yargs`, `glob`) | **0** |
|
|
75
|
+
| High-confidence findings on 601 JavaScript files (`eslint`, `express`, `execa`, `semver`, `chalk`, `commander`, `debug`, `yargs`, `glob`) | **0** (these packages contain no Tape/TAP suites or bundled output — see the [coverage note](docs/benchmark.md#what-the-javascript-half-does-not-cover)) |
|
|
76
76
|
|
|
77
77
|
The labels, the corpus definition and the harness are in [`benchmark/`](https://github.com/VoidH4x0r/slopgate/tree/main/benchmark) and [`docs/benchmark.md`](https://github.com/VoidH4x0r/slopgate/blob/main/docs/benchmark.md); `node scripts/benchmark.mjs` reproduces the numbers. We publish the false positives instead of hiding them.
|
|
78
78
|
|
|
@@ -204,7 +204,7 @@ jobs:
|
|
|
204
204
|
- uses: actions/checkout@v4
|
|
205
205
|
- uses: actions/setup-node@v4
|
|
206
206
|
with: { node-version: 22 }
|
|
207
|
-
- run: npx --yes @voidh4x0r/slopgate@0.1.
|
|
207
|
+
- run: npx --yes @voidh4x0r/slopgate@0.1.4 . --fail-on high
|
|
208
208
|
```
|
|
209
209
|
|
|
210
210
|
For GitHub code scanning, use `--format sarif` and upload with `github/codeql-action/upload-sarif`.
|
|
@@ -212,7 +212,7 @@ For GitHub code scanning, use `--format sarif` and upload with `github/codeql-ac
|
|
|
212
212
|
For inline pull-request annotations **without** code scanning, use `--format github`, which emits [workflow commands](https://docs.github.com/en/actions/using-workflows/workflow-commands-for-github-actions):
|
|
213
213
|
|
|
214
214
|
```yaml
|
|
215
|
-
- run: npx --yes @voidh4x0r/slopgate@0.1.
|
|
215
|
+
- run: npx --yes @voidh4x0r/slopgate@0.1.4 . --format github --fail-on high
|
|
216
216
|
```
|
|
217
217
|
|
|
218
218
|
Each finding becomes an `error` / `warning` / `notice` annotation on the exact line, followed by a summary notice.
|
|
@@ -279,6 +279,7 @@ We would rather miss a finding than teach you to ignore the tool. That is also w
|
|
|
279
279
|
|
|
280
280
|
- `.gitignore` is not read. Generated trees are skipped only through the built-in ignore list and your own `exclude` patterns.
|
|
281
281
|
- Symbolic links are skipped, but they are **not** counted in `stats.skipped`. Files larger than 1 MB, empty files, excluded files and unreadable files are counted.
|
|
282
|
+
- Bundled/minified files are only skipped when named `*.min.js` / `*.min.mjs`; exclude hashed chunk directories with your own `exclude` patterns.
|
|
282
283
|
- Modules that only exist on a non-CPython host (Jython's `java.*`, Emscripten's `js` / `pyodide`) are reported unless you add them to `ignoreModules`.
|
|
283
284
|
- A path whose name matches a subcommand (`rules/`, `init/`, `scan/`) is parsed as the subcommand; write `./rules` to scan that directory.
|
|
284
285
|
|
|
@@ -296,7 +297,7 @@ Issues and pull requests are welcome. Start with [CONTRIBUTING.md](https://githu
|
|
|
296
297
|
git clone https://github.com/VoidH4x0r/slopgate
|
|
297
298
|
cd slopgate
|
|
298
299
|
npm install
|
|
299
|
-
npm test #
|
|
300
|
+
npm test # 228 tests; the tests themselves make no network or child-process calls
|
|
300
301
|
npm run typecheck
|
|
301
302
|
npm run verify # all release gates in one command
|
|
302
303
|
```
|
package/dist/files.js
CHANGED
|
@@ -17,30 +17,18 @@ export const DEFAULT_INCLUDE = [
|
|
|
17
17
|
'**/*.ts', '**/*.mts', '**/*.cts', '**/*.tsx',
|
|
18
18
|
'**/*.js', '**/*.mjs', '**/*.cjs', '**/*.jsx',
|
|
19
19
|
];
|
|
20
|
-
const
|
|
21
|
-
'.py': 'python',
|
|
22
|
-
'.pyi': 'python',
|
|
23
|
-
'.ts': 'typescript',
|
|
24
|
-
'.mts': 'typescript',
|
|
25
|
-
'.cts': 'typescript',
|
|
26
|
-
'.tsx': 'tsx',
|
|
27
|
-
'.jsx': 'tsx',
|
|
20
|
+
const EXTENSIONS = {
|
|
21
|
+
'.py': { language: 'python', dialect: 'python' },
|
|
22
|
+
'.pyi': { language: 'python', dialect: 'python' },
|
|
23
|
+
'.ts': { language: 'typescript', dialect: 'typescript' },
|
|
24
|
+
'.mts': { language: 'typescript', dialect: 'typescript' },
|
|
25
|
+
'.cts': { language: 'typescript', dialect: 'typescript' },
|
|
26
|
+
'.tsx': { language: 'tsx', dialect: 'tsx' },
|
|
28
27
|
// JSX is legal in .js, and the tsx grammar is a superset of plain JS.
|
|
29
|
-
'.js': 'tsx',
|
|
30
|
-
'.
|
|
31
|
-
'.
|
|
32
|
-
}
|
|
33
|
-
const EXTENSION_DIALECT = {
|
|
34
|
-
'.py': 'python',
|
|
35
|
-
'.pyi': 'python',
|
|
36
|
-
'.ts': 'typescript',
|
|
37
|
-
'.mts': 'typescript',
|
|
38
|
-
'.cts': 'typescript',
|
|
39
|
-
'.tsx': 'tsx',
|
|
40
|
-
'.js': 'javascript',
|
|
41
|
-
'.jsx': 'javascript',
|
|
42
|
-
'.mjs': 'javascript',
|
|
43
|
-
'.cjs': 'javascript',
|
|
28
|
+
'.js': { language: 'tsx', dialect: 'javascript' },
|
|
29
|
+
'.jsx': { language: 'tsx', dialect: 'javascript' },
|
|
30
|
+
'.mjs': { language: 'tsx', dialect: 'javascript' },
|
|
31
|
+
'.cjs': { language: 'tsx', dialect: 'javascript' },
|
|
44
32
|
};
|
|
45
33
|
const MAX_FILE_BYTES = 1024 * 1024;
|
|
46
34
|
export function toPosix(p) {
|
|
@@ -137,14 +125,13 @@ export function languageFor(fileName) {
|
|
|
137
125
|
if (fileName.endsWith('.d.ts') || fileName.endsWith('.d.mts') || fileName.endsWith('.d.cts')) {
|
|
138
126
|
return undefined;
|
|
139
127
|
}
|
|
140
|
-
|
|
141
|
-
return EXTENSION_LANGUAGE[ext];
|
|
128
|
+
return EXTENSIONS[path.extname(fileName).toLowerCase()]?.language;
|
|
142
129
|
}
|
|
143
130
|
export function dialectFor(fileName) {
|
|
144
131
|
if (fileName.endsWith('.d.ts') || fileName.endsWith('.d.mts') || fileName.endsWith('.d.cts')) {
|
|
145
132
|
return undefined;
|
|
146
133
|
}
|
|
147
|
-
return
|
|
134
|
+
return EXTENSIONS[path.extname(fileName).toLowerCase()]?.dialect;
|
|
148
135
|
}
|
|
149
136
|
export async function discoverFiles(options) {
|
|
150
137
|
const root = path.resolve(options.root);
|
package/dist/mcp.js
CHANGED
|
@@ -121,12 +121,18 @@ export function createMcpServer(deps) {
|
|
|
121
121
|
return textResult(`Refusing to scan outside the repository root: ${target}`, true);
|
|
122
122
|
}
|
|
123
123
|
const result = await deps.scan(target);
|
|
124
|
+
if (result.stats.files === 0) {
|
|
125
|
+
return textResult(`No files matched under ${target} (check include/exclude patterns)`, true);
|
|
126
|
+
}
|
|
124
127
|
const visible = result.findings.filter((finding) => meetsConfidence(finding.confidence, confidence));
|
|
125
128
|
return textResult(formatFindings(visible, result, deps.version, max));
|
|
126
129
|
}
|
|
127
130
|
if (name === 'scan_diff') {
|
|
128
131
|
const base = typeof params.base === 'string' && params.base.length > 0 ? params.base : 'HEAD';
|
|
129
132
|
const result = await deps.scan(deps.root);
|
|
133
|
+
if (result.stats.files === 0) {
|
|
134
|
+
return textResult('No files matched in the repository (check include/exclude patterns)', true);
|
|
135
|
+
}
|
|
130
136
|
const set = await deps.diff(deps.root, base);
|
|
131
137
|
const inDiff = result.findings.filter((finding) => isInDiff(finding, set) && meetsConfidence(finding.confidence, confidence));
|
|
132
138
|
const preamble = `Diff since ${base}: ${inDiff.length} finding(s) on changed lines.`;
|
package/dist/rules/helpers.d.ts
CHANGED
|
@@ -40,6 +40,8 @@ export declare function isNoopModulePath(file: string): boolean;
|
|
|
40
40
|
export declare function looksLikeTestModule(file: string): boolean;
|
|
41
41
|
/** Text of the function's leading docstring, if it has one. */
|
|
42
42
|
export declare function docstringOf(fn: AstNode): string | undefined;
|
|
43
|
+
/** Text of the module's leading docstring, if it has one. */
|
|
44
|
+
export declare function moduleDocstring(root: AstNode): string | undefined;
|
|
43
45
|
/** True when the function's body starts with a docstring. */
|
|
44
46
|
export declare function hasDocstring(fn: AstNode): boolean;
|
|
45
47
|
/** True when the node sits inside `if __name__ == "__main__":`. */
|
package/dist/rules/helpers.js
CHANGED
|
@@ -66,6 +66,7 @@ export function collectCommentRanges(root) {
|
|
|
66
66
|
return descendantsOfType(root, ['comment', 'line_comment', 'block_comment']).map((node) => ({
|
|
67
67
|
startLine: node.startPosition.row + 1,
|
|
68
68
|
endLine: node.endPosition.row + 1,
|
|
69
|
+
startColumn: node.startPosition.column + 1,
|
|
69
70
|
}));
|
|
70
71
|
}
|
|
71
72
|
/**
|
|
@@ -111,15 +112,17 @@ export function isStubFile(file) {
|
|
|
111
112
|
}
|
|
112
113
|
/**
|
|
113
114
|
* Modules whose whole purpose is to provide no-op stand-ins (CPython's
|
|
114
|
-
* `multiprocessing/dummy`).
|
|
115
|
-
*
|
|
115
|
+
* `multiprocessing/dummy`, `dummy_threading.py`). Directory names must match
|
|
116
|
+
* exactly; file names may use the `dummy_`/`noop_` convention. `dummy_data/`
|
|
117
|
+
* is a normal package and `shims/` can contain unfinished code.
|
|
116
118
|
*/
|
|
117
|
-
const
|
|
119
|
+
const NOOP_DIRS = new Set(['dummy', '_dummy', 'noop', 'no_op', 'no-op']);
|
|
118
120
|
export function isNoopModulePath(file) {
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
121
|
+
const parts = file.toLowerCase().split('/');
|
|
122
|
+
if (parts.slice(0, -1).some((part) => NOOP_DIRS.has(part)))
|
|
123
|
+
return true;
|
|
124
|
+
const stem = (parts[parts.length - 1] ?? '').replace(/\.pyi?$/, '');
|
|
125
|
+
return /^_?(dummy|noop|no_op|no-op)(_|$)/.test(stem);
|
|
123
126
|
}
|
|
124
127
|
/** True when the file name follows a test-module convention. */
|
|
125
128
|
export function looksLikeTestModule(file) {
|
|
@@ -137,6 +140,14 @@ export function docstringOf(fn) {
|
|
|
137
140
|
const value = first.namedChildren[0];
|
|
138
141
|
return value?.type === 'string' ? value.text : undefined;
|
|
139
142
|
}
|
|
143
|
+
/** Text of the module's leading docstring, if it has one. */
|
|
144
|
+
export function moduleDocstring(root) {
|
|
145
|
+
const first = root.namedChildren.find((child) => !isComment(child));
|
|
146
|
+
if (first?.type !== 'expression_statement')
|
|
147
|
+
return undefined;
|
|
148
|
+
const value = first.namedChildren[0];
|
|
149
|
+
return value?.type === 'string' ? value.text : undefined;
|
|
150
|
+
}
|
|
140
151
|
/** True when the function's body starts with a docstring. */
|
|
141
152
|
export function hasDocstring(fn) {
|
|
142
153
|
const body = fn.childForFieldName('body');
|
package/dist/rules/python.js
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import { normalizePythonName } from "../deps.js";
|
|
2
2
|
import { IMPLICIT_MODULES, IMPORT_TO_DISTRIBUTION, PYTHON_STDLIB } from "../data/python-stdlib.js";
|
|
3
|
-
import { ancestorOfType, collapseWhitespace, descendantsOfType, endOf, hasCommentBetween, hasDocstring, docstringOf, insideCleanupFunction, insideMainGuard, isComment, isNoopModulePath, isStubFile, isTestPath, looksLikeTestModule, snippetOf, startOf, statementsOf, truncate, walk, } from "./helpers.js";
|
|
3
|
+
import { ancestorOfType, collapseWhitespace, descendantsOfType, endOf, hasCommentBetween, hasDocstring, docstringOf, insideCleanupFunction, insideMainGuard, isComment, isNoopModulePath, isStubFile, isTestPath, looksLikeTestModule, moduleDocstring, snippetOf, startOf, statementsOf, truncate, walk, } from "./helpers.js";
|
|
4
4
|
const TERMINATORS = new Set([
|
|
5
5
|
'return_statement',
|
|
6
6
|
'raise_statement',
|
|
@@ -401,7 +401,7 @@ const stubBody = {
|
|
|
401
401
|
if (isTestPath(ctx.file))
|
|
402
402
|
return [];
|
|
403
403
|
// Type stubs and deliberate no-op shims are made of `pass`/`...`.
|
|
404
|
-
if (isStubFile(ctx.file) || isNoopModulePath(ctx.file))
|
|
404
|
+
if (isStubFile(ctx.file) || isNoopModulePath(ctx.file) || isDocumentedNoopDirectory(ctx))
|
|
405
405
|
return [];
|
|
406
406
|
const drafts = [];
|
|
407
407
|
for (const fn of descendantsOfType(ctx.root, ['function_definition'])) {
|
|
@@ -452,6 +452,54 @@ const stubBody = {
|
|
|
452
452
|
return drafts;
|
|
453
453
|
},
|
|
454
454
|
};
|
|
455
|
+
/** A comment that explains why a failure is safe to ignore. */
|
|
456
|
+
const FAILURE_WORDS = /error|fail|throw|exception|invalid|log|raise/i;
|
|
457
|
+
const INTENT_WORDS = /ignor\w*|abort|skip|safe|accept|fallback|best effort|tolerate|\bok\b|fine/i;
|
|
458
|
+
const STRONG_EXPLANATION = /harmless|benign|intentional|by design|safe to ignore|expected (?:error|failure|exception|behaviou?r)/i;
|
|
459
|
+
/** Comments that describe future work, not why an error is safe to ignore. */
|
|
460
|
+
const NOISE_COMMENT = /(?:^|\s)(TODO|FIXME|XXX|HACK)\b|refactor|cleanup|next sprint/i;
|
|
461
|
+
function isExplanationText(text) {
|
|
462
|
+
return STRONG_EXPLANATION.test(text) || (FAILURE_WORDS.test(text) && INTENT_WORDS.test(text));
|
|
463
|
+
}
|
|
464
|
+
function overlaps(comment, fromLine, toLine) {
|
|
465
|
+
return comment.startLine <= toLine && comment.endLine >= fromLine;
|
|
466
|
+
}
|
|
467
|
+
/** A comment is standalone when only whitespace precedes its marker. */
|
|
468
|
+
function isStandaloneComment(ctx, comment) {
|
|
469
|
+
const line = ctx.lines[comment.startLine - 1] ?? '';
|
|
470
|
+
return line.slice(0, Math.max(0, comment.startColumn - 1)).trim().length === 0;
|
|
471
|
+
}
|
|
472
|
+
function commentText(ctx, comment) {
|
|
473
|
+
return ctx.lines.slice(comment.startLine - 1, comment.endLine).join(' ');
|
|
474
|
+
}
|
|
475
|
+
function explanationCommentBetween(ctx, fromLine, toLine) {
|
|
476
|
+
return ctx.comments.some((comment) => overlaps(comment, fromLine, toLine) &&
|
|
477
|
+
isStandaloneComment(ctx, comment) &&
|
|
478
|
+
isExplanationText(commentText(ctx, comment)));
|
|
479
|
+
}
|
|
480
|
+
function supportingCommentBetween(ctx, fromLine, toLine, handlerStartLine) {
|
|
481
|
+
return ctx.comments.some((comment) => {
|
|
482
|
+
if (!overlaps(comment, fromLine, toLine))
|
|
483
|
+
return false;
|
|
484
|
+
const text = commentText(ctx, comment);
|
|
485
|
+
if (NOISE_COMMENT.test(text))
|
|
486
|
+
return false;
|
|
487
|
+
// A comment on the `pass` line is unambiguously about that handler, so it
|
|
488
|
+
// may be inline. Comments before the handler must start their own line:
|
|
489
|
+
// a trailing comment on a previous statement often describes that
|
|
490
|
+
// statement, not the exception.
|
|
491
|
+
return isStandaloneComment(ctx, comment) || comment.startLine >= handlerStartLine;
|
|
492
|
+
});
|
|
493
|
+
}
|
|
494
|
+
const NOOP_DIR_PREFIX = /^(dummy|noop|no_op|no-op)[-_]/;
|
|
495
|
+
const NOOP_MODULE_DOC = /dummy implementation|deliberate(?:ly)? no-?op|single-threaded|faux implementation|stand-?in|shim module/i;
|
|
496
|
+
/** A prefixed directory is only a shim when its module docstring says so. */
|
|
497
|
+
function isDocumentedNoopDirectory(ctx) {
|
|
498
|
+
const dirs = ctx.file.toLowerCase().split('/').slice(0, -1);
|
|
499
|
+
if (!dirs.some((dir) => NOOP_DIR_PREFIX.test(dir)))
|
|
500
|
+
return false;
|
|
501
|
+
return NOOP_MODULE_DOC.test(moduleDocstring(ctx.root) ?? '');
|
|
502
|
+
}
|
|
455
503
|
const swallowedException = {
|
|
456
504
|
meta: {
|
|
457
505
|
id: 'py/swallowed-exception',
|
|
@@ -473,6 +521,9 @@ const swallowedException = {
|
|
|
473
521
|
if (tryNode.namedChildren.some((child) => child.type === 'else_clause'))
|
|
474
522
|
continue;
|
|
475
523
|
const tryBody = tryNode.namedChildren.find((child) => child.type === 'block');
|
|
524
|
+
// A comment immediately above `try` often explains the failure policy.
|
|
525
|
+
const aboveStart = Math.max(1, tryNode.startPosition.row);
|
|
526
|
+
const above = explanationCommentBetween(ctx, aboveStart, tryNode.startPosition.row + 1);
|
|
476
527
|
/** 0-based end row of the previous region, or -1 when there is no try body. */
|
|
477
528
|
let previousEndRow = tryBody ? tryBody.endPosition.row : -1;
|
|
478
529
|
for (const clause of tryNode.namedChildren) {
|
|
@@ -485,7 +536,7 @@ const swallowedException = {
|
|
|
485
536
|
// handler can explain this handler; comments inside the try body
|
|
486
537
|
// cannot. Advance the cursor for every handler, silent or not.
|
|
487
538
|
const handlerEndRow = body.endPosition.row;
|
|
488
|
-
const
|
|
539
|
+
const betweenStart = previousEndRow >= 0 ? previousEndRow + 2 : clause.startPosition.row + 1;
|
|
489
540
|
previousEndRow = handlerEndRow;
|
|
490
541
|
const statements = statementsOf(body);
|
|
491
542
|
const silent = statements.length === 0 ||
|
|
@@ -503,7 +554,8 @@ const swallowedException = {
|
|
|
503
554
|
// Optional-dependency idiom: swallowing a missing import is the point.
|
|
504
555
|
if (/ImportError|ModuleNotFoundError/.test(typeText))
|
|
505
556
|
continue;
|
|
506
|
-
const commented =
|
|
557
|
+
const commented = above ||
|
|
558
|
+
supportingCommentBetween(ctx, betweenStart, handlerEndRow + 1, body.startPosition.row + 1);
|
|
507
559
|
const bare = typeText.length === 0;
|
|
508
560
|
const broad = bare || /^(\(?\s*)?(Exception|BaseException)(\s*\))?$/.test(typeText);
|
|
509
561
|
const cleanup = insideCleanupFunction(clause);
|
package/dist/rules/typescript.js
CHANGED
|
@@ -65,7 +65,57 @@ function matchesAlias(specifier, aliases) {
|
|
|
65
65
|
return specifier === clean || specifier.startsWith(`${clean}/`);
|
|
66
66
|
});
|
|
67
67
|
}
|
|
68
|
-
const
|
|
68
|
+
const NODE_ASSERT_SPECIFIERS = new Set(['node:assert', 'node:assert/strict']);
|
|
69
|
+
function addAssertBinding(aliases, part) {
|
|
70
|
+
const match = /^\s*(?:type\s+)?([A-Za-z_$][\w$]*)(?:\s+as\s+([A-Za-z_$][\w$]*))?\s*$/.exec(part);
|
|
71
|
+
if (match?.[1])
|
|
72
|
+
aliases.add(match[2] ?? match[1]);
|
|
73
|
+
}
|
|
74
|
+
/** Local names bound to `node:assert` / `node:assert/strict`. */
|
|
75
|
+
function assertAliases(root) {
|
|
76
|
+
const aliases = new Set();
|
|
77
|
+
for (const node of descendantsOfType(root, ['import_statement'])) {
|
|
78
|
+
const specifier = sourceString(node);
|
|
79
|
+
if (!specifier || !NODE_ASSERT_SPECIFIERS.has(specifier))
|
|
80
|
+
continue;
|
|
81
|
+
const text = node.text;
|
|
82
|
+
const namespace = /import\s+\*\s+as\s+([A-Za-z_$][\w$]*)/.exec(text);
|
|
83
|
+
if (namespace?.[1])
|
|
84
|
+
aliases.add(namespace[1]);
|
|
85
|
+
const defaultImport = /import\s+([A-Za-z_$][\w$]*)\s*(?:,|from)/.exec(text);
|
|
86
|
+
if (defaultImport?.[1])
|
|
87
|
+
aliases.add(defaultImport[1]);
|
|
88
|
+
const named = /\{([^}]*)\}/.exec(text);
|
|
89
|
+
if (named?.[1]) {
|
|
90
|
+
for (const part of named[1].split(','))
|
|
91
|
+
addAssertBinding(aliases, part);
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
for (const call of descendantsOfType(root, ['call_expression'])) {
|
|
95
|
+
const fn = call.childForFieldName('function');
|
|
96
|
+
if (!fn || collapseWhitespace(fn.text) !== 'require')
|
|
97
|
+
continue;
|
|
98
|
+
const args = call.childForFieldName('arguments');
|
|
99
|
+
const specifier = stringLiteralValue(args?.namedChildren[0]);
|
|
100
|
+
if (!specifier || !NODE_ASSERT_SPECIFIERS.has(specifier))
|
|
101
|
+
continue;
|
|
102
|
+
const declarator = ancestorOfType(call, ['variable_declarator']);
|
|
103
|
+
const name = declarator?.childForFieldName('name')?.text;
|
|
104
|
+
if (!name)
|
|
105
|
+
continue;
|
|
106
|
+
if (/^[A-Za-z_$][\w$]*$/.test(name)) {
|
|
107
|
+
aliases.add(name);
|
|
108
|
+
}
|
|
109
|
+
else {
|
|
110
|
+
const pattern = /\{([^}]*)\}/.exec(name);
|
|
111
|
+
if (pattern?.[1]) {
|
|
112
|
+
for (const part of pattern[1].split(','))
|
|
113
|
+
addAssertBinding(aliases, part);
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
return aliases;
|
|
118
|
+
}
|
|
69
119
|
const T_ASSERTION_MEMBERS = new Set([
|
|
70
120
|
'ok',
|
|
71
121
|
'is',
|
|
@@ -78,15 +128,36 @@ const T_ASSERTION_MEMBERS = new Set([
|
|
|
78
128
|
'pass',
|
|
79
129
|
'fail',
|
|
80
130
|
'assert',
|
|
131
|
+
// Tape / TAP. The `t.` prefix is required, so these cannot match arbitrary
|
|
132
|
+
// `.equal` calls from other libraries.
|
|
133
|
+
'equal',
|
|
134
|
+
'equals',
|
|
135
|
+
'notEqual',
|
|
136
|
+
'deepEqual',
|
|
137
|
+
'notDeepEqual',
|
|
138
|
+
'looseEqual',
|
|
139
|
+
'notLooseEqual',
|
|
140
|
+
'deepLooseEqual',
|
|
141
|
+
'notDeepLooseEqual',
|
|
142
|
+
'strictEqual',
|
|
143
|
+
'notStrictEqual',
|
|
144
|
+
'error',
|
|
145
|
+
'notOk',
|
|
146
|
+
'doesNotThrow',
|
|
147
|
+
'notMatch',
|
|
81
148
|
]);
|
|
82
149
|
/**
|
|
83
150
|
* Test whether a call is an assertion. The full callee path matters:
|
|
84
151
|
* `assert.strictEqual` ends in `strictEqual`, which the old last-segment
|
|
85
152
|
* regex missed, so node:assert-based tests were reported as assertion-free.
|
|
86
153
|
*/
|
|
87
|
-
function isAssertionCallee(text) {
|
|
154
|
+
function isAssertionCallee(text, aliases) {
|
|
88
155
|
if (text.length === 0)
|
|
89
156
|
return false;
|
|
157
|
+
// Renamed imports: nodeAssert.strictEqual, strictAssert.equal, eq(...).
|
|
158
|
+
const root = text.split(/[.(]/)[0] ?? '';
|
|
159
|
+
if (aliases.has(root))
|
|
160
|
+
return true;
|
|
90
161
|
// node:assert and node:assert/strict: assert(...) plus every method.
|
|
91
162
|
if (text === 'assert' || text.startsWith('assert.'))
|
|
92
163
|
return true;
|
|
@@ -112,7 +183,7 @@ function isAssertionCallee(text) {
|
|
|
112
183
|
}
|
|
113
184
|
return false;
|
|
114
185
|
}
|
|
115
|
-
function hasAssertion(body) {
|
|
186
|
+
function hasAssertion(body, aliases) {
|
|
116
187
|
let found = false;
|
|
117
188
|
walk(body, (node) => {
|
|
118
189
|
if (found)
|
|
@@ -120,7 +191,7 @@ function hasAssertion(body) {
|
|
|
120
191
|
if (node.type === 'call_expression') {
|
|
121
192
|
const fn = node.childForFieldName('function') ?? node.namedChildren[0];
|
|
122
193
|
const text = collapseWhitespace(fn?.text ?? '');
|
|
123
|
-
if (isAssertionCallee(text)) {
|
|
194
|
+
if (isAssertionCallee(text, aliases)) {
|
|
124
195
|
found = true;
|
|
125
196
|
return false;
|
|
126
197
|
}
|
|
@@ -237,6 +308,7 @@ const noopTest = {
|
|
|
237
308
|
if (ctx.language === 'python')
|
|
238
309
|
return [];
|
|
239
310
|
const drafts = [];
|
|
311
|
+
const aliases = assertAliases(ctx.root);
|
|
240
312
|
for (const call of descendantsOfType(ctx.root, ['call_expression'])) {
|
|
241
313
|
const fn = call.childForFieldName('function');
|
|
242
314
|
if (!fn || !isTestCall(fn))
|
|
@@ -254,7 +326,7 @@ const noopTest = {
|
|
|
254
326
|
continue;
|
|
255
327
|
const label = args.namedChildren[0]?.type === 'string' ? truncate(args.namedChildren[0].text, 60) : undefined;
|
|
256
328
|
if (body.type !== 'statement_block') {
|
|
257
|
-
if (!hasAssertion(body)) {
|
|
329
|
+
if (!hasAssertion(body, aliases)) {
|
|
258
330
|
drafts.push({
|
|
259
331
|
message: 'test makes no assertions',
|
|
260
332
|
start: startOf(call),
|
|
@@ -278,7 +350,7 @@ const noopTest = {
|
|
|
278
350
|
});
|
|
279
351
|
continue;
|
|
280
352
|
}
|
|
281
|
-
if (!hasAssertion(body)) {
|
|
353
|
+
if (!hasAssertion(body, aliases)) {
|
|
282
354
|
drafts.push({
|
|
283
355
|
message: 'test makes no assertions',
|
|
284
356
|
start: startOf(call),
|
|
@@ -408,9 +480,10 @@ const stubFunction = {
|
|
|
408
480
|
end: endOf(body),
|
|
409
481
|
snippet: snippetOf(ctx, node),
|
|
410
482
|
// An empty body is a weak signal in JavaScript: callbacks and dispatch
|
|
411
|
-
// tables legitimately do nothing.
|
|
412
|
-
//
|
|
413
|
-
|
|
483
|
+
// tables legitimately do nothing. A class method that throws
|
|
484
|
+
// "not implemented" is also the standard way to declare an interface
|
|
485
|
+
// member for subclasses, so only standalone functions keep high.
|
|
486
|
+
confidence: form === 'empty body' || node.type === 'method_definition' ? 'medium' : 'high',
|
|
414
487
|
evidence: [`body: ${form}`],
|
|
415
488
|
help: 'Implement it, or throw an error with a message so callers fail loudly instead of silently doing nothing.',
|
|
416
489
|
});
|
|
@@ -504,6 +577,8 @@ const deadBranch = {
|
|
|
504
577
|
continue;
|
|
505
578
|
if (isTrue && node.type === 'while_statement')
|
|
506
579
|
continue;
|
|
580
|
+
// A nearby comment usually marks a deliberate disabled branch.
|
|
581
|
+
const commented = hasCommentBetween(ctx, Math.max(1, node.startPosition.row), node.endPosition.row + 1);
|
|
507
582
|
drafts.push({
|
|
508
583
|
message: isFalse
|
|
509
584
|
? `\`${node.type === 'while_statement' ? 'while' : 'if'} (${text})\` is dead code`
|
|
@@ -511,14 +586,31 @@ const deadBranch = {
|
|
|
511
586
|
start: startOf(node),
|
|
512
587
|
end: endOf(condition),
|
|
513
588
|
snippet: snippetOf(ctx, node),
|
|
514
|
-
confidence: isFalse ? 'high' : 'medium',
|
|
515
|
-
evidence: [
|
|
589
|
+
confidence: isFalse && !commented ? 'high' : 'medium',
|
|
590
|
+
evidence: [
|
|
591
|
+
`condition: ${text}`,
|
|
592
|
+
...(commented ? ['a nearby comment suggests this is a deliberate switch'] : []),
|
|
593
|
+
],
|
|
516
594
|
help: 'Replace the constant with the flag or configuration value it is standing in for.',
|
|
517
595
|
});
|
|
518
596
|
}
|
|
519
597
|
return drafts;
|
|
520
598
|
},
|
|
521
599
|
};
|
|
600
|
+
/**
|
|
601
|
+
* Function declarations and bare `var` statements are hoisted: they are usable
|
|
602
|
+
* before a `return` even when written after it. `let`/`const` and initialised
|
|
603
|
+
* `var` statements execute at their position, so they remain genuinely dead.
|
|
604
|
+
*/
|
|
605
|
+
function isHoistedDeclaration(statement) {
|
|
606
|
+
if (statement.type === 'function_declaration' || statement.type === 'generator_function_declaration') {
|
|
607
|
+
return true;
|
|
608
|
+
}
|
|
609
|
+
if (statement.type !== 'variable_declaration')
|
|
610
|
+
return false;
|
|
611
|
+
const declarators = statement.namedChildren.filter((child) => child.type === 'variable_declarator');
|
|
612
|
+
return declarators.length > 0 && declarators.every((declarator) => !declarator.childForFieldName('value'));
|
|
613
|
+
}
|
|
522
614
|
const unreachable = {
|
|
523
615
|
meta: {
|
|
524
616
|
id: 'ts/unreachable',
|
|
@@ -541,8 +633,10 @@ const unreachable = {
|
|
|
541
633
|
if (index === -1)
|
|
542
634
|
continue;
|
|
543
635
|
const terminator = statements[index];
|
|
544
|
-
|
|
545
|
-
|
|
636
|
+
if (!terminator)
|
|
637
|
+
continue;
|
|
638
|
+
const firstUnreachable = statements.slice(index + 1).find((statement) => !isHoistedDeclaration(statement));
|
|
639
|
+
if (!firstUnreachable)
|
|
546
640
|
continue;
|
|
547
641
|
const count = statements.length - index - 1;
|
|
548
642
|
const keyword = terminator.type.replace('_statement', '');
|
package/dist/types.d.ts
CHANGED
|
@@ -15,6 +15,8 @@ export interface Position {
|
|
|
15
15
|
export interface CommentRange {
|
|
16
16
|
startLine: number;
|
|
17
17
|
endLine: number;
|
|
18
|
+
/** 1-based column of the comment marker, for standalone-comment checks. */
|
|
19
|
+
startColumn: number;
|
|
18
20
|
}
|
|
19
21
|
export interface Finding {
|
|
20
22
|
ruleId: string;
|