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.
- prism_code_workspace-1.0.0.dist-info/METADATA +272 -0
- prism_code_workspace-1.0.0.dist-info/RECORD +30 -0
- prism_code_workspace-1.0.0.dist-info/WHEEL +4 -0
- prism_code_workspace-1.0.0.dist-info/entry_points.txt +3 -0
- prism_code_workspace-1.0.0.dist-info/licenses/LICENSE +21 -0
- python_app/__init__.py +3 -0
- python_app/ai.py +225 -0
- python_app/analysis.py +953 -0
- python_app/compare.py +685 -0
- python_app/compare_engine.py +284 -0
- python_app/compiled_analysis.py +727 -0
- python_app/desktop.py +181 -0
- python_app/function_pov/__init__.py +16 -0
- python_app/function_pov/analyzer.py +464 -0
- python_app/function_pov/graph.py +50 -0
- python_app/function_pov/models.py +53 -0
- python_app/function_pov/pov/__init__.py +17 -0
- python_app/function_pov/pov/engine.py +1630 -0
- python_app/function_pov/pov/exercises.py +1263 -0
- python_app/function_pov_ui.py +1749 -0
- python_app/i18n.py +570 -0
- python_app/installer.nsi +70 -0
- python_app/installer_runtime.nsi +70 -0
- python_app/js_analysis.py +709 -0
- python_app/launch.py +6 -0
- python_app/launch_native.py +14 -0
- python_app/metrics_advisor.py +79 -0
- python_app/native_app.py +1709 -0
- python_app/requirements.txt +7 -0
- python_app/server.py +453 -0
|
@@ -0,0 +1,727 @@
|
|
|
1
|
+
"""Python-native analysis for Java, C++ and C.
|
|
2
|
+
|
|
3
|
+
This is a practical beginner subset: declarations, assignments, conditions,
|
|
4
|
+
loops, functions/methods, returns and common print calls. Parsing uses
|
|
5
|
+
tree-sitter; the trace is a bounded evaluator and never executes source code.
|
|
6
|
+
"""
|
|
7
|
+
|
|
8
|
+
from __future__ import annotations
|
|
9
|
+
|
|
10
|
+
import re
|
|
11
|
+
from dataclasses import dataclass, field
|
|
12
|
+
from typing import Any
|
|
13
|
+
|
|
14
|
+
from tree_sitter import Language, Parser
|
|
15
|
+
|
|
16
|
+
import tree_sitter_java as tsjava
|
|
17
|
+
import tree_sitter_cpp as tscpp
|
|
18
|
+
import tree_sitter_c as tsc
|
|
19
|
+
|
|
20
|
+
from python_app.js_analysis import _guide
|
|
21
|
+
|
|
22
|
+
LANGUAGES = {
|
|
23
|
+
"java": {"id": "java", "name": "Java", "extension": "java"},
|
|
24
|
+
"cpp": {"id": "cpp", "name": "C++", "extension": "cpp"},
|
|
25
|
+
"c": {"id": "c", "name": "C", "extension": "c"},
|
|
26
|
+
}
|
|
27
|
+
PARSERS = {
|
|
28
|
+
"java": Language(tsjava.language()),
|
|
29
|
+
"cpp": Language(tscpp.language()),
|
|
30
|
+
"c": Language(tsc.language()),
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
|
|
34
|
+
def parser(language: str) -> Parser:
|
|
35
|
+
return Parser(PARSERS.get(language, PARSERS["c"]))
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
class Factory:
|
|
39
|
+
def __init__(self, source: str, language: str):
|
|
40
|
+
self.source = source
|
|
41
|
+
self.language = language
|
|
42
|
+
self.bytes = source.encode("utf-8")
|
|
43
|
+
self.lines = source.split("\n")
|
|
44
|
+
self.parser = parser(language)
|
|
45
|
+
self.counter = 0
|
|
46
|
+
self.functions: list[dict[str, Any]] = []
|
|
47
|
+
self.classes: list[dict[str, Any]] = []
|
|
48
|
+
self.assignments: list[dict[str, Any]] = []
|
|
49
|
+
self.actions: list[dict[str, Any]] = []
|
|
50
|
+
self.counts = {"loops": 0, "conditions": 0, "returns": 0, "maxDepth": 0}
|
|
51
|
+
|
|
52
|
+
def nid(self) -> str:
|
|
53
|
+
self.counter += 1
|
|
54
|
+
return f"cf-node-{self.counter}"
|
|
55
|
+
|
|
56
|
+
def text(self, node) -> str:
|
|
57
|
+
return self.bytes[node.start_byte:node.end_byte].decode("utf-8", "replace")
|
|
58
|
+
|
|
59
|
+
def line(self, node) -> int:
|
|
60
|
+
return node.start_point.row + 1
|
|
61
|
+
|
|
62
|
+
def end(self, node) -> int:
|
|
63
|
+
return node.end_point.row + 1
|
|
64
|
+
|
|
65
|
+
def field(self, node, name: str):
|
|
66
|
+
return node.child_by_field_name(name) if node else None
|
|
67
|
+
|
|
68
|
+
def block(self, node, depth: int) -> dict[str, Any]:
|
|
69
|
+
if node is None:
|
|
70
|
+
return {"type": "block", "startLine": 1, "endLine": 1, "children": []}
|
|
71
|
+
target = node
|
|
72
|
+
if node.type in {"block", "compound_statement", "class_body", "program", "translation_unit"}:
|
|
73
|
+
children = [self.convert(child, depth + 1) for child in node.named_children]
|
|
74
|
+
else:
|
|
75
|
+
children = [self.convert(node, depth + 1)]
|
|
76
|
+
flat = []
|
|
77
|
+
for child in children:
|
|
78
|
+
if isinstance(child, list):
|
|
79
|
+
flat.extend(child)
|
|
80
|
+
elif child:
|
|
81
|
+
flat.append(child)
|
|
82
|
+
return {"type": "block", "startLine": self.line(target), "endLine": self.end(target),
|
|
83
|
+
"children": flat}
|
|
84
|
+
|
|
85
|
+
def action(self, node, subtype: str, **extra) -> dict[str, Any]:
|
|
86
|
+
raw = self.text(node).strip()
|
|
87
|
+
return {
|
|
88
|
+
"type": "action", "id": self.nid(), "startLine": self.line(node),
|
|
89
|
+
"endLine": self.end(node), "header": raw, "text": raw,
|
|
90
|
+
"action": {"subtype": subtype, "raw": raw, "line": self.line(node),
|
|
91
|
+
"expressionText": raw, **extra},
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
def record(self, node, target: str, expression: str, dependencies: list[str],
|
|
95
|
+
operator: str, declaration: bool) -> None:
|
|
96
|
+
node["action"].update({
|
|
97
|
+
"subtype": "declaration" if declaration else "assignment",
|
|
98
|
+
"assignment": True, "targetDisplay": target, "targetName": target,
|
|
99
|
+
"isDeclaration": declaration, "operator": operator,
|
|
100
|
+
"expressionText": expression, "dependencies": dependencies,
|
|
101
|
+
})
|
|
102
|
+
record = {
|
|
103
|
+
"id": f"assignment-{len(self.assignments) + 1}", "nodeId": node["id"],
|
|
104
|
+
"line": node["startLine"], "endLine": node["endLine"], "target": target,
|
|
105
|
+
"targetName": target, "expressionText": expression,
|
|
106
|
+
"dependencies": dependencies, "operator": operator,
|
|
107
|
+
"isDeclaration": declaration, "scope": "Global", "action": node["action"],
|
|
108
|
+
}
|
|
109
|
+
self.assignments.append(record)
|
|
110
|
+
node["assignmentRecord"] = record
|
|
111
|
+
|
|
112
|
+
def names(self, node) -> list[str]:
|
|
113
|
+
result = []
|
|
114
|
+
def walk(n):
|
|
115
|
+
if n.type in {"identifier", "field_identifier"}:
|
|
116
|
+
value = self.text(n)
|
|
117
|
+
if value not in result:
|
|
118
|
+
result.append(value)
|
|
119
|
+
for child in n.named_children:
|
|
120
|
+
walk(child)
|
|
121
|
+
if node:
|
|
122
|
+
walk(node)
|
|
123
|
+
return result
|
|
124
|
+
|
|
125
|
+
def params(self, node) -> list[dict[str, Any]]:
|
|
126
|
+
result = []
|
|
127
|
+
for child in node.named_children if node else []:
|
|
128
|
+
if child.type in {"formal_parameter", "parameter_declaration"}:
|
|
129
|
+
text = self.text(child)
|
|
130
|
+
name = text.split("=")[0].strip().split()[-1].strip("[]") if text else ""
|
|
131
|
+
result.append({"name": name, "type": "", "defaultValue": None, "raw": text})
|
|
132
|
+
return result
|
|
133
|
+
|
|
134
|
+
def convert(self, node, depth: int = 0):
|
|
135
|
+
self.counts["maxDepth"] = max(self.counts["maxDepth"], depth)
|
|
136
|
+
kind = node.type
|
|
137
|
+
if kind in {"comment", "line_comment", "block_comment", "preproc_include", "using_declaration",
|
|
138
|
+
"import_declaration", "package_declaration"}:
|
|
139
|
+
return None
|
|
140
|
+
if kind == "class_declaration":
|
|
141
|
+
name = self.field(node, "name")
|
|
142
|
+
body = self.field(node, "body")
|
|
143
|
+
item = {
|
|
144
|
+
"type": "class", "id": self.nid(), "startLine": self.line(node),
|
|
145
|
+
"endLine": self.end(node), "header": f"class {self.text(name) if name else 'Class'}",
|
|
146
|
+
"name": self.text(name) if name else "Class",
|
|
147
|
+
"body": self.block(body, depth), "keyword": "class",
|
|
148
|
+
}
|
|
149
|
+
self.classes.append(item)
|
|
150
|
+
return item
|
|
151
|
+
if kind in {"method_declaration", "constructor_declaration", "function_definition"}:
|
|
152
|
+
return self.convert_function(node, depth)
|
|
153
|
+
if kind in {"local_variable_declaration", "declaration"}:
|
|
154
|
+
return self.convert_declaration(node, depth)
|
|
155
|
+
if kind == "if_statement":
|
|
156
|
+
self.counts["conditions"] += 1
|
|
157
|
+
condition = self.field(node, "condition")
|
|
158
|
+
consequence = self.field(node, "consequence")
|
|
159
|
+
alternative = self.field(node, "alternative")
|
|
160
|
+
return {
|
|
161
|
+
"type": "if", "id": self.nid(), "startLine": self.line(node),
|
|
162
|
+
"endLine": self.end(node), "header": self.text(node).split("{", 1)[0].strip(),
|
|
163
|
+
"condition": self.text(condition).strip("()") if condition else "condition",
|
|
164
|
+
"consequent": self.block(consequence, depth),
|
|
165
|
+
"alternate": self.block(alternative, depth) if alternative else None,
|
|
166
|
+
"hasElse": alternative is not None, "keyword": "if",
|
|
167
|
+
}
|
|
168
|
+
if kind in {"for_statement", "enhanced_for_statement", "for_range_loop"}:
|
|
169
|
+
self.counts["loops"] += 1
|
|
170
|
+
body = self.field(node, "body")
|
|
171
|
+
header = self.text(node).split("{", 1)[0].strip()
|
|
172
|
+
return {
|
|
173
|
+
"type": "for", "id": self.nid(), "startLine": self.line(node),
|
|
174
|
+
"endLine": self.end(node), "header": header, "loopHeader": header,
|
|
175
|
+
"body": self.block(body, depth), "keyword": "for",
|
|
176
|
+
"loopMeta": {"style": kind},
|
|
177
|
+
}
|
|
178
|
+
if kind == "while_statement":
|
|
179
|
+
self.counts["loops"] += 1
|
|
180
|
+
condition = self.field(node, "condition")
|
|
181
|
+
body = self.field(node, "body")
|
|
182
|
+
return {
|
|
183
|
+
"type": "while", "id": self.nid(), "startLine": self.line(node),
|
|
184
|
+
"endLine": self.end(node), "header": self.text(node).split("{", 1)[0].strip(),
|
|
185
|
+
"condition": self.text(condition).strip("()") if condition else "true",
|
|
186
|
+
"body": self.block(body, depth), "keyword": "while",
|
|
187
|
+
}
|
|
188
|
+
if kind == "return_statement":
|
|
189
|
+
self.counts["returns"] += 1
|
|
190
|
+
text = self.text(node).replace("return", "", 1).rstrip(";").strip()
|
|
191
|
+
return self.action(node, "return", expressionText=text)
|
|
192
|
+
if kind in {"break_statement", "continue_statement"}:
|
|
193
|
+
return self.action(node, "break" if "break" in kind else "continue")
|
|
194
|
+
if kind == "expression_statement":
|
|
195
|
+
expr = node.named_children[0] if node.named_children else None
|
|
196
|
+
if expr is None:
|
|
197
|
+
return None
|
|
198
|
+
return self.convert_expression(node, expr)
|
|
199
|
+
return self.action(node, "expression", expressionText=self.text(node))
|
|
200
|
+
|
|
201
|
+
def convert_function(self, node, depth: int):
|
|
202
|
+
if node.type == "function_definition":
|
|
203
|
+
declarator = self.field(node, "declarator")
|
|
204
|
+
name_node = self._first(declarator, "identifier") if declarator else None
|
|
205
|
+
params_node = self._first(declarator, "parameter_list") if declarator else None
|
|
206
|
+
body = self.field(node, "body")
|
|
207
|
+
name = self.text(name_node) if name_node else "function"
|
|
208
|
+
else:
|
|
209
|
+
name_node = self.field(node, "name")
|
|
210
|
+
params_node = self.field(node, "parameters")
|
|
211
|
+
body = self.field(node, "body")
|
|
212
|
+
name = self.text(name_node) if name_node else "method"
|
|
213
|
+
item = {
|
|
214
|
+
"type": "function", "id": self.nid(), "startLine": self.line(node),
|
|
215
|
+
"endLine": self.end(node), "header": self.text(node).split("{", 1)[0].strip(),
|
|
216
|
+
"name": name, "params": self.params(params_node), "returnType": "",
|
|
217
|
+
"body": self.block(body, depth), "keyword": "function", "scopeName": name,
|
|
218
|
+
}
|
|
219
|
+
item["actionCount"] = len(item["body"]["children"])
|
|
220
|
+
self.functions.append(item)
|
|
221
|
+
return item
|
|
222
|
+
|
|
223
|
+
def _first(self, node, type_name: str):
|
|
224
|
+
if node is None:
|
|
225
|
+
return None
|
|
226
|
+
if node.type == type_name:
|
|
227
|
+
return node
|
|
228
|
+
for child in node.named_children:
|
|
229
|
+
found = self._first(child, type_name)
|
|
230
|
+
if found:
|
|
231
|
+
return found
|
|
232
|
+
return None
|
|
233
|
+
|
|
234
|
+
def convert_declaration(self, node, depth: int):
|
|
235
|
+
results = []
|
|
236
|
+
declarators = [child for child in node.named_children if child.type in {"variable_declarator", "init_declarator"}]
|
|
237
|
+
for child in declarators:
|
|
238
|
+
name_node = self.field(child, "name") or self.field(child, "declarator")
|
|
239
|
+
value_node = self.field(child, "value")
|
|
240
|
+
if name_node is None:
|
|
241
|
+
name_node = self._first(child, "identifier")
|
|
242
|
+
if name_node is None:
|
|
243
|
+
continue
|
|
244
|
+
target = self.text(name_node).replace("[]", "").strip()
|
|
245
|
+
expression = self.text(value_node) if value_node else ""
|
|
246
|
+
declaration = True
|
|
247
|
+
action = self.action(node, "declaration", expressionText=expression)
|
|
248
|
+
self.record(action, target, expression, self.names(value_node), "=", declaration)
|
|
249
|
+
self.actions.append(action)
|
|
250
|
+
results.append(action)
|
|
251
|
+
if not results:
|
|
252
|
+
return self.action(node, "expression", expressionText=self.text(node))
|
|
253
|
+
return results[0] if len(results) == 1 else {
|
|
254
|
+
"type": "block", "startLine": self.line(node), "endLine": self.end(node), "children": results,
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
def convert_expression(self, node, expr):
|
|
258
|
+
raw = self.text(expr)
|
|
259
|
+
if expr.type in {"assignment_expression", "augmented_assignment_expression"}:
|
|
260
|
+
left = self.field(expr, "left")
|
|
261
|
+
right = self.field(expr, "right")
|
|
262
|
+
target = self.text(left) if left else "value"
|
|
263
|
+
value = self.text(right) if right else ""
|
|
264
|
+
operator = self.text(expr)[len(target):].rsplit(value, 1)[0].strip() if target and value else "="
|
|
265
|
+
action = self.action(node, "assignment", expressionText=value, operator=operator or "=")
|
|
266
|
+
self.record(action, target, value, self.names(right), operator or "=", False)
|
|
267
|
+
self.actions.append(action)
|
|
268
|
+
return action
|
|
269
|
+
if expr.type == "update_expression":
|
|
270
|
+
action = self.action(node, "update", expressionText=raw)
|
|
271
|
+
self.actions.append(action)
|
|
272
|
+
return action
|
|
273
|
+
if self._is_print(expr):
|
|
274
|
+
action = self.action(node, "print", printKind=self.language, expressionText=raw)
|
|
275
|
+
self.actions.append(action)
|
|
276
|
+
return action
|
|
277
|
+
if expr.type in {"method_invocation", "call_expression"}:
|
|
278
|
+
action = self.action(node, "call", expressionText=raw)
|
|
279
|
+
self.actions.append(action)
|
|
280
|
+
return action
|
|
281
|
+
return self.action(node, "expression", expressionText=raw)
|
|
282
|
+
|
|
283
|
+
def _is_print(self, expr) -> bool:
|
|
284
|
+
text = self.text(expr)
|
|
285
|
+
if "System.out.print" in text:
|
|
286
|
+
return True
|
|
287
|
+
if re.match(r"^(?:std::)?cout\s*<<", text):
|
|
288
|
+
return True
|
|
289
|
+
return expr.type == "call_expression" and re.match(r"printf\s*\(", text) is not None
|
|
290
|
+
|
|
291
|
+
|
|
292
|
+
@dataclass
|
|
293
|
+
class Trace:
|
|
294
|
+
steps: list[dict[str, Any]] = field(default_factory=list)
|
|
295
|
+
events: list[dict[str, Any]] = field(default_factory=list)
|
|
296
|
+
output: str = ""
|
|
297
|
+
warnings: list[str] = field(default_factory=list)
|
|
298
|
+
complete: bool = False
|
|
299
|
+
stopped: str | None = None
|
|
300
|
+
calls: int = 0
|
|
301
|
+
iterations: int = 0
|
|
302
|
+
scopes: list[dict[str, Any]] = field(default_factory=list)
|
|
303
|
+
global_scope: dict[str, Any] = field(default_factory=dict)
|
|
304
|
+
|
|
305
|
+
def display(self, value):
|
|
306
|
+
if isinstance(value, bool):
|
|
307
|
+
return "true" if value else "false"
|
|
308
|
+
if value is None:
|
|
309
|
+
return "null"
|
|
310
|
+
if isinstance(value, list):
|
|
311
|
+
return "{" + ", ".join(self.display(v) for v in value) + "}"
|
|
312
|
+
if isinstance(value, str):
|
|
313
|
+
return value
|
|
314
|
+
if isinstance(value, float) and value.is_integer():
|
|
315
|
+
return str(int(value))
|
|
316
|
+
return str(value)
|
|
317
|
+
|
|
318
|
+
def snapshot(self):
|
|
319
|
+
seen = set()
|
|
320
|
+
result = []
|
|
321
|
+
for scope in reversed(self.scopes + [self.global_scope]):
|
|
322
|
+
for name, value in scope.items():
|
|
323
|
+
if name in seen:
|
|
324
|
+
continue
|
|
325
|
+
seen.add(name)
|
|
326
|
+
result.append({"name": name, "display": self.display(value), "type": "array" if isinstance(value, list) else "number" if isinstance(value, (int, float)) else "string"})
|
|
327
|
+
return result[:20]
|
|
328
|
+
|
|
329
|
+
def add(self, line, kind, title, detail, code="", extra=None):
|
|
330
|
+
if len(self.steps) >= 420:
|
|
331
|
+
self.warnings.append("The trace reached its 420-step limit.")
|
|
332
|
+
raise StopIteration
|
|
333
|
+
self.steps.append({"index": len(self.steps), "line": line, "endLine": line, "kind": kind,
|
|
334
|
+
"title": title, "detail": detail, "vars": self.snapshot(),
|
|
335
|
+
"output": self.output, "outputDelta": "", "callStack": [],
|
|
336
|
+
"scope": "Global", "code": code, "extra": extra})
|
|
337
|
+
|
|
338
|
+
def event(self, kind, line, **data):
|
|
339
|
+
self.events.append({"kind": kind, "line": line, "target": data.get("target"),
|
|
340
|
+
"name": data.get("target"), "expressionText": data.get("expressionText"),
|
|
341
|
+
"operator": data.get("operator"), "value": self.display(data.get("value")),
|
|
342
|
+
"valueType": "number", "scope": "Global",
|
|
343
|
+
"dependencies": data.get("dependencies", []),
|
|
344
|
+
"stepIndex": len(self.steps) - 1 if self.steps else 0,
|
|
345
|
+
"index": len(self.events)})
|
|
346
|
+
|
|
347
|
+
|
|
348
|
+
class Return(Exception):
|
|
349
|
+
def __init__(self, value):
|
|
350
|
+
self.value = value
|
|
351
|
+
|
|
352
|
+
|
|
353
|
+
class Break(Exception):
|
|
354
|
+
pass
|
|
355
|
+
|
|
356
|
+
|
|
357
|
+
class Continue(Exception):
|
|
358
|
+
pass
|
|
359
|
+
|
|
360
|
+
|
|
361
|
+
class Runner:
|
|
362
|
+
def __init__(self, analysis: dict[str, Any], source: str):
|
|
363
|
+
self.analysis = analysis
|
|
364
|
+
self.source = source
|
|
365
|
+
self.bytes = source.encode("utf-8")
|
|
366
|
+
self.active_bytes = self.bytes
|
|
367
|
+
self.parser = parser(analysis["languageId"])
|
|
368
|
+
self.trace = Trace()
|
|
369
|
+
self.functions = {fn["name"]: fn for fn in analysis["functions"]}
|
|
370
|
+
|
|
371
|
+
def text(self, node):
|
|
372
|
+
data = self.active_bytes or self.bytes
|
|
373
|
+
return data[node.start_byte:node.end_byte].decode("utf-8", "replace")
|
|
374
|
+
|
|
375
|
+
def field(self, node, name: str):
|
|
376
|
+
return node.child_by_field_name(name) if node else None
|
|
377
|
+
|
|
378
|
+
def run(self):
|
|
379
|
+
self.trace.add(1, "start", "Program starts", "The source is parsed and simulated locally.")
|
|
380
|
+
target = self.analysis.get("entry", {}).get("node") if self.analysis.get("entry", {}).get("kind") == "function" else self.analysis["root"]
|
|
381
|
+
try:
|
|
382
|
+
if target and target.get("type") == "function":
|
|
383
|
+
self.call_function(target, [], self.trace.global_scope)
|
|
384
|
+
else:
|
|
385
|
+
self.exec_block(self.analysis["root"]["body"]["children"], self.trace.global_scope)
|
|
386
|
+
self.trace.complete = True
|
|
387
|
+
self.trace.add(max(1, len(self.source.split("\n"))), "end", "Program ends", "The simulated run finished.")
|
|
388
|
+
except StopIteration:
|
|
389
|
+
self.trace.stopped = "step_limit"
|
|
390
|
+
except Return:
|
|
391
|
+
self.trace.complete = True
|
|
392
|
+
except Exception as error: # pragma: no cover
|
|
393
|
+
self.trace.warnings.append(f"The trace stopped: {error}")
|
|
394
|
+
self.trace.stopped = "error"
|
|
395
|
+
return {"steps": self.trace.steps, "events": self.trace.events, "output": self.trace.output,
|
|
396
|
+
"warnings": self.trace.warnings, "complete": self.trace.complete,
|
|
397
|
+
"stoppedReason": self.trace.stopped, "entryName": self.analysis.get("entry", {}).get("name", "Program"),
|
|
398
|
+
"functionCalls": self.trace.calls, "iterations": self.trace.iterations,
|
|
399
|
+
"finalVars": self.trace.snapshot(), "callStackSupported": False,
|
|
400
|
+
"interpreter": "compiled-safe-ast"}
|
|
401
|
+
|
|
402
|
+
def exec_block(self, nodes, scope):
|
|
403
|
+
for node in nodes:
|
|
404
|
+
self.exec_node(node, scope)
|
|
405
|
+
|
|
406
|
+
def exec_node(self, node, scope):
|
|
407
|
+
kind = node.get("type")
|
|
408
|
+
if kind == "function":
|
|
409
|
+
scope[node["name"]] = ("function", node)
|
|
410
|
+
return
|
|
411
|
+
if kind == "class":
|
|
412
|
+
return
|
|
413
|
+
if kind == "if":
|
|
414
|
+
value = self.eval(node.get("condition", "false"), scope)
|
|
415
|
+
self.trace.add(node["startLine"], "condition", f"Check {node.get('condition')}",
|
|
416
|
+
f"The condition is {self.trace.display(value)}.", node.get("header", ""))
|
|
417
|
+
branch = node.get("consequent") if value else node.get("alternate")
|
|
418
|
+
if branch:
|
|
419
|
+
self.exec_block(branch.get("children", []), scope)
|
|
420
|
+
return
|
|
421
|
+
if kind == "for":
|
|
422
|
+
self.exec_loop(node, scope)
|
|
423
|
+
return
|
|
424
|
+
if kind == "while":
|
|
425
|
+
guard = 0
|
|
426
|
+
while self.eval(node.get("condition", "false"), scope) and guard < 50:
|
|
427
|
+
guard += 1
|
|
428
|
+
self.trace.iterations += 1
|
|
429
|
+
self.trace.add(node["startLine"], "iteration", f"Loop pass {self.trace.iterations}",
|
|
430
|
+
"The condition is still true.", node.get("header", ""))
|
|
431
|
+
try:
|
|
432
|
+
self.exec_block(node.get("body", {}).get("children", []), scope)
|
|
433
|
+
except Continue:
|
|
434
|
+
continue
|
|
435
|
+
except Break:
|
|
436
|
+
break
|
|
437
|
+
return
|
|
438
|
+
if kind == "action":
|
|
439
|
+
self.exec_action(node, scope)
|
|
440
|
+
|
|
441
|
+
def exec_loop(self, node, scope):
|
|
442
|
+
header = node.get("loopHeader", "")
|
|
443
|
+
match = re.search(r"for\s*\(\s*(?:[A-Za-z_]\w*(?:\[\])?\s+)?([A-Za-z_]\w*)\s*:\s*([^)]+)\)", header)
|
|
444
|
+
if match:
|
|
445
|
+
target, iterable_text = match.group(1), match.group(2).strip()
|
|
446
|
+
iterable = self.eval(iterable_text, scope)
|
|
447
|
+
if isinstance(iterable, list):
|
|
448
|
+
for value in iterable:
|
|
449
|
+
self.trace.iterations += 1
|
|
450
|
+
scope[target] = value
|
|
451
|
+
self.trace.add(node["startLine"], "iteration", f"Loop pass {self.trace.iterations}",
|
|
452
|
+
f"{target} receives {self.trace.display(value)}.", header)
|
|
453
|
+
try:
|
|
454
|
+
self.exec_block(node.get("body", {}).get("children", []), scope)
|
|
455
|
+
except Continue:
|
|
456
|
+
continue
|
|
457
|
+
except Break:
|
|
458
|
+
break
|
|
459
|
+
return
|
|
460
|
+
# Classic C-style loop: find the condition and an update.
|
|
461
|
+
match = re.search(r"for\s*\((.*?);(.*?);(.*?)\)", header, re.S)
|
|
462
|
+
if match:
|
|
463
|
+
init, condition, update = match.groups()
|
|
464
|
+
name_match = re.search(r"(?:int|let|var|auto)?\s*([A-Za-z_]\w*)\s*=", init)
|
|
465
|
+
if name_match:
|
|
466
|
+
name = name_match.group(1)
|
|
467
|
+
start = self.eval(init.split("=", 1)[1], scope)
|
|
468
|
+
scope[name] = start
|
|
469
|
+
guard = 0
|
|
470
|
+
while self.eval(condition, scope) and guard < 100:
|
|
471
|
+
guard += 1
|
|
472
|
+
self.trace.iterations += 1
|
|
473
|
+
self.trace.add(node["startLine"], "iteration", f"Loop pass {self.trace.iterations}",
|
|
474
|
+
f"{name} is {self.trace.display(scope.get(name))}.", header)
|
|
475
|
+
try:
|
|
476
|
+
self.exec_block(node.get("body", {}).get("children", []), scope)
|
|
477
|
+
except Continue:
|
|
478
|
+
pass
|
|
479
|
+
except Break:
|
|
480
|
+
break
|
|
481
|
+
if "++" in update:
|
|
482
|
+
scope[name] = scope.get(name, 0) + 1
|
|
483
|
+
elif "--" in update:
|
|
484
|
+
scope[name] = scope.get(name, 0) - 1
|
|
485
|
+
else:
|
|
486
|
+
scope[name] = self.eval(update, scope)
|
|
487
|
+
|
|
488
|
+
def exec_action(self, node, scope):
|
|
489
|
+
action = node.get("action") or {}
|
|
490
|
+
subtype = action.get("subtype")
|
|
491
|
+
if subtype == "return":
|
|
492
|
+
value = self.eval(action.get("expressionText", ""), scope)
|
|
493
|
+
self.trace.add(node["startLine"], "return", "Return a value", f"Returns {self.trace.display(value)}.", node.get("text", ""))
|
|
494
|
+
raise Return(value)
|
|
495
|
+
if subtype == "break":
|
|
496
|
+
raise Break
|
|
497
|
+
if subtype == "continue":
|
|
498
|
+
raise Continue
|
|
499
|
+
if subtype in {"declaration", "assignment"}:
|
|
500
|
+
target = action.get("targetDisplay") or action.get("targetName")
|
|
501
|
+
expression = action.get("expressionText", "")
|
|
502
|
+
value = self.eval(expression, scope)
|
|
503
|
+
operator = action.get("operator", "=")
|
|
504
|
+
if operator in {"+=", "-=", "*=", "/="}:
|
|
505
|
+
old = scope.get(str(target), 0)
|
|
506
|
+
value = old + value if operator == "+=" else old - value if operator == "-=" else old * value if operator == "*=" else old / value
|
|
507
|
+
scope[str(target)] = value
|
|
508
|
+
self.trace.event("assignment", node["startLine"], target=target, expressionText=expression, value=value)
|
|
509
|
+
self.trace.add(node["startLine"], "assign", f"Set {target}", f"{target} becomes {self.trace.display(value)}.", node.get("text", ""))
|
|
510
|
+
return
|
|
511
|
+
if subtype == "print":
|
|
512
|
+
text = self.format_print(action.get("expressionText", ""), scope)
|
|
513
|
+
if not text.endswith("\n"):
|
|
514
|
+
text += "\n"
|
|
515
|
+
self.trace.output += text
|
|
516
|
+
self.trace.add(node["startLine"], "print", "Print output", f"Output: {text.rstrip()}", node.get("text", ""))
|
|
517
|
+
return
|
|
518
|
+
if subtype == "call":
|
|
519
|
+
self.eval(action.get("expressionText", ""), scope)
|
|
520
|
+
|
|
521
|
+
def format_print(self, text, scope):
|
|
522
|
+
if "System.out.print" in text or "printf" in text:
|
|
523
|
+
match = re.search(r"\((.*)\)", text, re.S)
|
|
524
|
+
args = self.split_args(match.group(1) if match else "")
|
|
525
|
+
if "printf" in text and args:
|
|
526
|
+
fmt = self.eval(args[0], scope)
|
|
527
|
+
values = [self.eval(arg, scope) for arg in args[1:]]
|
|
528
|
+
if isinstance(fmt, str):
|
|
529
|
+
result = fmt.replace("\\n", "\n").replace("%d", "{}").replace("%s", "{}")
|
|
530
|
+
try:
|
|
531
|
+
return result.format(*values)
|
|
532
|
+
except Exception:
|
|
533
|
+
return result
|
|
534
|
+
return " ".join(self.trace.display(self.eval(arg, scope)) for arg in args)
|
|
535
|
+
# C++ cout << value << endl
|
|
536
|
+
rest = text.split("cout", 1)[-1]
|
|
537
|
+
values = []
|
|
538
|
+
for part in rest.split("<<"):
|
|
539
|
+
part = part.strip()
|
|
540
|
+
if part and "endl" not in part:
|
|
541
|
+
values.append(self.trace.display(self.eval(part, scope)))
|
|
542
|
+
return " ".join(values)
|
|
543
|
+
|
|
544
|
+
def split_args(self, text):
|
|
545
|
+
parts, current, depth, quote = [], "", 0, None
|
|
546
|
+
for char in text:
|
|
547
|
+
if quote:
|
|
548
|
+
current += char
|
|
549
|
+
if char == quote:
|
|
550
|
+
quote = None
|
|
551
|
+
continue
|
|
552
|
+
if char in "\"'":
|
|
553
|
+
quote = char
|
|
554
|
+
current += char
|
|
555
|
+
elif char in "([{":
|
|
556
|
+
depth += 1
|
|
557
|
+
current += char
|
|
558
|
+
elif char in ")]}":
|
|
559
|
+
depth -= 1
|
|
560
|
+
current += char
|
|
561
|
+
elif char == "," and depth == 0:
|
|
562
|
+
parts.append(current.strip())
|
|
563
|
+
current = ""
|
|
564
|
+
else:
|
|
565
|
+
current += char
|
|
566
|
+
if current.strip():
|
|
567
|
+
parts.append(current.strip())
|
|
568
|
+
return parts
|
|
569
|
+
|
|
570
|
+
def eval(self, text, scope):
|
|
571
|
+
if not text or not text.strip():
|
|
572
|
+
return None
|
|
573
|
+
stripped = text.strip()
|
|
574
|
+
if stripped.startswith("{") and stripped.endswith("}"):
|
|
575
|
+
inner = stripped[1:-1].strip()
|
|
576
|
+
return [self.eval(part, scope) for part in self.split_args(inner)] if inner else []
|
|
577
|
+
try:
|
|
578
|
+
node = self.parse_expression(stripped)
|
|
579
|
+
return self.eval_node(node, scope) if node else 0
|
|
580
|
+
except Exception:
|
|
581
|
+
return 0
|
|
582
|
+
|
|
583
|
+
def parse_expression(self, text: str):
|
|
584
|
+
"""Wrap an expression so each grammar can parse it outside a statement."""
|
|
585
|
+
if self.analysis["languageId"] == "java":
|
|
586
|
+
wrapper = f"class __Prism {{ void __m() {{ Object __x = {text}; }} }}"
|
|
587
|
+
else:
|
|
588
|
+
wrapper = f"void __prism() {{ int __x = {text}; }}"
|
|
589
|
+
self.active_bytes = wrapper.encode("utf-8")
|
|
590
|
+
tree = self.parser.parse(self.active_bytes)
|
|
591
|
+
stack = [tree.root_node]
|
|
592
|
+
while stack:
|
|
593
|
+
node = stack.pop()
|
|
594
|
+
if node.type in {"variable_declarator", "init_declarator"}:
|
|
595
|
+
value = node.child_by_field_name("value")
|
|
596
|
+
if value is not None:
|
|
597
|
+
return value
|
|
598
|
+
named = node.named_children
|
|
599
|
+
if len(named) >= 2:
|
|
600
|
+
return named[-1]
|
|
601
|
+
stack.extend(reversed(node.named_children))
|
|
602
|
+
return None
|
|
603
|
+
|
|
604
|
+
def eval_node(self, node, scope):
|
|
605
|
+
if node is None:
|
|
606
|
+
return None
|
|
607
|
+
kind = node.type
|
|
608
|
+
if kind in {"program", "translation_unit", "expression_statement", "parenthesized_expression"}:
|
|
609
|
+
return self.eval_node(node.named_children[0], scope) if node.named_children else None
|
|
610
|
+
if kind in {"decimal_integer_literal", "number_literal", "integer_literal"}:
|
|
611
|
+
value = self.text(node).replace("L", "")
|
|
612
|
+
return float(value) if "." in value else int(value)
|
|
613
|
+
if kind in {"string_literal", "string"}:
|
|
614
|
+
return self.text(node).strip('"')
|
|
615
|
+
if kind in {"character_literal"}:
|
|
616
|
+
return self.text(node).strip("'")
|
|
617
|
+
if kind in {"true", "false"}:
|
|
618
|
+
return kind == "true"
|
|
619
|
+
if kind == "null":
|
|
620
|
+
return None
|
|
621
|
+
if kind in {"identifier", "field_identifier"}:
|
|
622
|
+
value = scope.get(self.text(node))
|
|
623
|
+
return value if value is not None else 0
|
|
624
|
+
if kind in {"array_initializer", "initializer_list"}:
|
|
625
|
+
return [self.eval_node(child, scope) for child in node.named_children]
|
|
626
|
+
if kind == "binary_expression":
|
|
627
|
+
left_node = self.field(node, "left")
|
|
628
|
+
right_node = self.field(node, "right")
|
|
629
|
+
left = self.eval_node(left_node, scope)
|
|
630
|
+
right = self.eval_node(right_node, scope)
|
|
631
|
+
op = self.text(node.child_by_field_name("operator")) if node.child_by_field_name("operator") else ""
|
|
632
|
+
return {
|
|
633
|
+
"+": lambda: left + right, "-": lambda: left - right,
|
|
634
|
+
"*": lambda: left * right, "/": lambda: left / right,
|
|
635
|
+
"%": lambda: left % right, ">": lambda: left > right,
|
|
636
|
+
"<": lambda: left < right, ">=": lambda: left >= right,
|
|
637
|
+
"<=": lambda: left <= right, "==": lambda: left == right,
|
|
638
|
+
"!=": lambda: left != right, "&&": lambda: bool(left) and bool(right),
|
|
639
|
+
"||": lambda: bool(left) or bool(right),
|
|
640
|
+
}.get(op, lambda: 0)()
|
|
641
|
+
if kind == "unary_expression":
|
|
642
|
+
operand = self.field(node, "argument")
|
|
643
|
+
value = self.eval_node(operand, scope)
|
|
644
|
+
op_node = self.field(node, "operator")
|
|
645
|
+
op = self.text(op_node) if op_node else self.text(node)[0]
|
|
646
|
+
return -value if op == "-" else (not bool(value) if op == "!" else value)
|
|
647
|
+
if kind == "update_expression":
|
|
648
|
+
return self.eval_node(node.named_children[0], scope) if node.named_children else 0
|
|
649
|
+
if kind == "subscript_expression":
|
|
650
|
+
array = self.eval_node(self.field(node, "argument") or node.named_children[0], scope)
|
|
651
|
+
index = self.eval_node(self.field(node, "index") or node.named_children[-1], scope)
|
|
652
|
+
try:
|
|
653
|
+
return array[index]
|
|
654
|
+
except Exception:
|
|
655
|
+
return 0
|
|
656
|
+
if kind in {"method_invocation", "call_expression"}:
|
|
657
|
+
name_node = self.field(node, "name") or self.field(node, "function")
|
|
658
|
+
name = self.text(name_node) if name_node else ""
|
|
659
|
+
args_node = self.field(node, "arguments")
|
|
660
|
+
args = [self.eval_node(child, scope) for child in args_node.named_children] if args_node else []
|
|
661
|
+
if name in self.functions:
|
|
662
|
+
item = self.functions[name]
|
|
663
|
+
return self.call_function(item, args, scope)
|
|
664
|
+
return 0
|
|
665
|
+
return 0
|
|
666
|
+
|
|
667
|
+
def call_function(self, item, args, scope):
|
|
668
|
+
local = {param["name"]: value for param, value in zip(item["params"], args)}
|
|
669
|
+
self.trace.scopes.append(local)
|
|
670
|
+
self.trace.calls += 1
|
|
671
|
+
self.trace.add(item["startLine"], "call", f"Call {item['name']}()", "Enters the function.")
|
|
672
|
+
try:
|
|
673
|
+
self.exec_block(item["body"]["children"], local)
|
|
674
|
+
except Return as result:
|
|
675
|
+
return result.value
|
|
676
|
+
finally:
|
|
677
|
+
self.trace.scopes.pop()
|
|
678
|
+
return 0
|
|
679
|
+
|
|
680
|
+
|
|
681
|
+
def _metrics(source: str, factory: Factory) -> dict[str, int]:
|
|
682
|
+
lines = source.split("\n")
|
|
683
|
+
code = sum(1 for line in lines if line.strip() and not line.strip().startswith("//"))
|
|
684
|
+
comments = sum(1 for line in lines if line.strip().startswith("//"))
|
|
685
|
+
blank = sum(1 for line in lines if not line.strip())
|
|
686
|
+
return {
|
|
687
|
+
"totalLines": len(lines), "codeLines": code, "blankLines": blank,
|
|
688
|
+
"commentLines": comments, "characters": len(source),
|
|
689
|
+
"functions": len(factory.functions), "classes": len(factory.classes),
|
|
690
|
+
"loops": factory.counts["loops"], "conditions": factory.counts["conditions"],
|
|
691
|
+
"returns": factory.counts["returns"], "assignments": len(factory.assignments),
|
|
692
|
+
"maxDepth": factory.counts["maxDepth"],
|
|
693
|
+
}
|
|
694
|
+
|
|
695
|
+
|
|
696
|
+
def analyze_compiled(source: str, language: str = "java") -> dict[str, Any]:
|
|
697
|
+
text = str(source or "").replace("\r\n", "\n").replace("\r", "\n")
|
|
698
|
+
factory = Factory(text, language)
|
|
699
|
+
tree = factory.parser.parse(text.encode("utf-8"))
|
|
700
|
+
root = {
|
|
701
|
+
"type": "program", "id": factory.nid(), "startLine": 1,
|
|
702
|
+
"endLine": len(text.split("\n")), "header": "Program",
|
|
703
|
+
"body": factory.block(tree.root_node, 0),
|
|
704
|
+
"language": LANGUAGES[language]["name"], "parseMode": "braces",
|
|
705
|
+
"diagnostics": [],
|
|
706
|
+
}
|
|
707
|
+
metrics = _metrics(text, factory)
|
|
708
|
+
main = next((fn for fn in factory.functions if fn["name"] in {"main", "Main"}), None)
|
|
709
|
+
entry = {"kind": "function", "node": main, "name": main["name"] if main else "main", "inferred": False} if main else {
|
|
710
|
+
"kind": "program", "node": root, "name": "Program", "inferred": False
|
|
711
|
+
}
|
|
712
|
+
analysis = {
|
|
713
|
+
"source": text, "language": LANGUAGES[language], "languageId": language,
|
|
714
|
+
"root": root, "diagnostics": [], "lineCount": len(text.split("\n")),
|
|
715
|
+
"lines": [{"number": i, "text": line} for i, line in enumerate(text.split("\n"), 1)],
|
|
716
|
+
"highlightedLines": [line for line in text.split("\n")],
|
|
717
|
+
"functions": factory.functions, "classes": factory.classes,
|
|
718
|
+
"assignments": factory.assignments, "actionNodes": factory.actions,
|
|
719
|
+
"metrics": metrics, "entry": entry,
|
|
720
|
+
"flowFocus": {"kind": entry["kind"], "node": entry["node"], "name": entry["name"]},
|
|
721
|
+
"parseDiagnostics": [], "confidence": "medium",
|
|
722
|
+
"projectTitle": f"{LANGUAGES[language]['name']} program",
|
|
723
|
+
"featureSummary": f"{LANGUAGES[language]['name']} · {metrics['loops']} loops · {metrics['functions']} functions",
|
|
724
|
+
}
|
|
725
|
+
trace = Runner(analysis, text).run()
|
|
726
|
+
guide = _guide(analysis, trace, LANGUAGES[language]["name"])
|
|
727
|
+
return {"analysis": analysis, "trace": trace, "guide": guide}
|