prism-code-workspace 1.0.0__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,284 @@
1
+ """Structural comparison engine: Prism analysis trees -> structscope diff.
2
+
3
+ Kept free of Qt imports so it can be tested, scripted and reused. The heavy
4
+ lifting (symbol matching, status classification, two-column layout) is done by
5
+ the separate ``structscope`` package; this module only adapts the trees Prism
6
+ already builds into the symbol model structscope expects.
7
+
8
+ Requires ``structscope`` on the path: ``pip install structscope``.
9
+ """
10
+
11
+ from __future__ import annotations
12
+
13
+ import difflib
14
+ import hashlib
15
+ import sys
16
+ from pathlib import Path
17
+ from typing import Any, Dict, List, Optional, Tuple
18
+
19
+ try:
20
+ from structscope.diff import DiffResult
21
+ from structscope.matcher import match as match_symbols
22
+ from structscope.model import FileModel, Symbol
23
+
24
+ ENGINE_ERROR = ""
25
+ except Exception as exc: # pragma: no cover - depends on the environment
26
+ DiffResult = None # type: ignore[assignment]
27
+ match_symbols = None # type: ignore[assignment]
28
+ FileModel = None # type: ignore[assignment]
29
+ Symbol = None # type: ignore[assignment]
30
+ ENGINE_ERROR = f"{type(exc).__name__}: {exc}"
31
+
32
+ LANGUAGE_LABELS = [
33
+ ("python", "Python"), ("javascript", "JavaScript"), ("typescript", "TypeScript"),
34
+ ("java", "Java"), ("cpp", "C++"), ("c", "C"),
35
+ ]
36
+ FILE_EXTENSIONS = {
37
+ "python": ["py"], "javascript": ["js", "jsx", "mjs"], "typescript": ["ts", "tsx"],
38
+ "java": ["java"], "cpp": ["cpp", "cc", "cxx", "hpp", "h"], "c": ["c", "h"],
39
+ }
40
+
41
+ STATUS_COLORS = {
42
+ "added": "#57c98a",
43
+ "removed": "#ff6b6b",
44
+ "modified": "#f2b544",
45
+ "moved": "#6aa8ff",
46
+ "unchanged": "#59606b",
47
+ }
48
+ STATUS_FILL = {
49
+ "added": "#1e2f26",
50
+ "removed": "#33211f",
51
+ "modified": "#322a1b",
52
+ "moved": "#1d2733",
53
+ "unchanged": "#22252a",
54
+ }
55
+
56
+ _CONTAINERS = {"class", "function"}
57
+ _DECISIONS = {
58
+ "if", "elif", "else", "for", "foreach", "while", "case", "catch", "when",
59
+ "switch", "match", "try", "ternary", "do",
60
+ }
61
+
62
+
63
+ def analyze_source(language: str, source: str) -> Dict[str, Any]:
64
+ """Run the analyzer that belongs to ``language``.
65
+
66
+ The analyzers are imported on demand: the compiled-language one needs
67
+ tree-sitter, and a missing optional dependency should not stop Prism from
68
+ comparing Python files.
69
+ """
70
+ if language == "python":
71
+ try:
72
+ from python_app.analysis import analyze_python
73
+ except ImportError:
74
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
75
+ from python_app.analysis import analyze_python
76
+ return analyze_python(source)
77
+ if language in ("javascript", "typescript"):
78
+ try:
79
+ from python_app.js_analysis import analyze_javascript
80
+ except ImportError:
81
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
82
+ from python_app.js_analysis import analyze_javascript
83
+ return analyze_javascript(source, language)
84
+ try:
85
+ from python_app.compiled_analysis import analyze_compiled
86
+ except ImportError:
87
+ sys.path.insert(0, str(Path(__file__).resolve().parent.parent))
88
+ from python_app.compiled_analysis import analyze_compiled
89
+ return analyze_compiled(source, language)
90
+
91
+
92
+ def _children(node: Dict[str, Any]) -> List[Dict[str, Any]]:
93
+ body = node.get("body")
94
+ if isinstance(body, dict):
95
+ return list(body.get("children") or [])
96
+ if isinstance(body, list):
97
+ return list(body)
98
+ return []
99
+
100
+
101
+ def _flat_text(node: Dict[str, Any]) -> str:
102
+ return " ".join(str(node.get("header") or node.get("text") or "").split())
103
+
104
+
105
+ def _signature(node: Dict[str, Any], drop_name: str = "") -> str:
106
+ """Structural signature of a subtree: node types plus their source text.
107
+
108
+ Node ids are skipped on purpose: they change on every parse and would make
109
+ every symbol look modified. The symbol's own name can be dropped so that a
110
+ rename shows up as "moved" instead of "modified + added + removed".
111
+ """
112
+ parts: List[str] = []
113
+ stack: List[Tuple[Dict[str, Any], bool]] = [(node, True)]
114
+ while stack:
115
+ current, is_root = stack.pop()
116
+ text = _flat_text(current)
117
+ if is_root and drop_name and drop_name in text:
118
+ text = text.replace(drop_name, "\x00", 1)
119
+ parts.append(f"{current.get('type')}:{text}")
120
+ for child in reversed(_children(current)):
121
+ stack.append((child, False))
122
+ return "\n".join(parts)
123
+
124
+
125
+ def _body_hash(node: Dict[str, Any], name: str) -> str:
126
+ return hashlib.sha1(_signature(node, name).encode("utf-8")).hexdigest()
127
+
128
+
129
+ def _subtree_complexity(node: Dict[str, Any]) -> int:
130
+ total = 1
131
+ stack = [node]
132
+ while stack:
133
+ current = stack.pop()
134
+ for child in _children(current):
135
+ if child.get("type") in _DECISIONS:
136
+ total += 1
137
+ stack.append(child)
138
+ return total
139
+
140
+
141
+ def _has_doc_above(lines: List[str], start_line: int) -> bool:
142
+ index = start_line - 2
143
+ checked = 0
144
+ while index >= 0 and checked < 6:
145
+ stripped = lines[index].strip()
146
+ checked += 1
147
+ index -= 1
148
+ if not stripped or stripped.startswith("@"):
149
+ continue
150
+ return (
151
+ stripped.startswith("#")
152
+ or stripped.startswith("//")
153
+ or stripped.startswith("/*")
154
+ or stripped.startswith("*")
155
+ or stripped.startswith('"""')
156
+ or stripped.startswith("'''")
157
+ )
158
+ return False
159
+
160
+
161
+ def model_from_analysis(analysis: Dict[str, Any], label: str) -> Any:
162
+ """Build a structscope ``FileModel`` out of one Prism analysis result."""
163
+ raw_lines = analysis.get("lines") or []
164
+ lines = [
165
+ item.get("text", "") if isinstance(item, dict) else str(item)
166
+ for item in raw_lines
167
+ ]
168
+ source = "\n".join(lines)
169
+
170
+ def walk(nodes: List[Dict[str, Any]], prefix: str, depth: int, parent_kind: str) -> List[Any]:
171
+ found = []
172
+ for node in nodes:
173
+ kind_raw = node.get("type")
174
+ if kind_raw not in _CONTAINERS:
175
+ continue
176
+ name = str(node.get("name") or "anonymous")
177
+ if kind_raw == "class":
178
+ kind = "class"
179
+ elif parent_kind == "class":
180
+ kind = "method"
181
+ elif depth == 0:
182
+ kind = "function"
183
+ else:
184
+ kind = "nested"
185
+ qualname = f"{prefix}{name}"
186
+ start = int(node.get("startLine") or 1)
187
+ end = int(node.get("endLine") or start)
188
+ symbol = Symbol(
189
+ kind=kind,
190
+ name=name,
191
+ qualname=qualname,
192
+ lineno=start,
193
+ end_lineno=end,
194
+ depth=depth,
195
+ loc=sum(1 for line in lines[start - 1:end] if line.strip()),
196
+ complexity=_subtree_complexity(node),
197
+ params=len(node.get("params") or []),
198
+ has_doc=_has_doc_above(lines, start),
199
+ body_hash=_body_hash(node, name),
200
+ )
201
+ symbol.children = walk(_children(node), f"{qualname}.", depth + 1, kind)
202
+ found.append(symbol)
203
+ return found
204
+
205
+ root = analysis.get("root") or {}
206
+ symbols = walk(_children(root), "", 0, "")
207
+ return FileModel(
208
+ path=label,
209
+ label=label,
210
+ source=source,
211
+ lines=lines,
212
+ symbols=symbols,
213
+ loc=sum(1 for line in lines if line.strip()),
214
+ )
215
+
216
+
217
+ def compare_sources(
218
+ language: str,
219
+ old_source: str,
220
+ new_source: str,
221
+ old_label: str = "before",
222
+ new_label: str = "after",
223
+ ) -> Any:
224
+ """Diff two source strings with Prism's parsers and structscope's matcher."""
225
+ if ENGINE_ERROR:
226
+ raise RuntimeError(
227
+ "structscope is not available; install it with: pip install structscope"
228
+ )
229
+ old_analysis = analyze_source(language, old_source)["analysis"]
230
+ new_analysis = analyze_source(language, new_source)["analysis"]
231
+ old = model_from_analysis(old_analysis, old_label)
232
+ new = model_from_analysis(new_analysis, new_label)
233
+ pairs = match_symbols(old.symbols, new.symbols)
234
+ class PrismDiffResult(DiffResult):
235
+ def summary(self):
236
+ return {**super().summary(), "language": language}
237
+
238
+ result = PrismDiffResult(old=old, new=new, pairs=pairs)
239
+ return result
240
+
241
+
242
+ def aligned_rows(
243
+ old_lines: List[str], new_lines: List[str], old_start: int, new_start: int
244
+ ) -> List[Tuple[str, int, str, int, str]]:
245
+ """Line pairs for the detail table: (tag, old_no, old_text, new_no, new_text)."""
246
+ matcher = difflib.SequenceMatcher(a=old_lines, b=new_lines, autojunk=False)
247
+ rows: List[Tuple[str, int, str, int, str]] = []
248
+ for tag, i1, i2, j1, j2 in matcher.get_opcodes():
249
+ if tag == "equal":
250
+ for offset in range(i2 - i1):
251
+ rows.append((
252
+ "eq",
253
+ old_start + i1 + offset,
254
+ old_lines[i1 + offset],
255
+ new_start + j1 + offset,
256
+ new_lines[j1 + offset],
257
+ ))
258
+ continue
259
+ old_count = i2 - i1
260
+ new_count = j2 - j1
261
+ for offset in range(max(old_count, new_count)):
262
+ has_old = offset < old_count
263
+ has_new = offset < new_count
264
+ rows.append((
265
+ "rep" if has_old and has_new else ("del" if has_old else "ins"),
266
+ old_start + i1 + offset if has_old else 0,
267
+ old_lines[i1 + offset] if has_old else "",
268
+ new_start + j1 + offset if has_new else 0,
269
+ new_lines[j1 + offset] if has_new else "",
270
+ ))
271
+ return rows
272
+
273
+
274
+ def describe(summary: Dict[str, Any]) -> str:
275
+ """One-line stats string shared by the CLI-style output and the UI."""
276
+ return (
277
+ f"{summary['added']} added · {summary['removed']} removed · "
278
+ f"{summary['modified']} modified · {summary['moved']} moved · "
279
+ f"{summary['unchanged']} unchanged | "
280
+ f"LOC {summary['old_loc']} \u2192 {summary['new_loc']} "
281
+ f"({summary['loc_delta']:+d}) | "
282
+ f"complexity {summary['old_complexity']} \u2192 {summary['new_complexity']} "
283
+ f"({summary['complexity_delta']:+d})"
284
+ )