@voidh4x0r/slopgate 0.0.0-stage → 0.1.1
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 +82 -0
- package/LICENSE +21 -0
- package/README.md +304 -2
- package/dist/ast.d.ts +29 -0
- package/dist/ast.js +3 -0
- package/dist/baseline.d.ts +33 -0
- package/dist/baseline.js +104 -0
- package/dist/cli.d.ts +9 -0
- package/dist/cli.js +487 -0
- package/dist/config.d.ts +25 -0
- package/dist/config.js +91 -0
- package/dist/data/python-stdlib.d.ts +21 -0
- package/dist/data/python-stdlib.js +92 -0
- package/dist/deps.d.ts +8 -0
- package/dist/deps.js +491 -0
- package/dist/diff.d.ts +30 -0
- package/dist/diff.js +217 -0
- package/dist/engine.d.ts +15 -0
- package/dist/engine.js +169 -0
- package/dist/files.d.ts +33 -0
- package/dist/files.js +214 -0
- package/dist/mcp.d.ts +41 -0
- package/dist/mcp.js +226 -0
- package/dist/parser.d.ts +3 -0
- package/dist/parser.js +45 -0
- package/dist/reporters/github.d.ts +2 -0
- package/dist/reporters/github.js +44 -0
- package/dist/reporters/json.d.ts +10 -0
- package/dist/reporters/json.js +36 -0
- package/dist/reporters/pretty.d.ts +12 -0
- package/dist/reporters/pretty.js +103 -0
- package/dist/reporters/sarif.d.ts +2 -0
- package/dist/reporters/sarif.js +75 -0
- package/dist/rules/helpers.d.ts +53 -0
- package/dist/rules/helpers.js +178 -0
- package/dist/rules/index.d.ts +3 -0
- package/dist/rules/index.js +4 -0
- package/dist/rules/python.d.ts +2 -0
- package/dist/rules/python.js +632 -0
- package/dist/rules/typescript.d.ts +2 -0
- package/dist/rules/typescript.js +563 -0
- package/dist/suppress.d.ts +12 -0
- package/dist/suppress.js +52 -0
- package/dist/types.d.ts +95 -0
- package/dist/types.js +1 -0
- package/grammars/README.md +28 -0
- package/grammars/tree-sitter-python.wasm +0 -0
- package/grammars/tree-sitter-tsx.wasm +0 -0
- package/grammars/tree-sitter-typescript.wasm +0 -0
- package/package.json +61 -4
|
@@ -0,0 +1,632 @@
|
|
|
1
|
+
import { normalizePythonName } from "../deps.js";
|
|
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";
|
|
4
|
+
const TERMINATORS = new Set([
|
|
5
|
+
'return_statement',
|
|
6
|
+
'raise_statement',
|
|
7
|
+
'break_statement',
|
|
8
|
+
'continue_statement',
|
|
9
|
+
]);
|
|
10
|
+
function pythonImports(root) {
|
|
11
|
+
const imports = [];
|
|
12
|
+
for (const node of descendantsOfType(root, ['import_statement', 'import_from_statement'])) {
|
|
13
|
+
if (node.type === 'import_statement') {
|
|
14
|
+
for (const child of node.namedChildren) {
|
|
15
|
+
if (isComment(child))
|
|
16
|
+
continue;
|
|
17
|
+
const target = child.type === 'aliased_import' ? child.childForFieldName('name') : child;
|
|
18
|
+
const full = collapseWhitespace(target?.text ?? '');
|
|
19
|
+
const first = full.split('.')[0];
|
|
20
|
+
if (first)
|
|
21
|
+
imports.push({ node, module: full, root: first });
|
|
22
|
+
}
|
|
23
|
+
continue;
|
|
24
|
+
}
|
|
25
|
+
// `from .x import y` and `from . import y` are local by construction.
|
|
26
|
+
if (node.namedChildren.some((child) => child.type === 'relative_import'))
|
|
27
|
+
continue;
|
|
28
|
+
const moduleNode = node.namedChildren.find((child) => child.type === 'dotted_name');
|
|
29
|
+
const full = collapseWhitespace(moduleNode?.text ?? '');
|
|
30
|
+
const first = full.split('.')[0];
|
|
31
|
+
if (first)
|
|
32
|
+
imports.push({ node, module: full, root: first });
|
|
33
|
+
}
|
|
34
|
+
return imports;
|
|
35
|
+
}
|
|
36
|
+
/** `try: import ujson except ImportError: ...` is an optional dependency. */
|
|
37
|
+
function isOptionalImport(node) {
|
|
38
|
+
const tryNode = ancestorOfType(node, ['try_statement']);
|
|
39
|
+
if (!tryNode)
|
|
40
|
+
return false;
|
|
41
|
+
return /ImportError|ModuleNotFoundError/.test(tryNode.text);
|
|
42
|
+
}
|
|
43
|
+
const DISTRIBUTION_PREFIXES = Object.keys(IMPORT_TO_DISTRIBUTION).sort((a, b) => b.length - a.length);
|
|
44
|
+
/** Longest dotted import prefix that has an explicit distribution mapping. */
|
|
45
|
+
function distributionFor(module) {
|
|
46
|
+
for (const prefix of DISTRIBUTION_PREFIXES) {
|
|
47
|
+
if (module === prefix || module.startsWith(`${prefix}.`)) {
|
|
48
|
+
return IMPORT_TO_DISTRIBUTION[prefix];
|
|
49
|
+
}
|
|
50
|
+
}
|
|
51
|
+
return undefined;
|
|
52
|
+
}
|
|
53
|
+
function isDeclaredPython(module, ctx) {
|
|
54
|
+
const deps = ctx.deps.python;
|
|
55
|
+
const parts = module.split('.');
|
|
56
|
+
// A manifest declares distributions, but same-name packages (`requests`)
|
|
57
|
+
// and dotted namespace packages (`google.protobuf`) both appear here.
|
|
58
|
+
for (let index = parts.length; index > 0; index -= 1) {
|
|
59
|
+
const candidate = parts.slice(0, index).join('.');
|
|
60
|
+
if (deps.declared.has(normalizePythonName(candidate)))
|
|
61
|
+
return true;
|
|
62
|
+
}
|
|
63
|
+
const distribution = distributionFor(module);
|
|
64
|
+
if (distribution && deps.declared.has(normalizePythonName(distribution)))
|
|
65
|
+
return true;
|
|
66
|
+
return false;
|
|
67
|
+
}
|
|
68
|
+
function testFunctionName(fn) {
|
|
69
|
+
const name = fn.childForFieldName('name')?.text;
|
|
70
|
+
if (!name)
|
|
71
|
+
return undefined;
|
|
72
|
+
if (name.startsWith('test_') || /^test[A-Z0-9]/.test(name))
|
|
73
|
+
return name;
|
|
74
|
+
return undefined;
|
|
75
|
+
}
|
|
76
|
+
const ASSERTION_CALLEE = /(^|\.)(assert\w*|raises|expect|expects|should\w*|fail|check|verify|match_snapshot)$/;
|
|
77
|
+
function hasAssertion(body) {
|
|
78
|
+
let found = false;
|
|
79
|
+
walk(body, (node) => {
|
|
80
|
+
if (found)
|
|
81
|
+
return false;
|
|
82
|
+
if (node.type === 'assert_statement') {
|
|
83
|
+
found = true;
|
|
84
|
+
return false;
|
|
85
|
+
}
|
|
86
|
+
if (node.type === 'call') {
|
|
87
|
+
const fnText = collapseWhitespace(node.childForFieldName('function')?.text ?? '');
|
|
88
|
+
const last = fnText.split('.').pop() ?? '';
|
|
89
|
+
if (ASSERTION_CALLEE.test(last)) {
|
|
90
|
+
found = true;
|
|
91
|
+
return false;
|
|
92
|
+
}
|
|
93
|
+
}
|
|
94
|
+
return true;
|
|
95
|
+
});
|
|
96
|
+
return found;
|
|
97
|
+
}
|
|
98
|
+
function bodyCallsSelf(body) {
|
|
99
|
+
let found = false;
|
|
100
|
+
walk(body, (node) => {
|
|
101
|
+
if (found)
|
|
102
|
+
return false;
|
|
103
|
+
if (node.type === 'call') {
|
|
104
|
+
const fnText = collapseWhitespace(node.childForFieldName('function')?.text ?? '');
|
|
105
|
+
if (/^(self|cls)\./.test(fnText)) {
|
|
106
|
+
found = true;
|
|
107
|
+
return false;
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
return true;
|
|
111
|
+
});
|
|
112
|
+
return found;
|
|
113
|
+
}
|
|
114
|
+
function placeholderForm(block) {
|
|
115
|
+
const statements = statementsOf(block);
|
|
116
|
+
const afterDocstring = statements[0]?.type === 'expression_statement' &&
|
|
117
|
+
statements[0].namedChildren[0]?.type === 'string'
|
|
118
|
+
? statements.slice(1)
|
|
119
|
+
: statements;
|
|
120
|
+
if (afterDocstring.length !== 1)
|
|
121
|
+
return undefined;
|
|
122
|
+
const only = afterDocstring[0];
|
|
123
|
+
if (!only)
|
|
124
|
+
return undefined;
|
|
125
|
+
if (only.type === 'pass_statement')
|
|
126
|
+
return 'pass';
|
|
127
|
+
if (only.type === 'expression_statement') {
|
|
128
|
+
const text = collapseWhitespace(only.text);
|
|
129
|
+
if (text === '...')
|
|
130
|
+
return '...';
|
|
131
|
+
return undefined;
|
|
132
|
+
}
|
|
133
|
+
if (only.type === 'return_statement') {
|
|
134
|
+
const text = collapseWhitespace(only.text);
|
|
135
|
+
if (text === 'return' || text === 'return None')
|
|
136
|
+
return text;
|
|
137
|
+
return undefined;
|
|
138
|
+
}
|
|
139
|
+
if (only.type === 'raise_statement' && /NotImplementedError/.test(only.text)) {
|
|
140
|
+
return 'raise NotImplementedError';
|
|
141
|
+
}
|
|
142
|
+
return undefined;
|
|
143
|
+
}
|
|
144
|
+
const NEVER_STUBS = new Set([
|
|
145
|
+
'__init__',
|
|
146
|
+
'__new__',
|
|
147
|
+
'__post_init__',
|
|
148
|
+
'__enter__',
|
|
149
|
+
'__exit__',
|
|
150
|
+
'setUp',
|
|
151
|
+
'tearDown',
|
|
152
|
+
'setUpClass',
|
|
153
|
+
'tearDownClass',
|
|
154
|
+
]);
|
|
155
|
+
function isAbstractMember(fn) {
|
|
156
|
+
const decorated = fn.parent;
|
|
157
|
+
if (decorated && decorated.type === 'decorated_definition') {
|
|
158
|
+
const decorators = decorated.namedChildren
|
|
159
|
+
.filter((child) => child.type === 'decorator')
|
|
160
|
+
.map((child) => child.text);
|
|
161
|
+
if (decorators.some((text) => /abstractmethod|abstractproperty|overload|override/.test(text))) {
|
|
162
|
+
return true;
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
const cls = ancestorOfType(fn, ['class_definition']);
|
|
166
|
+
if (cls) {
|
|
167
|
+
const bases = cls.childForFieldName('superclasses')?.text ?? '';
|
|
168
|
+
if (/Protocol|ABC|ABCMeta/.test(bases))
|
|
169
|
+
return true;
|
|
170
|
+
}
|
|
171
|
+
const ifNode = ancestorOfType(fn, ['if_statement']);
|
|
172
|
+
if (ifNode) {
|
|
173
|
+
const condition = ifNode.childForFieldName('condition')?.text ?? '';
|
|
174
|
+
if (condition.includes('TYPE_CHECKING'))
|
|
175
|
+
return true;
|
|
176
|
+
}
|
|
177
|
+
return false;
|
|
178
|
+
}
|
|
179
|
+
function insideAbstractMethod(node) {
|
|
180
|
+
const fn = ancestorOfType(node, ['function_definition']);
|
|
181
|
+
if (!fn)
|
|
182
|
+
return false;
|
|
183
|
+
const parent = fn.parent;
|
|
184
|
+
if (parent && parent.type === 'decorated_definition') {
|
|
185
|
+
return parent.namedChildren.some((child) => child.type === 'decorator' && /abstractmethod/.test(child.text));
|
|
186
|
+
}
|
|
187
|
+
return false;
|
|
188
|
+
}
|
|
189
|
+
/** `if sys.platform == "java": from java.lang import System` is platform-specific. */
|
|
190
|
+
function insidePlatformGuard(node) {
|
|
191
|
+
let current = node.parent;
|
|
192
|
+
while (current) {
|
|
193
|
+
if (current.type === 'if_statement') {
|
|
194
|
+
const condition = current.childForFieldName('condition')?.text ?? '';
|
|
195
|
+
if (/sys\.platform|platform\.system\s*\(/.test(condition))
|
|
196
|
+
return true;
|
|
197
|
+
}
|
|
198
|
+
current = current.parent;
|
|
199
|
+
}
|
|
200
|
+
return false;
|
|
201
|
+
}
|
|
202
|
+
const phantomImport = {
|
|
203
|
+
meta: {
|
|
204
|
+
id: 'py/phantom-import',
|
|
205
|
+
title: 'Import is neither declared nor present',
|
|
206
|
+
summary: 'Adds an import that no manifest declares and no file in the repository provides. The classic signature of a package the model invented.',
|
|
207
|
+
severity: 'error',
|
|
208
|
+
confidence: 'high',
|
|
209
|
+
languages: ['python'],
|
|
210
|
+
tags: ['dependencies', 'hallucination'],
|
|
211
|
+
},
|
|
212
|
+
run(ctx) {
|
|
213
|
+
if (ctx.language !== 'python')
|
|
214
|
+
return [];
|
|
215
|
+
const drafts = [];
|
|
216
|
+
const manifests = ctx.deps.python.manifests;
|
|
217
|
+
for (const { node, module, root } of pythonImports(ctx.root)) {
|
|
218
|
+
if (PYTHON_STDLIB.has(root))
|
|
219
|
+
continue;
|
|
220
|
+
if (IMPLICIT_MODULES.has(root))
|
|
221
|
+
continue;
|
|
222
|
+
if (ctx.deps.ignoredModules.has(root) || ctx.deps.ignoredModules.has(module))
|
|
223
|
+
continue;
|
|
224
|
+
// Private C-extension modules (`_socket`, `_decimal`, `_winapi`, ...) are
|
|
225
|
+
// builtins; no project declares them in a manifest.
|
|
226
|
+
if (root.startsWith('_'))
|
|
227
|
+
continue;
|
|
228
|
+
if (isDeclaredPython(module, ctx))
|
|
229
|
+
continue;
|
|
230
|
+
if (ctx.deps.python.localModules.has(root))
|
|
231
|
+
continue;
|
|
232
|
+
if (isOptionalImport(node))
|
|
233
|
+
continue;
|
|
234
|
+
if (insidePlatformGuard(node))
|
|
235
|
+
continue;
|
|
236
|
+
drafts.push({
|
|
237
|
+
message: `\`${module}\` is imported but not declared in any manifest and not present in this repository`,
|
|
238
|
+
start: startOf(node),
|
|
239
|
+
end: endOf(node),
|
|
240
|
+
snippet: snippetOf(ctx, node),
|
|
241
|
+
// Test suites monkey-patch sys.path; keep the fact but do not fail CI.
|
|
242
|
+
...(isTestPath(ctx.file) ? { confidence: 'medium' } : {}),
|
|
243
|
+
evidence: [
|
|
244
|
+
`import: ${truncate(node.text, 100)}`,
|
|
245
|
+
manifests.length > 0
|
|
246
|
+
? `manifests checked: ${manifests.join(', ')}`
|
|
247
|
+
: 'no Python dependency manifest found (pyproject.toml, requirements*.txt, setup.py, Pipfile)',
|
|
248
|
+
],
|
|
249
|
+
help: 'Add it to your manifest, remove the import, or wrap it in try/except ImportError if it is optional.',
|
|
250
|
+
});
|
|
251
|
+
}
|
|
252
|
+
return drafts;
|
|
253
|
+
},
|
|
254
|
+
};
|
|
255
|
+
const noopTest = {
|
|
256
|
+
meta: {
|
|
257
|
+
id: 'py/noop-test',
|
|
258
|
+
title: 'Test does not assert anything',
|
|
259
|
+
summary: 'Finds `test_*` functions whose body has no assertion, no `pytest.raises`, and no mock verification. They pass no matter what the code does.',
|
|
260
|
+
severity: 'warning',
|
|
261
|
+
confidence: 'high',
|
|
262
|
+
languages: ['python'],
|
|
263
|
+
tags: ['tests', 'theater'],
|
|
264
|
+
},
|
|
265
|
+
run(ctx) {
|
|
266
|
+
if (ctx.language !== 'python')
|
|
267
|
+
return [];
|
|
268
|
+
if (isStubFile(ctx.file))
|
|
269
|
+
return [];
|
|
270
|
+
const drafts = [];
|
|
271
|
+
for (const fn of descendantsOfType(ctx.root, ['function_definition'])) {
|
|
272
|
+
const name = testFunctionName(fn);
|
|
273
|
+
if (!name)
|
|
274
|
+
continue;
|
|
275
|
+
if (insideMainGuard(fn))
|
|
276
|
+
continue;
|
|
277
|
+
const inClass = ancestorOfType(fn, ['class_definition']) !== undefined;
|
|
278
|
+
// `test_*` helpers exist in test-support tooling; only trust real test
|
|
279
|
+
// modules, or methods of a test class.
|
|
280
|
+
if (!looksLikeTestModule(ctx.file) && !inClass)
|
|
281
|
+
continue;
|
|
282
|
+
const body = fn.childForFieldName('body');
|
|
283
|
+
if (!body)
|
|
284
|
+
continue;
|
|
285
|
+
const docstring = docstringOf(fn);
|
|
286
|
+
// Doctest-style tests keep their expectations in the docstring.
|
|
287
|
+
if (docstring?.includes('>>>'))
|
|
288
|
+
continue;
|
|
289
|
+
// `def test_suite(): return DocTestSuite()` is a suite factory.
|
|
290
|
+
if (/TestSuite|load_tests/.test(body.text))
|
|
291
|
+
continue;
|
|
292
|
+
const statements = statementsOf(body).filter((statement) => !(statement.type === 'expression_statement' && statement.namedChildren[0]?.type === 'string'));
|
|
293
|
+
if (statements.length === 0) {
|
|
294
|
+
drafts.push({
|
|
295
|
+
message: `test \`${name}\` has an empty body`,
|
|
296
|
+
start: startOf(fn),
|
|
297
|
+
end: endOf(body),
|
|
298
|
+
snippet: snippetOf(ctx, fn),
|
|
299
|
+
confidence: docstring === undefined ? 'high' : 'medium',
|
|
300
|
+
evidence: [`test: ${name}`, 'body contains only a docstring or nothing'],
|
|
301
|
+
help: 'Add an assertion, or delete the test.',
|
|
302
|
+
});
|
|
303
|
+
continue;
|
|
304
|
+
}
|
|
305
|
+
if (!hasAssertion(body)) {
|
|
306
|
+
const delegatesToSelf = bodyCallsSelf(body);
|
|
307
|
+
const parameters = fn.childForFieldName('parameters');
|
|
308
|
+
const parameterCount = parameters
|
|
309
|
+
? parameters.namedChildren.filter((child) => child.type !== 'comment').length
|
|
310
|
+
: 0;
|
|
311
|
+
const decorated = fn.parent?.type === 'decorated_definition';
|
|
312
|
+
const decoratorText = decorated
|
|
313
|
+
? fn.parent?.namedChildren
|
|
314
|
+
.filter((child) => child.type === 'decorator')
|
|
315
|
+
.map((child) => child.text)
|
|
316
|
+
.join(' ') ?? ''
|
|
317
|
+
: '';
|
|
318
|
+
const helperDecorator = /contextmanager|staticmethod|classmethod|lru_cache|cached_property/.test(decoratorText);
|
|
319
|
+
// Module-level `test_*` functions that take several parameters, or that
|
|
320
|
+
// are wrapped by a helper decorator, are usually functions *for* tests.
|
|
321
|
+
// camelCase `testR(r)` is a helper convention too; pytest's own tests
|
|
322
|
+
// use `test_` or test classes.
|
|
323
|
+
const camelCase = !name.startsWith('test_');
|
|
324
|
+
const likelyHelper = !inClass && (parameterCount >= 2 || helperDecorator || (camelCase && parameterCount >= 1));
|
|
325
|
+
// unittest-style methods routinely delegate assertions to helpers.
|
|
326
|
+
const confidence = inClass || delegatesToSelf || likelyHelper ? 'medium' : 'high';
|
|
327
|
+
drafts.push({
|
|
328
|
+
message: `test \`${name}\` makes no assertions`,
|
|
329
|
+
start: startOf(fn),
|
|
330
|
+
end: endOf(body),
|
|
331
|
+
snippet: snippetOf(ctx, fn),
|
|
332
|
+
confidence,
|
|
333
|
+
evidence: [
|
|
334
|
+
`test: ${name}`,
|
|
335
|
+
`statements: ${statements.length}`,
|
|
336
|
+
'no assert / raises / mock assertion found',
|
|
337
|
+
...(delegatesToSelf ? ['the body calls a self.* helper, which may contain the assertions'] : []),
|
|
338
|
+
...(inClass && !delegatesToSelf ? ['defined inside a test class, where helpers often hold the assertions'] : []),
|
|
339
|
+
...(likelyHelper ? ['takes several parameters or uses a helper decorator, so it may be a test helper'] : []),
|
|
340
|
+
],
|
|
341
|
+
help: 'Every test should be able to fail. Add an assertion that depends on the behaviour under test.',
|
|
342
|
+
});
|
|
343
|
+
}
|
|
344
|
+
}
|
|
345
|
+
return drafts;
|
|
346
|
+
},
|
|
347
|
+
};
|
|
348
|
+
const tautologicalAssert = {
|
|
349
|
+
meta: {
|
|
350
|
+
id: 'py/tautological-assert',
|
|
351
|
+
title: 'Assertion cannot fail',
|
|
352
|
+
summary: 'Finds `assert True`, `assert 1`, and `x == x` comparisons: assertions that hold regardless of the code.',
|
|
353
|
+
severity: 'warning',
|
|
354
|
+
confidence: 'high',
|
|
355
|
+
languages: ['python'],
|
|
356
|
+
tags: ['tests', 'theater'],
|
|
357
|
+
},
|
|
358
|
+
run(ctx) {
|
|
359
|
+
if (ctx.language !== 'python')
|
|
360
|
+
return [];
|
|
361
|
+
const drafts = [];
|
|
362
|
+
for (const node of descendantsOfType(ctx.root, ['assert_statement'])) {
|
|
363
|
+
const expression = node.namedChildren[0];
|
|
364
|
+
if (!expression)
|
|
365
|
+
continue;
|
|
366
|
+
const text = collapseWhitespace(expression.text);
|
|
367
|
+
const literalNoop = text === 'True' || text === '1';
|
|
368
|
+
const negativeComparison = /(?:!=| is not | not in )/.test(` ${text} `);
|
|
369
|
+
const selfComparison = !negativeComparison &&
|
|
370
|
+
expression.type === 'comparison_operator' &&
|
|
371
|
+
expression.namedChildren.length === 2 &&
|
|
372
|
+
expression.namedChildren[0]?.text === expression.namedChildren[1]?.text;
|
|
373
|
+
if (!literalNoop && !selfComparison)
|
|
374
|
+
continue;
|
|
375
|
+
drafts.push({
|
|
376
|
+
message: `assertion can never fail: \`${truncate(text, 60)}\``,
|
|
377
|
+
start: startOf(node),
|
|
378
|
+
end: endOf(node),
|
|
379
|
+
snippet: snippetOf(ctx, node),
|
|
380
|
+
evidence: [`expression: ${truncate(text, 100)}`],
|
|
381
|
+
help: 'Assert on the actual behaviour (a return value, a raised error, a call) instead of a constant.',
|
|
382
|
+
});
|
|
383
|
+
}
|
|
384
|
+
return drafts;
|
|
385
|
+
},
|
|
386
|
+
};
|
|
387
|
+
const stubBody = {
|
|
388
|
+
meta: {
|
|
389
|
+
id: 'py/stub-body',
|
|
390
|
+
title: 'Function body is a placeholder',
|
|
391
|
+
summary: 'Finds functions whose entire body is `pass`, `...`, `return None` or `raise NotImplementedError`, outside of abstract/Protocol declarations.',
|
|
392
|
+
severity: 'warning',
|
|
393
|
+
confidence: 'high',
|
|
394
|
+
languages: ['python'],
|
|
395
|
+
tags: ['stubs', 'completeness'],
|
|
396
|
+
},
|
|
397
|
+
run(ctx) {
|
|
398
|
+
if (ctx.language !== 'python')
|
|
399
|
+
return [];
|
|
400
|
+
if (isTestPath(ctx.file))
|
|
401
|
+
return [];
|
|
402
|
+
// Type stubs and deliberate no-op shims are made of `pass`/`...`.
|
|
403
|
+
if (isStubFile(ctx.file) || isNoopModulePath(ctx.file))
|
|
404
|
+
return [];
|
|
405
|
+
const drafts = [];
|
|
406
|
+
for (const fn of descendantsOfType(ctx.root, ['function_definition'])) {
|
|
407
|
+
const name = fn.childForFieldName('name')?.text;
|
|
408
|
+
if (!name)
|
|
409
|
+
continue;
|
|
410
|
+
if (testFunctionName(fn))
|
|
411
|
+
continue;
|
|
412
|
+
if (NEVER_STUBS.has(name))
|
|
413
|
+
continue;
|
|
414
|
+
if (name.startsWith('__') && name.endsWith('__'))
|
|
415
|
+
continue;
|
|
416
|
+
const body = fn.childForFieldName('body');
|
|
417
|
+
if (!body)
|
|
418
|
+
continue;
|
|
419
|
+
if (isAbstractMember(fn))
|
|
420
|
+
continue;
|
|
421
|
+
const form = placeholderForm(body);
|
|
422
|
+
if (!form)
|
|
423
|
+
continue;
|
|
424
|
+
const moduleLevel = fn.parent?.type === 'module';
|
|
425
|
+
const documented = hasDocstring(fn);
|
|
426
|
+
const publicName = !name.startsWith('_');
|
|
427
|
+
let confidence = 'medium';
|
|
428
|
+
if (moduleLevel && publicName && !documented && (form === 'pass' || form === '...')) {
|
|
429
|
+
confidence = 'high';
|
|
430
|
+
}
|
|
431
|
+
else if (form === 'return' || form === 'return None') {
|
|
432
|
+
confidence = 'low';
|
|
433
|
+
}
|
|
434
|
+
drafts.push({
|
|
435
|
+
message: `function \`${name}\` is a stub (body is \`${form}\`)`,
|
|
436
|
+
start: startOf(fn),
|
|
437
|
+
end: endOf(body),
|
|
438
|
+
snippet: snippetOf(ctx, fn),
|
|
439
|
+
confidence,
|
|
440
|
+
evidence: [
|
|
441
|
+
`function: ${name}`,
|
|
442
|
+
`body: ${form}`,
|
|
443
|
+
...(documented ? ['the function has a docstring, which suggests a documented interface'] : []),
|
|
444
|
+
...(moduleLevel ? [] : ['defined inside a class or another function']),
|
|
445
|
+
],
|
|
446
|
+
help: form === 'raise NotImplementedError'
|
|
447
|
+
? 'If this is intentional, make sure callers handle the error; otherwise implement it.'
|
|
448
|
+
: 'Implement it, or raise NotImplementedError with a message so callers fail loudly instead of silently returning None.',
|
|
449
|
+
});
|
|
450
|
+
}
|
|
451
|
+
return drafts;
|
|
452
|
+
},
|
|
453
|
+
};
|
|
454
|
+
const swallowedException = {
|
|
455
|
+
meta: {
|
|
456
|
+
id: 'py/swallowed-exception',
|
|
457
|
+
title: 'Exception is swallowed silently',
|
|
458
|
+
summary: 'Finds `except` handlers whose whole body is `pass` or `...`, so failures disappear without a trace.',
|
|
459
|
+
severity: 'warning',
|
|
460
|
+
confidence: 'high',
|
|
461
|
+
languages: ['python'],
|
|
462
|
+
tags: ['errors', 'reliability'],
|
|
463
|
+
},
|
|
464
|
+
run(ctx) {
|
|
465
|
+
if (ctx.language !== 'python')
|
|
466
|
+
return [];
|
|
467
|
+
if (isTestPath(ctx.file))
|
|
468
|
+
return [];
|
|
469
|
+
const drafts = [];
|
|
470
|
+
for (const tryNode of descendantsOfType(ctx.root, ['try_statement'])) {
|
|
471
|
+
// `try: ... except X: pass else: fail()` is an assertion idiom, not a bug.
|
|
472
|
+
if (tryNode.namedChildren.some((child) => child.type === 'else_clause'))
|
|
473
|
+
continue;
|
|
474
|
+
for (const clause of tryNode.namedChildren) {
|
|
475
|
+
if (clause.type !== 'except_clause' && clause.type !== 'except_group_clause')
|
|
476
|
+
continue;
|
|
477
|
+
const body = clause.namedChildren.filter((child) => child.type === 'block').pop();
|
|
478
|
+
if (!body)
|
|
479
|
+
continue;
|
|
480
|
+
const statements = statementsOf(body);
|
|
481
|
+
const silent = statements.length === 0 ||
|
|
482
|
+
(statements.length === 1 &&
|
|
483
|
+
(statements[0]?.type === 'pass_statement' ||
|
|
484
|
+
(statements[0]?.type === 'expression_statement' &&
|
|
485
|
+
collapseWhitespace(statements[0].text) === '...')));
|
|
486
|
+
if (!silent)
|
|
487
|
+
continue;
|
|
488
|
+
const typeText = clause.namedChildren
|
|
489
|
+
.filter((child) => child.type !== 'block')
|
|
490
|
+
.map((child) => collapseWhitespace(child.text))
|
|
491
|
+
.join(' ')
|
|
492
|
+
.trim();
|
|
493
|
+
// Optional-dependency idiom: swallowing a missing import is the point.
|
|
494
|
+
if (/ImportError|ModuleNotFoundError/.test(typeText))
|
|
495
|
+
continue;
|
|
496
|
+
// Explain-the-suppression comments usually sit between the `try` body
|
|
497
|
+
// and the `except`, so the window starts at the whole statement.
|
|
498
|
+
const commented = hasCommentBetween(ctx, tryNode.startPosition.row + 1, body.endPosition.row + 1);
|
|
499
|
+
const bare = typeText.length === 0;
|
|
500
|
+
const broad = bare || /^(\(?\s*)?(Exception|BaseException)(\s*\))?$/.test(typeText);
|
|
501
|
+
const cleanup = insideCleanupFunction(clause);
|
|
502
|
+
const confidence = broad && !commented && !cleanup ? 'high' : 'medium';
|
|
503
|
+
drafts.push({
|
|
504
|
+
message: commented
|
|
505
|
+
? '`except` swallows the error (a comment explains why)'
|
|
506
|
+
: broad
|
|
507
|
+
? '`except` swallows the error silently'
|
|
508
|
+
: '`except` swallows a specific error type silently',
|
|
509
|
+
start: startOf(clause),
|
|
510
|
+
end: endOf(body),
|
|
511
|
+
snippet: snippetOf(ctx, clause),
|
|
512
|
+
confidence,
|
|
513
|
+
evidence: [
|
|
514
|
+
`handler: ${truncate(collapseWhitespace(clause.text.split(/\r?\n/)[0] ?? ''), 100)}`,
|
|
515
|
+
...(bare ? ['bare except: catches every exception, including KeyboardInterrupt'] : []),
|
|
516
|
+
...(cleanup ? ['inside a cleanup/finaliser function, where this is often intentional'] : []),
|
|
517
|
+
...(commented ? ['a comment explains the suppression'] : []),
|
|
518
|
+
],
|
|
519
|
+
help: 'Log it, re-raise it, or narrow the exception type and add a comment explaining why it is safe to ignore.',
|
|
520
|
+
});
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
return drafts;
|
|
524
|
+
},
|
|
525
|
+
};
|
|
526
|
+
const deadBranch = {
|
|
527
|
+
meta: {
|
|
528
|
+
id: 'py/dead-branch',
|
|
529
|
+
title: 'Constant condition',
|
|
530
|
+
summary: 'Finds `if False:`, `if 0:`, `while False:` and `if True:` branches that can never behave as written.',
|
|
531
|
+
severity: 'warning',
|
|
532
|
+
confidence: 'medium',
|
|
533
|
+
languages: ['python'],
|
|
534
|
+
tags: ['control-flow', 'dead-code'],
|
|
535
|
+
},
|
|
536
|
+
run(ctx) {
|
|
537
|
+
if (ctx.language !== 'python')
|
|
538
|
+
return [];
|
|
539
|
+
if (isTestPath(ctx.file))
|
|
540
|
+
return [];
|
|
541
|
+
const drafts = [];
|
|
542
|
+
for (const node of descendantsOfType(ctx.root, ['if_statement', 'while_statement'])) {
|
|
543
|
+
if (insideAbstractMethod(node))
|
|
544
|
+
continue;
|
|
545
|
+
const condition = node.childForFieldName('condition');
|
|
546
|
+
if (!condition)
|
|
547
|
+
continue;
|
|
548
|
+
const text = collapseWhitespace(condition.text);
|
|
549
|
+
const isDeadFalse = text === 'False' || text === '0' || text === 'None';
|
|
550
|
+
// `while True:` is a legitimate event loop; `if True:` is not.
|
|
551
|
+
const isDeadTrue = text === 'True' || text === '1';
|
|
552
|
+
if (!isDeadFalse && !isDeadTrue)
|
|
553
|
+
continue;
|
|
554
|
+
if (isDeadTrue && node.type === 'while_statement')
|
|
555
|
+
continue;
|
|
556
|
+
// `if False:` around imports is the type-checking idiom:
|
|
557
|
+
// if False: # or if TYPE_CHECKING:
|
|
558
|
+
// from foo import Bar
|
|
559
|
+
const block = node.childForFieldName('consequence');
|
|
560
|
+
const statements = block ? statementsOf(block) : [];
|
|
561
|
+
const onlyImports = statements.length > 0 &&
|
|
562
|
+
statements.every((statement) => statement.type === 'import_statement' || statement.type === 'import_from_statement');
|
|
563
|
+
if (onlyImports)
|
|
564
|
+
continue;
|
|
565
|
+
const commented = hasCommentBetween(ctx, Math.max(1, node.startPosition.row), node.endPosition.row + 1);
|
|
566
|
+
drafts.push({
|
|
567
|
+
message: isDeadFalse
|
|
568
|
+
? `\`${node.type === 'while_statement' ? 'while' : 'if'} ${text}:\` is dead code`
|
|
569
|
+
: `\`if ${text}:\` makes the else-branch unreachable`,
|
|
570
|
+
start: startOf(node),
|
|
571
|
+
end: endOf(condition),
|
|
572
|
+
snippet: snippetOf(ctx, node),
|
|
573
|
+
confidence: isDeadFalse && !commented ? 'high' : 'medium',
|
|
574
|
+
evidence: [`condition: ${text}`, ...(commented ? ['a nearby comment suggests this is a deliberate switch'] : [])],
|
|
575
|
+
help: 'Replace the constant with the flag or configuration value it is standing in for.',
|
|
576
|
+
});
|
|
577
|
+
}
|
|
578
|
+
return drafts;
|
|
579
|
+
},
|
|
580
|
+
};
|
|
581
|
+
const unreachable = {
|
|
582
|
+
meta: {
|
|
583
|
+
id: 'py/unreachable',
|
|
584
|
+
title: 'Statement after an unconditional exit',
|
|
585
|
+
summary: 'Finds statements placed after `return`, `raise`, `break` or `continue` in the same block.',
|
|
586
|
+
severity: 'error',
|
|
587
|
+
confidence: 'high',
|
|
588
|
+
languages: ['python'],
|
|
589
|
+
tags: ['control-flow', 'dead-code'],
|
|
590
|
+
},
|
|
591
|
+
run(ctx) {
|
|
592
|
+
if (ctx.language !== 'python')
|
|
593
|
+
return [];
|
|
594
|
+
if (isTestPath(ctx.file))
|
|
595
|
+
return [];
|
|
596
|
+
const drafts = [];
|
|
597
|
+
const seen = new Set();
|
|
598
|
+
for (const block of descendantsOfType(ctx.root, ['block'])) {
|
|
599
|
+
const statements = statementsOf(block);
|
|
600
|
+
const index = statements.findIndex((statement) => TERMINATORS.has(statement.type));
|
|
601
|
+
if (index === -1)
|
|
602
|
+
continue;
|
|
603
|
+
const firstUnreachable = statements[index + 1];
|
|
604
|
+
if (!firstUnreachable || seen.has(firstUnreachable))
|
|
605
|
+
continue;
|
|
606
|
+
seen.add(firstUnreachable);
|
|
607
|
+
const terminator = statements[index];
|
|
608
|
+
if (!terminator)
|
|
609
|
+
continue;
|
|
610
|
+
const count = statements.length - index - 1;
|
|
611
|
+
const keyword = terminator.type.replace('_statement', '');
|
|
612
|
+
drafts.push({
|
|
613
|
+
message: `code after \`${keyword}\` is unreachable`,
|
|
614
|
+
start: startOf(firstUnreachable),
|
|
615
|
+
end: endOf(firstUnreachable),
|
|
616
|
+
snippet: snippetOf(ctx, firstUnreachable),
|
|
617
|
+
evidence: [`${count} statement(s) follow the \`${keyword}\` at line ${terminator.startPosition.row + 1}`],
|
|
618
|
+
help: 'Delete the unreachable code, or move it before the exit if it was meant to run.',
|
|
619
|
+
});
|
|
620
|
+
}
|
|
621
|
+
return drafts;
|
|
622
|
+
},
|
|
623
|
+
};
|
|
624
|
+
export const pythonRules = [
|
|
625
|
+
phantomImport,
|
|
626
|
+
noopTest,
|
|
627
|
+
tautologicalAssert,
|
|
628
|
+
stubBody,
|
|
629
|
+
swallowedException,
|
|
630
|
+
deadBranch,
|
|
631
|
+
unreachable,
|
|
632
|
+
];
|