patchpilot-mcp 0.4.1__py3-none-any.whl

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.
@@ -0,0 +1,177 @@
1
+ """Strict, bounded JSON inspection with source coordinates; no external I/O."""
2
+
3
+ from bisect import bisect_right
4
+ import json
5
+ import re
6
+ from .analysis import bounded, finding, InputError, MAX_FINDINGS
7
+ from .common import no_input
8
+
9
+ MAX_DEPTH = 100
10
+ NUMBER = re.compile(r"-?(?:0|[1-9][0-9]*)(?:\.[0-9]+)?(?:[eE][+-]?[0-9]+)?")
11
+ STRING = json.JSONDecoder()
12
+ WHITESPACE = " \t\r\n"
13
+
14
+
15
+ class JsonSyntax(ValueError):
16
+ def __init__(self, message: str, offset: int):
17
+ super().__init__(message)
18
+ self.offset = offset
19
+
20
+
21
+ class Inspector:
22
+ def __init__(self, source: str, path: str, start_line: int):
23
+ self.s, self.i, self.path, self.start_line = source, 0, path, start_line
24
+ self.starts = [0] + [m.end() for m in re.finditer("\n", source)]
25
+ self.findings: list[dict] = []
26
+
27
+ def location(self, offset):
28
+ index = bisect_right(self.starts, offset) - 1
29
+ return self.start_line + index, offset - self.starts[index] + 1
30
+
31
+ def ws(self):
32
+ while self.i < len(self.s) and self.s[self.i] in WHITESPACE:
33
+ self.i += 1
34
+
35
+ def peek(self):
36
+ return self.s[self.i : self.i + 1]
37
+
38
+ def require(self, character):
39
+ self.ws()
40
+ if self.peek() != character:
41
+ raise JsonSyntax(f"Expected {character!r}", self.i)
42
+ self.i += 1
43
+
44
+ def string(self):
45
+ try:
46
+ value, end = STRING.raw_decode(self.s, self.i)
47
+ except json.JSONDecodeError as exc:
48
+ raise JsonSyntax(exc.msg, exc.pos) from None
49
+ if not isinstance(value, str):
50
+ raise JsonSyntax("Expected a JSON string", self.i)
51
+ self.i = end
52
+ return value
53
+
54
+ def value(self, depth=0):
55
+ if depth > MAX_DEPTH:
56
+ raise InputError(f"JSON nesting exceeds {MAX_DEPTH}")
57
+ self.ws()
58
+ c = self.peek()
59
+ if c == "{":
60
+ self.object_value(depth)
61
+ elif c == "[":
62
+ self.array(depth)
63
+ elif c == '"':
64
+ self.string()
65
+ else:
66
+ for literal in ("true", "false", "null"):
67
+ if self.s.startswith(literal, self.i):
68
+ self.i += len(literal)
69
+ return
70
+ # Match grammar only: no conversion of numeric values, no overflow.
71
+ m = NUMBER.match(self.s, self.i)
72
+ if m is None:
73
+ raise JsonSyntax("Expected a JSON value", self.i)
74
+ self.i = m.end()
75
+
76
+ def object_value(self, depth):
77
+ self.i += 1
78
+ self.ws()
79
+ if self.peek() == "}":
80
+ self.i += 1
81
+ return
82
+ seen: dict[str, int] = {}
83
+ while True:
84
+ self.ws()
85
+ offset = self.i
86
+ if self.peek() != '"':
87
+ raise JsonSyntax("Expected a quoted object key", offset)
88
+ key = self.string()
89
+ if key in seen:
90
+ line, col = self.location(offset)
91
+ first, first_col = self.location(seen[key])
92
+ f = finding(
93
+ "JSON_DUPLICATE_KEY",
94
+ "warning",
95
+ "fact",
96
+ self.path,
97
+ line,
98
+ f"Object key repeats its earlier occurrence at {first}:{first_col}.",
99
+ "Resolve repeated keys; JSON readers can differ in which value they retain.",
100
+ )
101
+ f.update(column=col)
102
+ self.findings.append(f)
103
+ else:
104
+ seen[key] = offset
105
+ self.require(":")
106
+ self.value(depth + 1)
107
+ self.ws()
108
+ if self.peek() == "}":
109
+ self.i += 1
110
+ return
111
+ self.require(",")
112
+
113
+ def array(self, depth):
114
+ self.i += 1
115
+ self.ws()
116
+ if self.peek() == "]":
117
+ self.i += 1
118
+ return
119
+ while True:
120
+ self.value(depth + 1)
121
+ self.ws()
122
+ if self.peek() == "]":
123
+ self.i += 1
124
+ return
125
+ self.require(",")
126
+
127
+
128
+ def review_json(
129
+ source: str,
130
+ path: str = "document.json",
131
+ start_line: int = 1,
132
+ *,
133
+ complete: bool = False,
134
+ ) -> dict:
135
+ lines = bounded(source, name="source")
136
+ if not 1 <= start_line <= 10**8 or not path or len(path) > 1024:
137
+ raise InputError("Invalid path label or line offset")
138
+ if source == "" and not complete:
139
+ return no_input(path)
140
+ visitor = Inspector(source, path, start_line)
141
+ syntax_ok = True
142
+ try:
143
+ visitor.value()
144
+ visitor.ws()
145
+ if visitor.i != len(source):
146
+ raise JsonSyntax("Unexpected trailing content", visitor.i)
147
+ except JsonSyntax as exc:
148
+ syntax_ok = False
149
+ line, col = visitor.location(exc.offset)
150
+ f = finding(
151
+ "JSON_SYNTAX",
152
+ "error",
153
+ "fact",
154
+ path,
155
+ line,
156
+ str(exc),
157
+ "Correct the JSON syntax at this location.",
158
+ )
159
+ f["column"] = col
160
+ visitor.findings.insert(0, f)
161
+ return dict(
162
+ path=path,
163
+ syntax_ok=syntax_ok,
164
+ lines=len(lines),
165
+ findings=visitor.findings[:MAX_FINDINGS],
166
+ omitted_findings=max(0, len(visitor.findings) - MAX_FINDINGS),
167
+ coverage=(
168
+ "checked_incomplete_findings"
169
+ if len(visitor.findings) > MAX_FINDINGS
170
+ else "checked_complete"
171
+ ),
172
+ limitations=[
173
+ "JSON grammar and duplicate object-key tokens only; no schema or business-rule validation.",
174
+ "Duplicate-key observations are limited to the parsed input and scoped to each object.",
175
+ f"JSON nesting capped at {MAX_DEPTH}; findings capped at {MAX_FINDINGS}.",
176
+ ],
177
+ )
@@ -0,0 +1,316 @@
1
+ """Bounded Python syntax and ordinary maintainability review."""
2
+
3
+ import ast
4
+ import re
5
+ from .common import (
6
+ MAX_LINES,
7
+ MAX_FINDINGS,
8
+ MAX_AST_NODES,
9
+ InputError,
10
+ bounded,
11
+ finding,
12
+ no_input,
13
+ )
14
+
15
+ DEFINITIONS = (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)
16
+
17
+
18
+ def _duplicate_definitions(nodes, add, start_line):
19
+ for node in nodes:
20
+ for _, value in ast.iter_fields(node):
21
+ if not isinstance(value, list):
22
+ continue
23
+ seen = {}
24
+ for stmt in value:
25
+ if not isinstance(stmt, DEFINITIONS):
26
+ continue
27
+ # Decorated overloads and property accessors are often intentional.
28
+ if stmt.decorator_list:
29
+ continue
30
+ if stmt.name in seen:
31
+ add(
32
+ "DUPLICATE_DEFINITION",
33
+ "warning",
34
+ "heuristic",
35
+ stmt.lineno,
36
+ f"'{stmt.name}' repeats a direct definition at line {seen[stmt.name]+start_line-1}.",
37
+ "Confirm rebinding is intentional; consolidate or rename if accidental.",
38
+ )
39
+ seen[stmt.name] = stmt.lineno
40
+
41
+
42
+ def _unreachable(node, add):
43
+ for _, value in ast.iter_fields(node):
44
+ if not isinstance(value, list):
45
+ continue
46
+ terminated = False
47
+ for stmt in value:
48
+ if not isinstance(stmt, ast.stmt):
49
+ continue
50
+ if terminated:
51
+ add(
52
+ "UNREACHABLE_STATEMENT",
53
+ "warning",
54
+ "heuristic",
55
+ stmt.lineno,
56
+ "Statement follows an unconditional terminator in the same block.",
57
+ "Check whether the following statement is intentional or should move before the terminator.",
58
+ )
59
+ break
60
+ if isinstance(stmt, (ast.Return, ast.Raise, ast.Break, ast.Continue)):
61
+ terminated = True
62
+
63
+
64
+ def _dictionary_keys(node, add, char_column):
65
+ if isinstance(node, ast.Dict):
66
+ seen_keys = set()
67
+ for key in node.keys:
68
+ if not isinstance(key, ast.Constant) or type(key.value) not in (
69
+ str,
70
+ int,
71
+ float,
72
+ bool,
73
+ bytes,
74
+ type(None),
75
+ ):
76
+ continue
77
+ if key.value in seen_keys:
78
+ add(
79
+ "DUPLICATE_LITERAL_KEY",
80
+ "warning",
81
+ "fact",
82
+ key.lineno,
83
+ "Dictionary literal repeats a constant key; a later value overwrites an earlier one.",
84
+ "Check the duplicated key and preserve the intended value.",
85
+ char_column(key),
86
+ )
87
+ seen_keys.add(key.value)
88
+
89
+
90
+ def _block_and_dictionary_rules(nodes, add, char_column):
91
+ for node in nodes:
92
+ _unreachable(node, add)
93
+ _dictionary_keys(node, add, char_column)
94
+
95
+
96
+ def _branch_score(fn):
97
+ score = 1
98
+ stack = list(fn.body)
99
+ while stack:
100
+ node = stack.pop()
101
+ if isinstance(node, (*DEFINITIONS, ast.Lambda)):
102
+ continue
103
+ if isinstance(
104
+ node,
105
+ (
106
+ ast.If,
107
+ ast.IfExp,
108
+ ast.For,
109
+ ast.AsyncFor,
110
+ ast.While,
111
+ ast.ExceptHandler,
112
+ ),
113
+ ):
114
+ score += 1
115
+ elif isinstance(node, ast.BoolOp):
116
+ score += len(node.values) - 1
117
+ elif isinstance(node, ast.Match):
118
+ score += len(node.cases)
119
+ elif isinstance(node, ast.comprehension):
120
+ score += 1 + len(node.ifs)
121
+ stack.extend(ast.iter_child_nodes(node))
122
+ return score
123
+
124
+
125
+ def _functions(nodes, start_line, complexity_threshold, add):
126
+ functions = []
127
+ for fn in nodes:
128
+ if not isinstance(fn, (ast.FunctionDef, ast.AsyncFunctionDef)):
129
+ continue
130
+ score = _branch_score(fn)
131
+ functions.append(
132
+ dict(
133
+ name=fn.name,
134
+ line=fn.lineno + start_line - 1,
135
+ end_line=fn.end_lineno + start_line - 1,
136
+ branch_score=score,
137
+ )
138
+ )
139
+ if score >= complexity_threshold:
140
+ add(
141
+ "BRANCH_COMPLEXITY",
142
+ "warning",
143
+ "heuristic",
144
+ fn.lineno,
145
+ f"'{fn.name}' has branch score {score} (threshold {complexity_threshold}).",
146
+ "Consider simpler control flow or extract a cohesive helper; preserve behavior with tests.",
147
+ )
148
+ return functions
149
+
150
+
151
+ def _import_statement(stmt):
152
+ return isinstance(stmt, (ast.Import, ast.ImportFrom)) and not (
153
+ isinstance(stmt, ast.ImportFrom) and stmt.module == "__future__"
154
+ )
155
+
156
+
157
+ def _inspect_imports(stmt, reads, strings, add):
158
+ for alias in stmt.names:
159
+ name = alias.asname or alias.name.split(".")[0]
160
+ if name == "*" or alias.asname == alias.name:
161
+ continue
162
+ if name not in reads and not re.search(
163
+ r"\b" + re.escape(name) + r"\b", strings
164
+ ):
165
+ add(
166
+ "POSSIBLY_UNUSED_IMPORT",
167
+ "info",
168
+ "heuristic",
169
+ stmt.lineno,
170
+ f"Imported name '{name}' has no explicit read in the supplied module.",
171
+ "Check re-exports, runtime registration and side effects before removing.",
172
+ )
173
+
174
+
175
+ def _unused_imports(tree, nodes, add):
176
+ reads = {
177
+ n.id for n in nodes if isinstance(n, ast.Name) and isinstance(n.ctx, ast.Load)
178
+ }
179
+ # String-literal exports and forward annotations are conservative exclusions.
180
+ strings = " ".join(
181
+ n.value
182
+ for n in nodes
183
+ if isinstance(n, ast.Constant) and isinstance(n.value, str)
184
+ )
185
+ for stmt in tree.body:
186
+ if _import_statement(stmt):
187
+ _inspect_imports(stmt, reads, strings, add)
188
+
189
+
190
+ def _validate_source(source, path, start_line, complexity_threshold):
191
+ lines = bounded(source, name="source")
192
+ if source.replace("\r\n", "\n").replace("\r", "\n").count("\n") > MAX_LINES:
193
+ raise InputError(f"source exceeds {MAX_LINES} lines")
194
+ if not 1 <= start_line <= 10**8 or not 2 <= complexity_threshold <= 50:
195
+ raise InputError("Invalid line offset or complexity threshold")
196
+ if not path or len(path) > 1024:
197
+ raise InputError("Path is only a label and must be 1–1024 characters")
198
+ return lines
199
+
200
+
201
+ def _parse_source(source):
202
+ try:
203
+ tree = ast.parse(source)
204
+ nodes = list(ast.walk(tree))
205
+ if len(nodes) > MAX_AST_NODES:
206
+ raise InputError(f"AST exceeds {MAX_AST_NODES} nodes")
207
+ # Compiler validates syntax contexts (e.g. return outside a function);
208
+ # the code object is discarded and is never executed.
209
+ compile(tree, "<supplied source>", "exec", dont_inherit=True)
210
+ except RecursionError as e:
211
+ raise InputError("Python syntax nesting exceeds supported bounds") from e
212
+ return tree, nodes
213
+
214
+
215
+ def review_python(
216
+ source: str,
217
+ path: str = "snippet.py",
218
+ start_line: int = 1,
219
+ complexity_threshold: int = 10,
220
+ complete_module: bool = False,
221
+ ) -> dict:
222
+ lines = _validate_source(source, path, start_line, complexity_threshold)
223
+ if source == "" and not complete_module:
224
+ return no_input(path, functions=[])
225
+ issues: list[dict] = []
226
+
227
+ def add(code, severity, evidence, line, message, recommendation, column=None):
228
+ f = finding(
229
+ code,
230
+ severity,
231
+ evidence,
232
+ path,
233
+ line + start_line - 1 if line is not None else None,
234
+ message,
235
+ recommendation,
236
+ )
237
+ if column is not None:
238
+ f["column"] = column
239
+ issues.append(f)
240
+
241
+ try:
242
+ tree, nodes = _parse_source(source)
243
+ except InputError:
244
+ raise
245
+ except (SyntaxError, ValueError) as e:
246
+ add(
247
+ "PYTHON_SYNTAX",
248
+ "error",
249
+ "fact",
250
+ getattr(e, "lineno", None),
251
+ getattr(e, "msg", "Invalid source input"),
252
+ "Check complete surrounding context and correct syntax.",
253
+ )
254
+ return dict(
255
+ path=path,
256
+ syntax_ok=False,
257
+ lines=len(lines),
258
+ functions=[],
259
+ findings=issues,
260
+ omitted_findings=0,
261
+ limitations=[
262
+ "Syntax is evaluated only for supplied text in isolation; partial fragments may be invalid."
263
+ ],
264
+ )
265
+ python_lines = source.replace("\r\n", "\n").replace("\r", "\n").split("\n")
266
+
267
+ def char_column(node):
268
+ return (
269
+ len(
270
+ python_lines[node.lineno - 1]
271
+ .encode("utf-8")[: node.col_offset]
272
+ .decode("utf-8")
273
+ )
274
+ + 1
275
+ )
276
+
277
+ _duplicate_definitions(nodes, add, start_line)
278
+ _block_and_dictionary_rules(nodes, add, char_column)
279
+ from .python_rules import python_rules
280
+
281
+ def emit_rule(code, severity, evidence, node, message, recommendation):
282
+ add(
283
+ code,
284
+ severity,
285
+ evidence,
286
+ node.lineno,
287
+ message,
288
+ recommendation,
289
+ char_column(node),
290
+ )
291
+
292
+ python_rules(source, tree, nodes, emit_rule)
293
+ functions = _functions(nodes, start_line, complexity_threshold, add)
294
+ if complete_module:
295
+ _unused_imports(tree, nodes, add)
296
+ return dict(
297
+ path=path,
298
+ syntax_ok=True,
299
+ lines=len(python_lines) - (python_lines[-1] == ""),
300
+ functions=functions,
301
+ findings=issues[:MAX_FINDINGS],
302
+ omitted_findings=max(0, len(issues) - MAX_FINDINGS),
303
+ coverage=(
304
+ "checked_incomplete_findings"
305
+ if len(issues) > MAX_FINDINGS
306
+ else "checked_complete" if complete_module else "checked_fragment"
307
+ ),
308
+ limitations=[
309
+ "AST and compiler syntax checks only supplied source; no code execution or import resolution.",
310
+ "Branch score is a simple branch-point heuristic, not a formal complexity metric.",
311
+ "Duplicate definitions may be intentional; decorated definitions skipped.",
312
+ "Unused-import hints require complete_module and are not proof of dead code.",
313
+ "Unused-local hints use Python symbol tables for supplied functions and skip reflective scopes; they are heuristics.",
314
+ f"Findings are capped at {MAX_FINDINGS}.",
315
+ ],
316
+ )
@@ -0,0 +1,216 @@
1
+ """Ordinary Python maintainability rules with conservative lexical-scope checks."""
2
+
3
+ import ast
4
+ import builtins
5
+ import symtable
6
+
7
+ FUNCTIONS = (ast.FunctionDef, ast.AsyncFunctionDef)
8
+ SCOPES = (
9
+ *FUNCTIONS,
10
+ ast.ClassDef,
11
+ ast.Lambda,
12
+ ast.ListComp,
13
+ ast.SetComp,
14
+ ast.DictComp,
15
+ ast.GeneratorExp,
16
+ )
17
+ BUILTINS = {name for name in dir(builtins) if not name.startswith("_")}
18
+ DYNAMIC_NAMES = {"locals", "vars", "eval", "exec"}
19
+
20
+
21
+ def _function_assignments(fn):
22
+ """Only names assigned directly in this function; exclude nested lexical scopes."""
23
+ names = {}
24
+ dynamic = False
25
+ stack = list(reversed(fn.body))
26
+ while stack:
27
+ node = stack.pop()
28
+ if isinstance(node, SCOPES):
29
+ # Defaults, decorators, and class bases can evaluate in this scope. Treat
30
+ # any dynamic lookup in them conservatively via the nested-node check below.
31
+ continue
32
+ if (
33
+ isinstance(node, ast.Call)
34
+ and isinstance(node.func, ast.Name)
35
+ and node.func.id in DYNAMIC_NAMES
36
+ ):
37
+ dynamic = True
38
+ if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store):
39
+ names.setdefault(node.id, node)
40
+ stack.extend(reversed(list(ast.iter_child_nodes(node))))
41
+ return names, dynamic
42
+
43
+
44
+ def _child_references(table, name):
45
+ stack = list(table.get_children())
46
+ while stack:
47
+ nested = stack.pop()
48
+ try:
49
+ symbol = nested.lookup(name)
50
+ except KeyError:
51
+ symbol = None
52
+ if symbol is not None and (symbol.is_free() or symbol.is_nonlocal()):
53
+ return True
54
+ stack.extend(nested.get_children())
55
+ return False
56
+
57
+
58
+ def _names_with_context(node, context):
59
+ return {
60
+ n.id
61
+ for n in ast.walk(node)
62
+ if isinstance(n, ast.Name) and isinstance(n.ctx, context)
63
+ }
64
+
65
+
66
+ def _comprehension_inputs(comp):
67
+ """First iterable is evaluated outside targets; later expressions see earlier targets."""
68
+ bound, reads = set(), set()
69
+ for generator in comp.generators:
70
+ reads.update(_names_with_context(generator.iter, ast.Load) - bound)
71
+ bound.update(_names_with_context(generator.target, ast.Store))
72
+ for condition in generator.ifs:
73
+ reads.update(_names_with_context(condition, ast.Load) - bound)
74
+ body = (comp.key, comp.value) if isinstance(comp, ast.DictComp) else (comp.elt,)
75
+ for expression in body:
76
+ reads.update(_names_with_context(expression, ast.Load) - bound)
77
+ return reads
78
+
79
+
80
+ def _comprehension_reads(fn):
81
+ """Preserve outer reads hidden by PEP 709; conservatively include nested scopes."""
82
+ scopes = (ast.ListComp, ast.SetComp, ast.DictComp, ast.GeneratorExp)
83
+ result = set()
84
+ for comp in ast.walk(fn):
85
+ if isinstance(comp, scopes):
86
+ result.update(_comprehension_inputs(comp))
87
+ return result
88
+
89
+
90
+ def _default_and_exception_rules(nodes, emit):
91
+ # A literal list/dict/set default is created when its function is defined.
92
+ for node in nodes:
93
+ if isinstance(node, FUNCTIONS):
94
+ for default in [*node.args.defaults, *node.args.kw_defaults]:
95
+ if isinstance(
96
+ default,
97
+ (
98
+ ast.List,
99
+ ast.Dict,
100
+ ast.Set,
101
+ ast.ListComp,
102
+ ast.DictComp,
103
+ ast.SetComp,
104
+ ),
105
+ ):
106
+ emit(
107
+ "MUTABLE_DEFAULT",
108
+ "warning",
109
+ "heuristic",
110
+ default,
111
+ "Mutable default value may be shared between calls.",
112
+ "If sharing is not intentional, use a sentinel default and create a fresh value in the function.",
113
+ )
114
+ elif isinstance(node, ast.ExceptHandler) and node.type is None:
115
+ emit(
116
+ "BARE_EXCEPT",
117
+ "warning",
118
+ "heuristic",
119
+ node,
120
+ "Bare except catches exceptions beyond ordinary Exception subclasses.",
121
+ "Catch the intended exception types; preserve intentional cleanup behavior.",
122
+ )
123
+
124
+
125
+ def _builtin_rules(nodes, emit):
126
+ # Builtin shadowing is a maintainability hint, not evidence of broken behavior.
127
+ for node in nodes:
128
+ name = None
129
+ if isinstance(node, ast.Name) and isinstance(node.ctx, ast.Store):
130
+ name = node.id
131
+ elif isinstance(node, ast.arg):
132
+ name = node.arg
133
+ elif isinstance(node, (*FUNCTIONS, ast.ClassDef)):
134
+ name = node.name
135
+ if name in BUILTINS:
136
+ emit(
137
+ "BUILTIN_SHADOWING",
138
+ "info",
139
+ "heuristic",
140
+ node,
141
+ f"Binding '{name}' shadows a Python builtin name.",
142
+ "Consider a more specific name if the shadowing is unintended.",
143
+ )
144
+
145
+
146
+ def _reflective(fn):
147
+ return any(
148
+ isinstance(n, ast.Call)
149
+ and isinstance(n.func, ast.Name)
150
+ and n.func.id in DYNAMIC_NAMES
151
+ for n in ast.walk(fn)
152
+ )
153
+
154
+
155
+ def _unused_symbol(symbol, table, name):
156
+ return (
157
+ symbol.is_local()
158
+ and symbol.is_assigned()
159
+ and not symbol.is_parameter()
160
+ and not symbol.is_imported()
161
+ and not symbol.is_global()
162
+ and not symbol.is_nonlocal()
163
+ and not symbol.is_referenced()
164
+ and not _child_references(table, name)
165
+ )
166
+
167
+
168
+ def _unused_function(fn, table, emit):
169
+ names, dynamic = _function_assignments(fn)
170
+ # Avoid false confidence in reflective access, including nested calls.
171
+ if dynamic or _reflective(fn):
172
+ return
173
+ # A store in a comprehension is not necessarily a store in this function;
174
+ # direct assignments were collected without entering comprehensions.
175
+ comprehension_reads = _comprehension_reads(fn)
176
+ for name, node in names.items():
177
+ if name.startswith("_") or name in comprehension_reads:
178
+ continue
179
+ try:
180
+ symbol = table.lookup(name)
181
+ except KeyError:
182
+ continue
183
+ if _unused_symbol(symbol, table, name):
184
+ emit(
185
+ "POSSIBLY_UNUSED_LOCAL",
186
+ "info",
187
+ "heuristic",
188
+ node,
189
+ f"Local binding '{name}' has no lexical reference in the supplied function.",
190
+ "Check intended use or remove the assignment only if its value and side effects are unnecessary.",
191
+ )
192
+
193
+
194
+ def _unused_rules(source, nodes, emit):
195
+ try:
196
+ root = symtable.symtable(source, "<supplied source>", "exec")
197
+ except (SyntaxError, RecursionError, ValueError):
198
+ return
199
+ functions = {}
200
+ for node in nodes:
201
+ if isinstance(node, FUNCTIONS):
202
+ functions.setdefault((node.name, node.lineno), []).append(node)
203
+ stack = list(root.get_children())
204
+ while stack:
205
+ table = stack.pop()
206
+ stack.extend(table.get_children())
207
+ candidates = functions.get((table.get_name(), table.get_lineno()), [])
208
+ if len(candidates) != 1:
209
+ continue
210
+ _unused_function(candidates[0], table, emit)
211
+
212
+
213
+ def python_rules(source, tree, nodes, emit):
214
+ _default_and_exception_rules(nodes, emit)
215
+ _builtin_rules(nodes, emit)
216
+ _unused_rules(source, nodes, emit)