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.
- patchpilot/__init__.py +3 -0
- patchpilot/__main__.py +246 -0
- patchpilot/analysis.py +20 -0
- patchpilot/changed.py +464 -0
- patchpilot/common.py +75 -0
- patchpilot/compact.py +292 -0
- patchpilot/config.py +217 -0
- patchpilot/diff.py +581 -0
- patchpilot/external_sarif.py +219 -0
- patchpilot/formatting.py +175 -0
- patchpilot/js_review.py +253 -0
- patchpilot/json_review.py +177 -0
- patchpilot/python_review.py +316 -0
- patchpilot/python_rules.py +216 -0
- patchpilot/sarif.py +59 -0
- patchpilot/server.py +274 -0
- patchpilot/signatures.py +224 -0
- patchpilot/snapshot.py +572 -0
- patchpilot_mcp-0.4.1.dist-info/METADATA +381 -0
- patchpilot_mcp-0.4.1.dist-info/RECORD +24 -0
- patchpilot_mcp-0.4.1.dist-info/WHEEL +5 -0
- patchpilot_mcp-0.4.1.dist-info/entry_points.txt +3 -0
- patchpilot_mcp-0.4.1.dist-info/licenses/LICENSE +21 -0
- patchpilot_mcp-0.4.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,219 @@
|
|
|
1
|
+
"""Import metadata from an already-generated external SARIF document, without execution."""
|
|
2
|
+
|
|
3
|
+
import hashlib
|
|
4
|
+
import json
|
|
5
|
+
import re
|
|
6
|
+
from urllib.parse import unquote, urlsplit
|
|
7
|
+
from .analysis import MAX_FINDINGS, InputError, bounded, parse_diff
|
|
8
|
+
|
|
9
|
+
|
|
10
|
+
def _valid_relative_path(path):
|
|
11
|
+
# Match relative labels only; no filesystem traversal or normalization of unknown bases.
|
|
12
|
+
return (
|
|
13
|
+
bool(path)
|
|
14
|
+
and len(path) <= 1024
|
|
15
|
+
and not path.startswith(("/", "\\"))
|
|
16
|
+
and not any(ord(c) < 32 for c in path)
|
|
17
|
+
and not any(part in ("..", ".", "") for part in path.split("/"))
|
|
18
|
+
and "\\" not in path
|
|
19
|
+
)
|
|
20
|
+
|
|
21
|
+
|
|
22
|
+
def _decode_label(value):
|
|
23
|
+
try:
|
|
24
|
+
parsed = urlsplit(value)
|
|
25
|
+
if parsed.scheme or parsed.netloc or parsed.query or parsed.fragment:
|
|
26
|
+
return None
|
|
27
|
+
return unquote(parsed.path, errors="strict")
|
|
28
|
+
except (ValueError, UnicodeError):
|
|
29
|
+
return None
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _artifact_label(value):
|
|
33
|
+
if (
|
|
34
|
+
not isinstance(value, str)
|
|
35
|
+
or not 1 <= len(value) <= 2048
|
|
36
|
+
or any(ord(c) < 32 for c in value)
|
|
37
|
+
):
|
|
38
|
+
return None
|
|
39
|
+
path = _decode_label(value)
|
|
40
|
+
if path is not None and _valid_relative_path(path):
|
|
41
|
+
return path
|
|
42
|
+
return None
|
|
43
|
+
|
|
44
|
+
|
|
45
|
+
def _reject_duplicate(pairs):
|
|
46
|
+
out = {}
|
|
47
|
+
for key, value in pairs:
|
|
48
|
+
if key in out:
|
|
49
|
+
raise InputError("Duplicate SARIF JSON key")
|
|
50
|
+
out[key] = value
|
|
51
|
+
return out
|
|
52
|
+
|
|
53
|
+
|
|
54
|
+
def _reject_nonfinite(value):
|
|
55
|
+
raise InputError("Nonfinite SARIF value")
|
|
56
|
+
|
|
57
|
+
|
|
58
|
+
def _read_runs(sarif_text):
|
|
59
|
+
if not isinstance(sarif_text, str):
|
|
60
|
+
raise InputError("External SARIF must be explicit JSON text")
|
|
61
|
+
bounded(sarif_text, name="external SARIF")
|
|
62
|
+
try:
|
|
63
|
+
data = json.loads(
|
|
64
|
+
sarif_text,
|
|
65
|
+
object_pairs_hook=_reject_duplicate,
|
|
66
|
+
parse_constant=_reject_nonfinite,
|
|
67
|
+
)
|
|
68
|
+
except (ValueError, RecursionError) as exc:
|
|
69
|
+
raise InputError("Invalid SARIF JSON") from exc
|
|
70
|
+
if (
|
|
71
|
+
not isinstance(data, dict)
|
|
72
|
+
or data.get("version") != "2.1.0"
|
|
73
|
+
or not isinstance(data.get("runs"), list)
|
|
74
|
+
or len(data["runs"]) > 50
|
|
75
|
+
):
|
|
76
|
+
raise InputError("Expected bounded SARIF 2.1.0 runs array")
|
|
77
|
+
return data["runs"]
|
|
78
|
+
|
|
79
|
+
|
|
80
|
+
def _obj_field(value, field, default=None):
|
|
81
|
+
return value.get(field, default) if isinstance(value, dict) else default
|
|
82
|
+
|
|
83
|
+
|
|
84
|
+
def _tool_name(run):
|
|
85
|
+
tool = run.get("tool", {})
|
|
86
|
+
driver = _obj_field(tool, "driver", {})
|
|
87
|
+
tool_name = _obj_field(driver, "name")
|
|
88
|
+
if not isinstance(tool_name, str) or not re.fullmatch(
|
|
89
|
+
r"[A-Za-z0-9 ._:/+%-]{1,100}", tool_name
|
|
90
|
+
):
|
|
91
|
+
return "unknown_external_tool"
|
|
92
|
+
return tool_name
|
|
93
|
+
|
|
94
|
+
|
|
95
|
+
def _result_metadata(item):
|
|
96
|
+
if not isinstance(item, dict):
|
|
97
|
+
raise InputError("Invalid SARIF result")
|
|
98
|
+
rule = item.get("ruleId", "unknown")
|
|
99
|
+
if not isinstance(rule, str) or not re.fullmatch(
|
|
100
|
+
r"[A-Za-z0-9._:/+%-]{1,120}", rule
|
|
101
|
+
):
|
|
102
|
+
rule = "unknown"
|
|
103
|
+
raw_level = item.get("level", "warning")
|
|
104
|
+
levels = {"error": "error", "warning": "warning", "note": "info", "none": "unknown"}
|
|
105
|
+
level = (
|
|
106
|
+
levels.get(raw_level, "unknown") if isinstance(raw_level, str) else "unknown"
|
|
107
|
+
)
|
|
108
|
+
locations = item.get("locations", [])
|
|
109
|
+
if not isinstance(locations, list) or len(locations) > 100:
|
|
110
|
+
raise InputError("Invalid SARIF locations")
|
|
111
|
+
return rule, level, locations
|
|
112
|
+
|
|
113
|
+
|
|
114
|
+
def _location_metadata(loc):
|
|
115
|
+
physical = _obj_field(loc, "physicalLocation", {})
|
|
116
|
+
artifact = _obj_field(physical, "artifactLocation", {})
|
|
117
|
+
region = _obj_field(physical, "region", {})
|
|
118
|
+
path = (
|
|
119
|
+
_artifact_label(artifact.get("uri"))
|
|
120
|
+
if isinstance(artifact, dict) and "uriBaseId" not in artifact
|
|
121
|
+
else None
|
|
122
|
+
)
|
|
123
|
+
line = _obj_field(region, "startLine")
|
|
124
|
+
if type(line) is not int or not 1 <= line <= 10**9:
|
|
125
|
+
line = None
|
|
126
|
+
return path, line
|
|
127
|
+
|
|
128
|
+
|
|
129
|
+
def _correlation(path, line, match):
|
|
130
|
+
if path is None or line is None or match is None:
|
|
131
|
+
return "unresolved"
|
|
132
|
+
if line in match.get(path, set()):
|
|
133
|
+
return "changed_line"
|
|
134
|
+
if path in match:
|
|
135
|
+
return "outside_changed_lines"
|
|
136
|
+
return "outside_supplied_diff"
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _record(tool_name, rule, level, loc, indices, match):
|
|
140
|
+
path, line = _location_metadata(loc)
|
|
141
|
+
run_index, result_index, location_index = indices
|
|
142
|
+
identity = json.dumps(
|
|
143
|
+
[tool_name, rule, path, line, level, run_index, result_index, location_index],
|
|
144
|
+
ensure_ascii=True,
|
|
145
|
+
separators=(",", ":"),
|
|
146
|
+
)
|
|
147
|
+
return dict(
|
|
148
|
+
id="external-" + hashlib.sha256(identity.encode()).hexdigest()[:24],
|
|
149
|
+
provenance="external_unverified",
|
|
150
|
+
tool=tool_name,
|
|
151
|
+
rule_id=rule,
|
|
152
|
+
severity=level,
|
|
153
|
+
path=path,
|
|
154
|
+
line=line,
|
|
155
|
+
correlation=_correlation(path, line, match),
|
|
156
|
+
run=run_index,
|
|
157
|
+
result=result_index,
|
|
158
|
+
location=location_index,
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
|
|
162
|
+
def _result_records(tool_name, item, run_index, result_index, match):
|
|
163
|
+
rule, level, locations = _result_metadata(item)
|
|
164
|
+
# Emit one record per finding location; preserve unresolved results when none exist.
|
|
165
|
+
for location_index, loc in enumerate(locations or [None], 1):
|
|
166
|
+
yield _record(
|
|
167
|
+
tool_name,
|
|
168
|
+
rule,
|
|
169
|
+
level,
|
|
170
|
+
loc,
|
|
171
|
+
(run_index, result_index, location_index),
|
|
172
|
+
match,
|
|
173
|
+
)
|
|
174
|
+
|
|
175
|
+
|
|
176
|
+
def _normalize_runs(runs, match):
|
|
177
|
+
records = []
|
|
178
|
+
total = 0
|
|
179
|
+
for run_index, run in enumerate(runs, 1):
|
|
180
|
+
if not isinstance(run, dict) or not isinstance(run.get("results", []), list):
|
|
181
|
+
raise InputError("Invalid SARIF run/results")
|
|
182
|
+
tool_name = _tool_name(run)
|
|
183
|
+
for result_index, item in enumerate(run.get("results", []), 1):
|
|
184
|
+
total += 1
|
|
185
|
+
if total > 1000:
|
|
186
|
+
raise InputError("External report exceeds 1000 results")
|
|
187
|
+
for record in _result_records(
|
|
188
|
+
tool_name, item, run_index, result_index, match
|
|
189
|
+
):
|
|
190
|
+
records.append(record)
|
|
191
|
+
if len(records) > 2000:
|
|
192
|
+
raise InputError("External report exceeds 2000 locations")
|
|
193
|
+
return records, total
|
|
194
|
+
|
|
195
|
+
|
|
196
|
+
def import_external_sarif(sarif_text, diff=None):
|
|
197
|
+
runs = _read_runs(sarif_text)
|
|
198
|
+
match = None
|
|
199
|
+
if diff is not None:
|
|
200
|
+
match = {f.path: set(f.added_lines) for f in parse_diff(diff)[0]}
|
|
201
|
+
records, total = _normalize_runs(runs, match)
|
|
202
|
+
order = {"error": 0, "warning": 1, "info": 2, "unknown": 3}
|
|
203
|
+
rows = sorted(
|
|
204
|
+
records,
|
|
205
|
+
key=lambda x: (order[x["severity"]], x["path"] or "", x["line"] or 0, x["id"]),
|
|
206
|
+
)
|
|
207
|
+
return dict(
|
|
208
|
+
findings=rows[:MAX_FINDINGS],
|
|
209
|
+
omitted_findings=max(0, len(rows) - MAX_FINDINGS),
|
|
210
|
+
supplied_result_count=total,
|
|
211
|
+
normalized_locations=len(rows),
|
|
212
|
+
unresolved_count=sum(x["correlation"] == "unresolved" for x in rows),
|
|
213
|
+
limitations=[
|
|
214
|
+
"Caller-provided external metadata is unverified; no scanner or external result validity check was performed.",
|
|
215
|
+
"Only relative artifact labels and start-line coordinates are correlated with the explicitly supplied diff.",
|
|
216
|
+
"Messages, descriptions, embedded code, instructions, fixes, links, and external artifacts are ignored.",
|
|
217
|
+
"All unmatched/unresolved findings remain in the report subject to the explicit cap.",
|
|
218
|
+
],
|
|
219
|
+
)
|
patchpilot/formatting.py
ADDED
|
@@ -0,0 +1,175 @@
|
|
|
1
|
+
"""Suggest only narrowly verified trailing-whitespace formatting diffs."""
|
|
2
|
+
|
|
3
|
+
import ast
|
|
4
|
+
import difflib
|
|
5
|
+
from .analysis import InputError, MAX_FILES, MAX_FINDINGS, parse_diff, bounded
|
|
6
|
+
from .changed import _verify_context, infer, review_source
|
|
7
|
+
|
|
8
|
+
|
|
9
|
+
def _unified(before, after, path):
|
|
10
|
+
pieces = []
|
|
11
|
+
|
|
12
|
+
def lf_lines(value):
|
|
13
|
+
parts = value.split("\n")
|
|
14
|
+
return [line + "\n" for line in parts[:-1]] + ([parts[-1]] if parts[-1] else [])
|
|
15
|
+
|
|
16
|
+
for line in difflib.unified_diff(
|
|
17
|
+
lf_lines(before),
|
|
18
|
+
lf_lines(after),
|
|
19
|
+
fromfile="a/" + path,
|
|
20
|
+
tofile="b/" + path,
|
|
21
|
+
lineterm="\n",
|
|
22
|
+
):
|
|
23
|
+
pieces.append(
|
|
24
|
+
line if line.endswith("\n") else line + "\n\\n"
|
|
25
|
+
)
|
|
26
|
+
return "".join(pieces)
|
|
27
|
+
|
|
28
|
+
|
|
29
|
+
def _formatting_entry(item):
|
|
30
|
+
if (
|
|
31
|
+
not isinstance(item, dict)
|
|
32
|
+
or set(item) - {"path", "source"}
|
|
33
|
+
or not isinstance(item.get("path"), str)
|
|
34
|
+
or not isinstance(item.get("source"), str)
|
|
35
|
+
):
|
|
36
|
+
raise InputError("Formatting entries require exact path and full source")
|
|
37
|
+
return item["path"], item["source"]
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _supplied_sources(entries, expected):
|
|
41
|
+
if not isinstance(entries, list) or len(entries) > MAX_FILES:
|
|
42
|
+
raise InputError("Invalid formatting entries")
|
|
43
|
+
supplied = {}
|
|
44
|
+
total = 0
|
|
45
|
+
for item in entries:
|
|
46
|
+
path, source = _formatting_entry(item)
|
|
47
|
+
if path not in expected or path in supplied:
|
|
48
|
+
raise InputError("Formatting path must match a unique supplied diff path")
|
|
49
|
+
bounded(source, name="source")
|
|
50
|
+
total += len(source.encode("utf-8"))
|
|
51
|
+
if total > 1024 * 1024:
|
|
52
|
+
raise InputError("Formatting sources exceed 1 MiB")
|
|
53
|
+
supplied[path] = source
|
|
54
|
+
return supplied
|
|
55
|
+
|
|
56
|
+
|
|
57
|
+
def _context_skip(path, source, file, language):
|
|
58
|
+
if language not in {"python", "json"}:
|
|
59
|
+
return dict(
|
|
60
|
+
path=path,
|
|
61
|
+
reason="Only Python and strict JSON have verified formatting suggestions.",
|
|
62
|
+
)
|
|
63
|
+
if any(c in path for c in "\r\n\t\x00") or "\r" in source:
|
|
64
|
+
return dict(path=path, reason="Unsupported path label or non-LF line endings.")
|
|
65
|
+
valid, _, bad = _verify_context(
|
|
66
|
+
source, file.new_context, file.new_ranges, file.new_eof
|
|
67
|
+
)
|
|
68
|
+
if not file.hunks or not valid:
|
|
69
|
+
return dict(path=path, reason="No verified post-change text context.", line=bad)
|
|
70
|
+
return None
|
|
71
|
+
|
|
72
|
+
|
|
73
|
+
def _syntax_skip(source, path, language):
|
|
74
|
+
try:
|
|
75
|
+
before = review_source(source, path, language)
|
|
76
|
+
except InputError:
|
|
77
|
+
return dict(path=path, reason="Source exceeds review bounds.")
|
|
78
|
+
if before["syntax_ok"] is not True:
|
|
79
|
+
return dict(
|
|
80
|
+
path=path,
|
|
81
|
+
reason="Syntax is not proven valid; no suggested formatting patch.",
|
|
82
|
+
)
|
|
83
|
+
return None
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _trim_added_lines(source, added_lines):
|
|
87
|
+
# Git lines are LF-delimited.
|
|
88
|
+
lines = source.split("\n")
|
|
89
|
+
candidates = [
|
|
90
|
+
n
|
|
91
|
+
for n in added_lines
|
|
92
|
+
if 1 <= n <= len(lines) and lines[n - 1].endswith((" ", "\t"))
|
|
93
|
+
]
|
|
94
|
+
new_lines = list(lines)
|
|
95
|
+
for n in candidates:
|
|
96
|
+
new_lines[n - 1] = new_lines[n - 1].rstrip(" \t")
|
|
97
|
+
return candidates, "\n".join(new_lines)
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def _preserves_syntax(source, corrected, path, language):
|
|
101
|
+
try:
|
|
102
|
+
after = review_source(corrected, path, language)
|
|
103
|
+
if after["syntax_ok"] is not True:
|
|
104
|
+
return False
|
|
105
|
+
if language == "python":
|
|
106
|
+
left = ast.dump(ast.parse(source), include_attributes=False)
|
|
107
|
+
right = ast.dump(ast.parse(corrected), include_attributes=False)
|
|
108
|
+
if left != right:
|
|
109
|
+
return False
|
|
110
|
+
except (InputError, SyntaxError, ValueError, RecursionError):
|
|
111
|
+
return False
|
|
112
|
+
return True
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
def _propose(path, source, corrected, candidates, language):
|
|
116
|
+
if not _preserves_syntax(source, corrected, path, language):
|
|
117
|
+
return None, dict(
|
|
118
|
+
path=path,
|
|
119
|
+
reason="Whitespace removal did not preserve verified syntax/AST.",
|
|
120
|
+
)
|
|
121
|
+
proposed = _unified(source, corrected, path)
|
|
122
|
+
if len(proposed.encode("utf-8")) > 256 * 1024:
|
|
123
|
+
return None, dict(path=path, reason="Proposed patch exceeds limits.")
|
|
124
|
+
return (
|
|
125
|
+
dict(
|
|
126
|
+
path=path,
|
|
127
|
+
changed_lines=candidates,
|
|
128
|
+
unified_diff=proposed,
|
|
129
|
+
evidence=(
|
|
130
|
+
"verified_python_ast"
|
|
131
|
+
if language == "python"
|
|
132
|
+
else "verified_json_grammar"
|
|
133
|
+
),
|
|
134
|
+
action="Review this formatting-only suggestion; it has not been applied.",
|
|
135
|
+
),
|
|
136
|
+
None,
|
|
137
|
+
)
|
|
138
|
+
|
|
139
|
+
|
|
140
|
+
def _suggest_file(path, source, file):
|
|
141
|
+
language = infer(path)
|
|
142
|
+
skip = _context_skip(path, source, file, language)
|
|
143
|
+
if skip:
|
|
144
|
+
return None, skip
|
|
145
|
+
skip = _syntax_skip(source, path, language)
|
|
146
|
+
if skip:
|
|
147
|
+
return None, skip
|
|
148
|
+
candidates, corrected = _trim_added_lines(source, file.added_lines)
|
|
149
|
+
if not candidates:
|
|
150
|
+
return None, None
|
|
151
|
+
return _propose(path, source, corrected, candidates, language)
|
|
152
|
+
|
|
153
|
+
|
|
154
|
+
def suggest_formatting_patch(diff, entries):
|
|
155
|
+
"""Return proposed suggestions only, never write or apply them."""
|
|
156
|
+
files, _ = parse_diff(diff)
|
|
157
|
+
expected = {f.path: f for f in files if f.new != "/dev/null"}
|
|
158
|
+
supplied = _supplied_sources(entries, expected)
|
|
159
|
+
suggestions = []
|
|
160
|
+
skipped = []
|
|
161
|
+
for path, source in supplied.items():
|
|
162
|
+
suggestion, skip = _suggest_file(path, source, expected[path])
|
|
163
|
+
if suggestion is not None:
|
|
164
|
+
suggestions.append(suggestion)
|
|
165
|
+
if skip is not None:
|
|
166
|
+
skipped.append(skip)
|
|
167
|
+
return dict(
|
|
168
|
+
suggestions=suggestions[:MAX_FINDINGS],
|
|
169
|
+
skipped=skipped,
|
|
170
|
+
limitations=[
|
|
171
|
+
"Only trailing spaces/tabs on added lines in supplied, context-matching Python or strict JSON.",
|
|
172
|
+
"Python AST equality and successful syntax before/after required; comments and external formatting conventions still require human review.",
|
|
173
|
+
"No patch applied, no project files opened, no other fixes generated.",
|
|
174
|
+
],
|
|
175
|
+
)
|
patchpilot/js_review.py
ADDED
|
@@ -0,0 +1,253 @@
|
|
|
1
|
+
"""Bounded Tree-sitter grammar parsing and ordinary JS/TS maintainability."""
|
|
2
|
+
|
|
3
|
+
from importlib import import_module
|
|
4
|
+
from .analysis import MAX_FINDINGS, MAX_AST_NODES, InputError, bounded, finding
|
|
5
|
+
from .common import no_input
|
|
6
|
+
|
|
7
|
+
GRAMMARS = {
|
|
8
|
+
"javascript": ("tree_sitter_javascript", "language"),
|
|
9
|
+
"jsx": ("tree_sitter_javascript", "language"),
|
|
10
|
+
"typescript": ("tree_sitter_typescript", "language_typescript"),
|
|
11
|
+
"tsx": ("tree_sitter_typescript", "language_tsx"),
|
|
12
|
+
"go": ("tree_sitter_go", "language"),
|
|
13
|
+
"java": ("tree_sitter_java", "language"),
|
|
14
|
+
"csharp": ("tree_sitter_c_sharp", "language"),
|
|
15
|
+
"dart": ("tree_sitter_dart", "language"),
|
|
16
|
+
}
|
|
17
|
+
JS_LANGUAGES = {"javascript", "jsx", "typescript", "tsx"}
|
|
18
|
+
|
|
19
|
+
|
|
20
|
+
def parse_tree(source, language):
|
|
21
|
+
"""Return explicit source bytes and a grammar tree, or None if parser unavailable."""
|
|
22
|
+
try:
|
|
23
|
+
from tree_sitter import Language, Parser
|
|
24
|
+
|
|
25
|
+
module, name = GRAMMARS[language]
|
|
26
|
+
grammar = getattr(import_module(module), name)
|
|
27
|
+
parser = Parser(Language(grammar()))
|
|
28
|
+
except (ImportError, OSError, AttributeError, TypeError, ValueError):
|
|
29
|
+
return None
|
|
30
|
+
raw = source.encode("utf-8")
|
|
31
|
+
return raw, parser.parse(raw).root_node
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def _column(raw, node):
|
|
35
|
+
_, byte_col = node.start_point
|
|
36
|
+
line_start = node.start_byte - byte_col
|
|
37
|
+
return len(raw[line_start : node.start_byte].decode("utf-8", errors="replace")) + 1
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def _lexical_rules(statement, raw, seen, emit):
|
|
41
|
+
for declaration in statement.named_children:
|
|
42
|
+
if declaration.type != "variable_declarator":
|
|
43
|
+
continue
|
|
44
|
+
name = declaration.child_by_field_name("name")
|
|
45
|
+
if name is None or name.type != "identifier":
|
|
46
|
+
continue
|
|
47
|
+
key = raw[name.start_byte : name.end_byte].decode("utf-8")
|
|
48
|
+
# Escaped identifiers are outside reliable literal-name comparison.
|
|
49
|
+
if "\\" in key:
|
|
50
|
+
continue
|
|
51
|
+
if key in seen:
|
|
52
|
+
emit(
|
|
53
|
+
"JS_DUPLICATE_LEXICAL",
|
|
54
|
+
"warning",
|
|
55
|
+
"heuristic",
|
|
56
|
+
name,
|
|
57
|
+
"Repeated direct lexical binding in the same supplied block.",
|
|
58
|
+
"Confirm declaration scope and consolidate or rename the duplicate binding.",
|
|
59
|
+
)
|
|
60
|
+
else:
|
|
61
|
+
seen[key] = name.start_point[0]
|
|
62
|
+
|
|
63
|
+
|
|
64
|
+
def _js_rules(node, raw, emit):
|
|
65
|
+
# Only direct sibling lexical declarations; ignore var, functions, imports,
|
|
66
|
+
# destructuring, and TS overloads or declarations in other scopes.
|
|
67
|
+
if node.type not in {"program", "statement_block"}:
|
|
68
|
+
return
|
|
69
|
+
seen = {}
|
|
70
|
+
terminal = False
|
|
71
|
+
for statement in node.named_children:
|
|
72
|
+
if statement.type in {
|
|
73
|
+
"comment",
|
|
74
|
+
"empty_statement",
|
|
75
|
+
"function_declaration",
|
|
76
|
+
"generator_function_declaration",
|
|
77
|
+
"interface_declaration",
|
|
78
|
+
"type_alias_declaration",
|
|
79
|
+
"ambient_declaration",
|
|
80
|
+
"import_statement",
|
|
81
|
+
}:
|
|
82
|
+
continue
|
|
83
|
+
if terminal:
|
|
84
|
+
emit(
|
|
85
|
+
"JS_UNREACHABLE_STATEMENT",
|
|
86
|
+
"warning",
|
|
87
|
+
"heuristic",
|
|
88
|
+
statement,
|
|
89
|
+
"Direct statement follows an unconditional control-flow terminator.",
|
|
90
|
+
"Check whether the code should run before the terminator or can be removed.",
|
|
91
|
+
)
|
|
92
|
+
terminal = False
|
|
93
|
+
# only the first statement following a terminator is highlighted.
|
|
94
|
+
if statement.type in {
|
|
95
|
+
"return_statement",
|
|
96
|
+
"throw_statement",
|
|
97
|
+
"break_statement",
|
|
98
|
+
"continue_statement",
|
|
99
|
+
}:
|
|
100
|
+
terminal = True
|
|
101
|
+
if statement.type != "lexical_declaration":
|
|
102
|
+
continue
|
|
103
|
+
_lexical_rules(statement, raw, seen, emit)
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def _walk_nodes(root):
|
|
107
|
+
stack, count = [root], 0
|
|
108
|
+
while stack:
|
|
109
|
+
node = stack.pop()
|
|
110
|
+
count += 1
|
|
111
|
+
if count > MAX_AST_NODES:
|
|
112
|
+
raise InputError(f"Parse tree exceeds {MAX_AST_NODES} nodes")
|
|
113
|
+
yield node
|
|
114
|
+
stack.extend(reversed(node.children))
|
|
115
|
+
|
|
116
|
+
|
|
117
|
+
def _collect_comment(node, raw, start_line, include_comments, comment_lines):
|
|
118
|
+
if (
|
|
119
|
+
include_comments
|
|
120
|
+
and node.type == "comment"
|
|
121
|
+
and node.start_point[0] == node.end_point[0]
|
|
122
|
+
):
|
|
123
|
+
comment_lines.setdefault(start_line + node.start_point[0], []).append(
|
|
124
|
+
raw[node.start_byte : node.end_byte].decode("utf-8")
|
|
125
|
+
)
|
|
126
|
+
|
|
127
|
+
|
|
128
|
+
def _needs_fallback(root, issues):
|
|
129
|
+
return root.has_error and not issues
|
|
130
|
+
|
|
131
|
+
|
|
132
|
+
def _grammar_options(language, root):
|
|
133
|
+
return (
|
|
134
|
+
"JS_TS_SYNTAX" if language in JS_LANGUAGES else "STATIC_SYNTAX",
|
|
135
|
+
not root.has_error and language in JS_LANGUAGES,
|
|
136
|
+
)
|
|
137
|
+
|
|
138
|
+
|
|
139
|
+
def _inspect_tree(raw, root, path, start_line, language, include_comments):
|
|
140
|
+
issues = []
|
|
141
|
+
comment_lines = {}
|
|
142
|
+
|
|
143
|
+
def emit(code, severity, evidence, node, message, recommendation):
|
|
144
|
+
row, _ = node.start_point
|
|
145
|
+
f = finding(
|
|
146
|
+
code, severity, evidence, path, start_line + row, message, recommendation
|
|
147
|
+
)
|
|
148
|
+
f["column"] = _column(raw, node)
|
|
149
|
+
issues.append(f)
|
|
150
|
+
|
|
151
|
+
syntax_rule, run_js_rules = _grammar_options(language, root)
|
|
152
|
+
for node in _walk_nodes(root):
|
|
153
|
+
if node.is_error or node.is_missing:
|
|
154
|
+
emit(
|
|
155
|
+
syntax_rule,
|
|
156
|
+
"error",
|
|
157
|
+
"fact",
|
|
158
|
+
node,
|
|
159
|
+
(
|
|
160
|
+
"Missing grammar token."
|
|
161
|
+
if node.is_missing
|
|
162
|
+
else "Text does not match the selected grammar."
|
|
163
|
+
),
|
|
164
|
+
"Check syntax and surrounding context for the chosen language.",
|
|
165
|
+
)
|
|
166
|
+
if run_js_rules:
|
|
167
|
+
_js_rules(node, raw, emit)
|
|
168
|
+
_collect_comment(node, raw, start_line, include_comments, comment_lines)
|
|
169
|
+
if _needs_fallback(root, issues):
|
|
170
|
+
issues.append(
|
|
171
|
+
finding(
|
|
172
|
+
syntax_rule,
|
|
173
|
+
"error",
|
|
174
|
+
"fact",
|
|
175
|
+
path,
|
|
176
|
+
start_line,
|
|
177
|
+
"Parser reported an incomplete syntax tree.",
|
|
178
|
+
"Review supplied source in isolation.",
|
|
179
|
+
)
|
|
180
|
+
)
|
|
181
|
+
return issues, comment_lines
|
|
182
|
+
|
|
183
|
+
|
|
184
|
+
def _validate_static(language, path, start_line):
|
|
185
|
+
if language not in GRAMMARS:
|
|
186
|
+
raise InputError("Unsupported static language")
|
|
187
|
+
if not 1 <= start_line <= 10**8 or not path or len(path) > 1024:
|
|
188
|
+
raise InputError("Invalid path label or line offset")
|
|
189
|
+
|
|
190
|
+
|
|
191
|
+
def review_static(
|
|
192
|
+
source: str,
|
|
193
|
+
path: str = "snippet.js",
|
|
194
|
+
start_line: int = 1,
|
|
195
|
+
language: str = "javascript",
|
|
196
|
+
*,
|
|
197
|
+
include_comments: bool = False,
|
|
198
|
+
complete: bool = False,
|
|
199
|
+
) -> dict:
|
|
200
|
+
lines = bounded(source, name="source")
|
|
201
|
+
_validate_static(language, path, start_line)
|
|
202
|
+
if source == "" and not complete:
|
|
203
|
+
return no_input(path, language=language)
|
|
204
|
+
limitations = [
|
|
205
|
+
"Tree-sitter grammar checks only; no semantic/type checking, execution, imports, project configuration or runtime validity.",
|
|
206
|
+
"JS/TS rules examine direct statement siblings conservatively; other languages receive grammar diagnostics only.",
|
|
207
|
+
f"Parse node count capped at {MAX_AST_NODES}; findings capped at {MAX_FINDINGS}.",
|
|
208
|
+
]
|
|
209
|
+
parsed = parse_tree(source, language)
|
|
210
|
+
if parsed is None:
|
|
211
|
+
return dict(
|
|
212
|
+
path=path,
|
|
213
|
+
language=language,
|
|
214
|
+
syntax_ok=None,
|
|
215
|
+
coverage="unknown_parser_unavailable",
|
|
216
|
+
lines=len(lines),
|
|
217
|
+
findings=[],
|
|
218
|
+
omitted_findings=0,
|
|
219
|
+
limitations=limitations
|
|
220
|
+
+ ["Static parser dependency is unavailable or incompatible."],
|
|
221
|
+
)
|
|
222
|
+
raw, root = parsed
|
|
223
|
+
issues, comment_lines = _inspect_tree(
|
|
224
|
+
raw, root, path, start_line, language, include_comments
|
|
225
|
+
)
|
|
226
|
+
report = dict(
|
|
227
|
+
path=path,
|
|
228
|
+
language=language,
|
|
229
|
+
syntax_ok=not root.has_error,
|
|
230
|
+
coverage=(
|
|
231
|
+
"checked_incomplete_findings"
|
|
232
|
+
if len(issues) > MAX_FINDINGS
|
|
233
|
+
else "grammar_checked"
|
|
234
|
+
),
|
|
235
|
+
lines=len(lines),
|
|
236
|
+
findings=issues[:MAX_FINDINGS],
|
|
237
|
+
omitted_findings=max(0, len(issues) - MAX_FINDINGS),
|
|
238
|
+
limitations=limitations,
|
|
239
|
+
)
|
|
240
|
+
if include_comments:
|
|
241
|
+
report["comments"] = comment_lines
|
|
242
|
+
return report
|
|
243
|
+
|
|
244
|
+
|
|
245
|
+
def review_javascript(
|
|
246
|
+
source: str,
|
|
247
|
+
path: str = "snippet.js",
|
|
248
|
+
start_line: int = 1,
|
|
249
|
+
language: str = "javascript",
|
|
250
|
+
) -> dict:
|
|
251
|
+
if language not in JS_LANGUAGES:
|
|
252
|
+
raise InputError("Unsupported JavaScript/TypeScript language")
|
|
253
|
+
return review_static(source, path, start_line, language)
|