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.
python_app/analysis.py ADDED
@@ -0,0 +1,953 @@
1
+ """Python-native analysis path for Prism.
2
+
3
+ The parser, structural model, explanation and bounded trace for Python now live
4
+ in Python. The JS engine remains available for the other supported languages
5
+ while they are migrated in later phases.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import ast
11
+ import html
12
+ import re
13
+ import operator
14
+ import symtable
15
+ from dataclasses import dataclass, field
16
+ from typing import Any
17
+
18
+ LANGUAGE = {
19
+ "id": "python", "name": "Python", "short": "PY", "monogram": "Py",
20
+ "extension": "py", "family": "python", "entry": "script",
21
+ "tagline": "Readable by design",
22
+ "blurb": "Indentation, lists, and beginner-friendly syntax.",
23
+ "tint": "#DCEAF7", "tintInk": "#275676", "wash": "#EFF6FB",
24
+ "hoverWash": "#E4F0F9", "lineComment": "#", "blockComment": None,
25
+ "keywords": [
26
+ "def", "return", "if", "elif", "else", "for", "while", "in", "not",
27
+ "and", "or", "is", "None", "True", "False", "class", "import", "from",
28
+ "as", "try", "except", "finally", "raise", "with", "yield", "lambda",
29
+ "pass", "break", "continue", "global", "nonlocal", "async", "await",
30
+ "del", "assert", "self",
31
+ ],
32
+ "literals": ["True", "False", "None"],
33
+ "capabilities": ["functions", "loops", "conditionals", "lists"],
34
+ "interpreter": "full",
35
+ }
36
+
37
+
38
+ class _NodeFactory:
39
+ def __init__(self, source: str):
40
+ self.source = source
41
+ self.lines = source.split("\n")
42
+ self.next_id = 1
43
+ self.assignments: list[dict[str, Any]] = []
44
+ self.action_nodes: list[dict[str, Any]] = []
45
+ self.functions: list[dict[str, Any]] = []
46
+ self.classes: list[dict[str, Any]] = []
47
+ self.function_names: set[str] = set()
48
+ self.assigned_names: set[str] = set()
49
+ self.counts = {"loops": 0, "conditions": 0, "returns": 0, "maxDepth": 0}
50
+
51
+ def nid(self) -> str:
52
+ self.next_id += 1
53
+ return f"node-{self.next_id}"
54
+
55
+ def line(self, node: ast.AST) -> int:
56
+ return int(getattr(node, "lineno", 1) or 1)
57
+
58
+ def end_line(self, node: ast.AST) -> int:
59
+ return int(getattr(node, "end_lineno", self.line(node)) or self.line(node))
60
+
61
+ def text(self, node: ast.AST) -> str:
62
+ try:
63
+ return ast.unparse(node)
64
+ except Exception:
65
+ return self.lines[self.line(node) - 1].strip() if self.line(node) <= len(self.lines) else ""
66
+
67
+ def block(self, statements: list[ast.stmt], depth: int = 0, start: int | None = None) -> dict[str, Any]:
68
+ children = [self.convert(statement, depth + 1) for statement in statements]
69
+ first = start or (children[0]["startLine"] if children else 1)
70
+ last = children[-1]["endLine"] if children else first
71
+ return {"type": "block", "startLine": first, "endLine": last, "children": children}
72
+
73
+ def action(self, statement: ast.stmt, subtype: str, **extra: Any) -> dict[str, Any]:
74
+ line = self.line(statement)
75
+ text = self.lines[line - 1].strip() if line <= len(self.lines) else self.text(statement)
76
+ action: dict[str, Any] = {
77
+ "subtype": subtype, "raw": text, "line": line,
78
+ "expressionText": self.text(statement), **extra,
79
+ }
80
+ return {
81
+ "type": "action", "id": self.nid(), "startLine": line,
82
+ "endLine": self.end_line(statement), "header": text, "text": text,
83
+ "action": action,
84
+ }
85
+
86
+ def record_assignment(self, node: dict[str, Any], target: str, expression: str,
87
+ dependencies: list[str], operator: str, is_declaration: bool,
88
+ scope: str = "Global") -> dict[str, Any]:
89
+ action = node["action"]
90
+ action.update({
91
+ "subtype": "declaration" if is_declaration else "assignment",
92
+ "assignment": True, "targetDisplay": target, "targetName": target,
93
+ "targetChain": target, "isDeclaration": is_declaration,
94
+ "isUpdate": not is_declaration or operator != "=",
95
+ "declarationType": "", "operator": operator,
96
+ "expressionText": expression, "expressionAST": None,
97
+ })
98
+ record = {
99
+ "id": f"assignment-{len(self.assignments) + 1}", "nodeId": node["id"],
100
+ "line": node["startLine"], "endLine": node["endLine"],
101
+ "target": target, "targetName": target, "expressionText": expression,
102
+ "dependencies": dependencies, "operator": operator,
103
+ "isDeclaration": is_declaration, "declarationType": "",
104
+ "scope": scope, "action": action,
105
+ }
106
+ self.assignments.append(record)
107
+ node["assignmentRecord"] = record
108
+ return record
109
+
110
+ def convert(self, node: ast.stmt, depth: int = 0) -> dict[str, Any]:
111
+ self.counts["maxDepth"] = max(self.counts["maxDepth"], depth)
112
+ line = self.line(node)
113
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
114
+ return self.convert_function(node, depth)
115
+ if isinstance(node, ast.ClassDef):
116
+ body = self.block(node.body, depth)
117
+ item = {
118
+ "type": "class", "id": self.nid(), "startLine": line,
119
+ "endLine": self.end_line(node), "header": f"class {node.name}",
120
+ "name": node.name, "body": body, "keyword": "class",
121
+ }
122
+ self.classes.append(item)
123
+ return item
124
+ if isinstance(node, ast.If):
125
+ self.counts["conditions"] += 1
126
+ consequent = self.block(node.body, depth, line)
127
+ alternate = self.block(node.orelse, depth) if node.orelse else None
128
+ return {
129
+ "type": "if", "id": self.nid(), "startLine": line,
130
+ "endLine": self.end_line(node),
131
+ "header": f"if {self.text(node.test)}",
132
+ "condition": self.text(node.test),
133
+ "consequent": consequent, "alternate": alternate,
134
+ "hasElse": bool(node.orelse), "keyword": "if",
135
+ }
136
+ if isinstance(node, (ast.For, ast.AsyncFor)):
137
+ self.counts["loops"] += 1
138
+ body = self.block(node.body, depth, line)
139
+ return {
140
+ "type": "for", "id": self.nid(), "startLine": line,
141
+ "endLine": self.end_line(node),
142
+ "header": f"for {self.text(node.target)} in {self.text(node.iter)}",
143
+ "loopHeader": f"{self.text(node.target)} in {self.text(node.iter)}",
144
+ "body": body, "keyword": "for",
145
+ "alternate": self.block(node.orelse, depth) if node.orelse else None,
146
+ "loopMeta": {"style": "for"},
147
+ }
148
+ if isinstance(node, ast.While):
149
+ self.counts["loops"] += 1
150
+ body = self.block(node.body, depth, line)
151
+ return {
152
+ "type": "while", "id": self.nid(), "startLine": line,
153
+ "endLine": self.end_line(node),
154
+ "header": f"while {self.text(node.test)}",
155
+ "condition": self.text(node.test), "body": body, "keyword": "while",
156
+ "alternate": self.block(node.orelse, depth) if node.orelse else None,
157
+ }
158
+ if isinstance(node, ast.Assign):
159
+ if len(node.targets) != 1:
160
+ return self.action(node, "unsupported")
161
+ target = self.text(node.targets[0]) if node.targets else "value"
162
+ expression = self.text(node.value)
163
+ first = target not in self.assigned_names and isinstance(node.targets[0], ast.Name)
164
+ self.assigned_names.add(target)
165
+ action_node = self.action(node, "declaration" if first else "assignment",
166
+ expressionText=expression)
167
+ deps = sorted({n.id for n in ast.walk(node.value) if isinstance(n, ast.Name)})
168
+ self.record_assignment(action_node, target, expression, deps, "=", first)
169
+ self.action_nodes.append(action_node)
170
+ return action_node
171
+ if isinstance(node, ast.AnnAssign):
172
+ target = self.text(node.target)
173
+ expression = self.text(node.value) if node.value is not None else ""
174
+ first = target not in self.assigned_names
175
+ self.assigned_names.add(target)
176
+ action_node = self.action(node, "declaration", expressionText=expression)
177
+ deps = sorted({n.id for n in ast.walk(node.value) if isinstance(n, ast.Name)}) if node.value else []
178
+ self.record_assignment(action_node, target, expression, deps, "=", first)
179
+ self.action_nodes.append(action_node)
180
+ return action_node
181
+ if isinstance(node, ast.AugAssign):
182
+ target = self.text(node.target)
183
+ right = self.text(node.value)
184
+ operator = self.op(node.op)
185
+ expression = f"{target} {operator} {right}"
186
+ action_node = self.action(node, "assignment", operator=operator,
187
+ expressionText=expression, rhs=right)
188
+ deps = sorted({target, *{n.id for n in ast.walk(node.value) if isinstance(n, ast.Name)}})
189
+ self.record_assignment(action_node, target, expression, deps, operator, False)
190
+ self.action_nodes.append(action_node)
191
+ return action_node
192
+ if isinstance(node, ast.Return):
193
+ self.counts["returns"] += 1
194
+ return self.action(node, "return", expressionText=self.text(node.value) if node.value else "")
195
+ if isinstance(node, ast.Break):
196
+ return self.action(node, "break")
197
+ if isinstance(node, ast.Continue):
198
+ return self.action(node, "continue")
199
+ if isinstance(node, ast.Pass):
200
+ return self.action(node, "pass")
201
+ if isinstance(node, (ast.Import, ast.ImportFrom)):
202
+ return self.action(node, "import")
203
+ if isinstance(node, (ast.Expr, ast.Raise, ast.Assert)):
204
+ value = getattr(node, "value", None)
205
+ is_print = isinstance(value, ast.Call) and isinstance(value.func, ast.Name) and value.func.id == "print"
206
+ is_call = isinstance(value, ast.Call)
207
+ subtype = "print" if is_print else "call" if is_call else "expression"
208
+ extra: dict[str, Any] = {}
209
+ if is_print:
210
+ extra = {"printKind": "python", "expressionText": self.text(value)}
211
+ elif is_call:
212
+ extra = {"expressionText": self.text(value), "calleeName": self.text(value.func)}
213
+ action_node = self.action(node, subtype, **extra)
214
+ self.action_nodes.append(action_node)
215
+ return action_node
216
+ # Fallback for try/with/other structures: keep a readable structural leaf.
217
+ return {
218
+ "type": "action", "id": self.nid(), "startLine": line,
219
+ "endLine": self.end_line(node),
220
+ "header": self.text(node), "text": self.text(node),
221
+ "action": {"subtype": "unsupported", "raw": self.text(node), "line": line,
222
+ "expressionText": self.text(node)},
223
+ }
224
+
225
+ def convert_function(self, node: ast.FunctionDef | ast.AsyncFunctionDef, depth: int) -> dict[str, Any]:
226
+ body = self.block(node.body, depth, self.line(node) + 1)
227
+ params = []
228
+ for arg in node.args.posonlyargs + node.args.args:
229
+ params.append({"name": arg.arg, "type": "", "defaultValue": None, "raw": arg.arg})
230
+ if node.args.vararg or node.args.kwarg or node.args.kwonlyargs or node.decorator_list:
231
+ unsupported_signature = True
232
+ else:
233
+ unsupported_signature = False
234
+ for arg in node.args.kwonlyargs:
235
+ params.append({"name": arg.arg, "type": "", "defaultValue": None, "raw": arg.arg})
236
+ item = {
237
+ "type": "function", "id": self.nid(), "startLine": self.line(node),
238
+ "endLine": self.end_line(node),
239
+ "header": f"def {node.name}({', '.join(p['name'] for p in params)})",
240
+ "name": node.name, "params": params, "returnType": "",
241
+ "body": body, "keyword": "def", "scopeName": node.name,
242
+ "defaults": [self.text(value) for value in node.args.defaults],
243
+ "unsupportedSignature": unsupported_signature,
244
+ }
245
+ item["actionCount"] = len([n for n in ast.walk(node) if isinstance(n, (ast.Assign, ast.AugAssign, ast.Expr))])
246
+ self.functions.append(item)
247
+ self.function_names.add(node.name)
248
+ return item
249
+
250
+ @staticmethod
251
+ def op(node: ast.operator) -> str:
252
+ return {
253
+ ast.Add: "+=", ast.Sub: "-=", ast.Mult: "*=", ast.Div: "/=",
254
+ }.get(type(node), "=")
255
+
256
+
257
+ @dataclass
258
+ class TraceState:
259
+ steps: list[dict[str, Any]] = field(default_factory=list)
260
+ events: list[dict[str, Any]] = field(default_factory=list)
261
+ output: str = ""
262
+ warnings: list[str] = field(default_factory=list)
263
+ complete: bool = False
264
+ stopped_reason: str | None = None
265
+ function_calls: int = 0
266
+ iterations: int = 0
267
+ scopes: list[dict[str, Any]] = field(default_factory=list)
268
+ call_stack: list[str] = field(default_factory=list)
269
+ max_steps: int = 420
270
+ lines: list[str] = field(default_factory=list)
271
+
272
+ def add_step(self, line: int, kind: str, title: str, detail: str,
273
+ code: str = "", extra: Any = None, scope: str = "Global") -> int:
274
+ if len(self.steps) >= self.max_steps:
275
+ if not self.warnings:
276
+ self.warnings.append(f"The trace reached its {self.max_steps}-step limit.")
277
+ raise StopIteration
278
+ index = len(self.steps)
279
+ previous = self.steps[-1]["output"] if self.steps else ""
280
+ self.steps.append({
281
+ "index": index, "line": line, "endLine": line, "kind": kind,
282
+ "title": title, "detail": detail,
283
+ "vars": self.snapshot(scope), "output": self.output,
284
+ "outputDelta": self.output[len(previous):], "callStack": list(self.call_stack),
285
+ "scope": scope, "code": code, "extra": extra,
286
+ })
287
+ return index
288
+
289
+ def snapshot(self, scope: str) -> list[dict[str, Any]]:
290
+ found: dict[str, dict[str, Any]] = {}
291
+ for frame in reversed(self.scopes):
292
+ for name, value in frame.items():
293
+ if name in found:
294
+ continue
295
+ found[name] = {
296
+ "name": name, "display": display(value),
297
+ "type": value_type(value), "scope": scope, "changed": False,
298
+ }
299
+ return list(found.values())[:20]
300
+
301
+ def event(self, kind: str, line: int, **data: Any) -> None:
302
+ self.events.append({
303
+ "kind": kind, "line": line, "target": data.get("target"),
304
+ "name": data.get("name"), "expressionText": data.get("expressionText"),
305
+ "operator": data.get("operator"), "value": display(data.get("value")),
306
+ "valueType": value_type(data.get("value")),
307
+ "scope": data.get("scope", "Global"),
308
+ "dependencies": data.get("dependencies", []),
309
+ "stepIndex": len(self.steps) - 1 if self.steps else 0,
310
+ "index": len(self.events),
311
+ })
312
+
313
+
314
+ def display(value: Any) -> str:
315
+ if isinstance(value, bool):
316
+ return "True" if value else "False"
317
+ if value is None:
318
+ return "None"
319
+ if isinstance(value, str):
320
+ return value
321
+ if isinstance(value, list):
322
+ return "[" + ", ".join(display(v) for v in value) + "]"
323
+ if isinstance(value, dict):
324
+ return "{" + ", ".join(f"{display(k)}: {display(v)}" for k, v in value.items()) + "}"
325
+ return str(value)
326
+
327
+
328
+ def value_type(value: Any) -> str:
329
+ if isinstance(value, bool):
330
+ return "boolean"
331
+ if isinstance(value, (int, float)):
332
+ return "number"
333
+ if isinstance(value, str):
334
+ return "string"
335
+ if isinstance(value, list):
336
+ return "array"
337
+ if isinstance(value, dict):
338
+ return "object"
339
+ if callable(value):
340
+ return "function"
341
+ return "unknown"
342
+
343
+
344
+ class _ReturnSignal(Exception):
345
+ def __init__(self, value: Any):
346
+ self.value = value
347
+
348
+
349
+ class _BreakSignal(Exception):
350
+ pass
351
+
352
+
353
+ class _ContinueSignal(Exception):
354
+ pass
355
+
356
+
357
+ class _PyRunner:
358
+ def __init__(self, root: dict[str, Any], source: str, analysis: dict[str, Any]):
359
+ self.root = root
360
+ self.trace = TraceState(lines=source.split("\n"))
361
+ self.functions: dict[str, dict[str, Any]] = {fn["name"]: fn for fn in analysis["functions"]}
362
+ self.global_scope: dict[str, Any] = {}
363
+ self.trace.scopes = [self.global_scope]
364
+ self.current_line = 1
365
+ self.last_top_level_return = None
366
+ self.function_locals = {}
367
+ self.local_name_stack: list[set[str]] = []
368
+ def collect(table):
369
+ for child in table.get_children():
370
+ if child.get_type() == "function":
371
+ self.function_locals[(child.get_name(), child.get_lineno())] = {
372
+ symbol.get_name() for symbol in child.get_symbols() if symbol.is_local()
373
+ }
374
+ collect(child)
375
+ collect(symtable.symtable(source, "<prism>", "exec"))
376
+
377
+ def run(self) -> dict[str, Any]:
378
+ t = self.trace
379
+ t.add_step(1, "start", "Program starts",
380
+ "This is a safe simulated run. Prism follows the code locally; your browser never executes it.",
381
+ code=t.lines[0].strip() if t.lines else "")
382
+ try:
383
+ self.exec_block(self.root["body"]["children"], self.global_scope, "Global")
384
+ t.add_step(len(t.lines), "end", "Program ends",
385
+ "The program finished. The final output is shown in the terminal.",
386
+ code="")
387
+ t.complete = True
388
+ except StopIteration:
389
+ t.stopped_reason = "step_limit"
390
+ t.warnings.append(f"The trace stopped at line {self.current_line}: step limit reached.")
391
+ except _ReturnSignal:
392
+ t.complete = True
393
+ except Exception as error: # pragma: no cover - defensive boundary
394
+ t.warnings.append(f"The trace stopped at line {self.current_line}: {error}")
395
+ t.stopped_reason = "error"
396
+ return {
397
+ "steps": t.steps, "events": t.events, "output": t.output,
398
+ "warnings": t.warnings, "complete": t.complete,
399
+ "stoppedReason": t.stopped_reason, "entryName": "Program",
400
+ "functionCalls": t.function_calls, "iterations": t.iterations,
401
+ "finalVars": t.snapshot("Global"), "callStackSupported": True,
402
+ "interpreter": "python-safe-ast",
403
+ "lastTopLevelReturn": self.last_top_level_return if t.complete else None,
404
+ "stoppedLine": self.current_line if not t.complete else None,
405
+ }
406
+
407
+ def exec_block(self, nodes: list[dict[str, Any]], scope: dict[str, Any], scope_name: str) -> None:
408
+ for node in nodes:
409
+ self.exec_node(node, scope, scope_name)
410
+
411
+ def exec_node(self, node: dict[str, Any], scope: dict[str, Any], scope_name: str) -> None:
412
+ kind = node.get("type")
413
+ self.current_line = node.get("startLine", 1)
414
+ if kind == "function":
415
+ if node.get("unsupportedSignature"):
416
+ raise ValueError("Unsupported function signature")
417
+ node = dict(node)
418
+ node["boundDefaults"] = [self.eval(value, scope) for value in node.get("defaults", [])]
419
+ scope[node["name"]] = ("function", node)
420
+ return
421
+ if kind == "class":
422
+ raise ValueError("Classes are not supported by the simulator")
423
+ if kind == "if":
424
+ value = self.eval(node["condition"], scope)
425
+ self.trace.event("condition", self.current_line, expressionText=node["condition"], value=value)
426
+ self.trace.add_step(self.current_line, "condition", f"Check {node['condition']}",
427
+ f"The condition evaluates to {display(value)}.",
428
+ code=node["header"], scope=scope_name, extra={"value": display(value)})
429
+ branch = node["consequent"] if value else node.get("alternate")
430
+ if branch:
431
+ self.exec_block(branch["children"], scope, scope_name)
432
+ return
433
+ if kind == "for":
434
+ iterable = self.eval(node.get("loopHeader", "").split(" in ", 1)[-1], scope)
435
+ if not isinstance(iterable, (list, tuple, range)):
436
+ raise ValueError("Loop value is not iterable in the supported subset")
437
+ target = node.get("loopHeader", "").split(" in ", 1)[0].strip()
438
+ if not target.isidentifier():
439
+ raise ValueError("Unsupported loop target")
440
+ for value in iterable:
441
+ self.trace.iterations += 1
442
+ scope[target] = value
443
+ self.trace.event("loop-target", self.current_line, target=target, name=target,
444
+ expressionText=self._iter_text(node), value=value, dependencies=[])
445
+ self.trace.add_step(self.current_line, "iteration", f"Loop pass {self.trace.iterations}",
446
+ f"`{target}` receives `{display(value)}`.",
447
+ code=node["header"], scope=scope_name)
448
+ try:
449
+ self.exec_block(node["body"]["children"], scope, scope_name)
450
+ except _ContinueSignal:
451
+ continue
452
+ except _BreakSignal:
453
+ break
454
+ else:
455
+ if node.get("alternate"):
456
+ self.exec_block(node["alternate"]["children"], scope, scope_name)
457
+ return
458
+ if kind == "while":
459
+ guard = 0
460
+ while self.eval(node.get("condition", "False"), scope):
461
+ if guard >= 60:
462
+ self.current_line = node["startLine"]
463
+ raise ValueError("while loop exceeded 60 iterations")
464
+ guard += 1
465
+ self.trace.iterations += 1
466
+ self.trace.add_step(self.current_line, "iteration", f"Loop pass {self.trace.iterations}",
467
+ f"`{node.get('condition')}` is still true.",
468
+ code=node["header"], scope=scope_name)
469
+ try:
470
+ self.exec_block(node["body"]["children"], scope, scope_name)
471
+ except _ContinueSignal:
472
+ continue
473
+ except _BreakSignal:
474
+ break
475
+ else:
476
+ if node.get("alternate"):
477
+ self.exec_block(node["alternate"]["children"], scope, scope_name)
478
+ return
479
+ if kind == "action":
480
+ self.exec_action(node, scope, scope_name)
481
+
482
+ def _iter_text(self, node: dict[str, Any]) -> str:
483
+ return node.get("loopHeader", "").split(" in ", 1)[-1]
484
+
485
+ def exec_action(self, node: dict[str, Any], scope: dict[str, Any], scope_name: str) -> None:
486
+ action = node.get("action") or {}
487
+ subtype = action.get("subtype")
488
+ text_line = node.get("text", "")
489
+ if subtype in {"return"}:
490
+ value = self.eval(action.get("expressionText", ""), scope)
491
+ self.trace.event("return", self.current_line, value=value)
492
+ self.trace.add_step(self.current_line, "return", "Return a value",
493
+ f"Returns `{display(value)}`.", code=text_line,
494
+ scope=scope_name, extra={"value": display(value)})
495
+ raise _ReturnSignal(value)
496
+ if subtype == "break":
497
+ raise _BreakSignal
498
+ if subtype == "continue":
499
+ raise _ContinueSignal
500
+ if subtype in {"declaration", "assignment"}:
501
+ target = action.get("targetDisplay") or action.get("targetName")
502
+ if not str(target).isidentifier():
503
+ raise ValueError("Unsupported assignment target")
504
+ expression = action.get("expressionText", "")
505
+ operator = action.get("operator", "=")
506
+ if operator != "=" and action.get("rhs"):
507
+ operators = {"+=": "+", "-=": "-", "*=": "*", "/=": "/"}
508
+ if operator not in operators:
509
+ raise ValueError("Unsupported augmented assignment")
510
+ current = self.eval(str(target), scope)
511
+ if isinstance(current, list) and operator in {"+=", "*="}:
512
+ right = self.eval(action['rhs'], scope)
513
+ if operator == "+=" and isinstance(right, (list, tuple, range)):
514
+ if len(current) + len(right) > 4096:
515
+ raise ValueError("Collection exceeds 4096 items")
516
+ current.extend(right)
517
+ elif operator == "*=" and isinstance(right, int):
518
+ if len(current) * max(right, 0) > 4096:
519
+ raise ValueError("Collection exceeds 4096 items")
520
+ current *= right
521
+ else:
522
+ raise ValueError("Unsupported list augmented assignment")
523
+ value = current
524
+ else:
525
+ value = self.eval(f"{target} {operators[operator]} ({action['rhs']})", scope)
526
+ else:
527
+ value = self.eval(expression, scope)
528
+ is_decl = bool(action.get("isDeclaration"))
529
+ scope[str(target)] = value
530
+ self.trace.event(
531
+ "assignment", self.current_line, target=target, name=target,
532
+ expressionText=expression, operator=action.get("operator", "="), value=value,
533
+ dependencies=action.get("dependencies", []), scope=scope_name,
534
+ )
535
+ self.trace.add_step(self.current_line, "assign", f"Set {target}",
536
+ f"The right side ({expression}) is evaluated and stored in {target}, which now holds {display(value)}.",
537
+ code=text_line, scope=scope_name,
538
+ extra={"target": target, "value": display(value)})
539
+ return
540
+ if subtype == "print":
541
+ call = ast.parse(action.get("expressionText", ""), mode="eval").body
542
+ args = [self._eval_node(arg, scope) for arg in call.args]
543
+ options = {kw.arg: self._eval_node(kw.value, scope) for kw in call.keywords}
544
+ if any(key not in {"sep", "end"} for key in options):
545
+ raise ValueError("Unsupported print option")
546
+ sep, end = options.get("sep"), options.get("end")
547
+ if sep is not None and not isinstance(sep, str) or end is not None and not isinstance(end, str):
548
+ raise ValueError("print sep and end must be strings or None")
549
+ text = (" " if sep is None else sep).join(str(arg) for arg in args)
550
+ addition = text + ("\n" if end is None else end)
551
+ if len(self.trace.output) + len(addition) > 60000:
552
+ raise ValueError("Output exceeds 60000 characters")
553
+ self.trace.output += addition
554
+ self.trace.event("print", self.current_line, value=text)
555
+ self.trace.add_step(self.current_line, "print", "Print output",
556
+ f"Appends `{text}` to the output.", code=text_line,
557
+ scope=scope_name, extra={"value": text})
558
+ return
559
+ if subtype == "call":
560
+ self.eval(action.get("expressionText", ""), scope)
561
+ return
562
+ if subtype in {"comment", "empty", "pass"}:
563
+ return
564
+ raise ValueError(f"Unsupported statement: {text_line}")
565
+
566
+ def _print_args(self, text: str, scope: dict[str, Any]) -> list[Any]:
567
+ try:
568
+ call = ast.parse(text, mode="eval").body
569
+ if isinstance(call, ast.Call):
570
+ return [self.eval(ast.unparse(arg), scope) for arg in call.args]
571
+ except Exception:
572
+ pass
573
+ return []
574
+
575
+ def eval(self, expression: str, scope: dict[str, Any]) -> Any:
576
+ if not expression:
577
+ return None
578
+ try:
579
+ tree = ast.parse(expression, mode="eval").body
580
+ except SyntaxError:
581
+ return None
582
+ return self._eval_node(tree, scope)
583
+
584
+ def _eval_node(self, node: ast.AST, scope: dict[str, Any]) -> Any:
585
+ value = self._eval_raw(node, scope)
586
+ if isinstance(value, int) and value.bit_length() > 4096:
587
+ raise ValueError("Integer exceeds 4096 bits")
588
+ if isinstance(value, str) and len(value) > 60000:
589
+ raise ValueError("String exceeds 60000 characters")
590
+ if isinstance(value, (list, tuple, dict)) and len(value) > 4096:
591
+ raise ValueError("Collection exceeds 4096 items")
592
+ return value
593
+
594
+ def _eval_raw(self, node: ast.AST, scope: dict[str, Any]) -> Any:
595
+ if isinstance(node, ast.Constant):
596
+ return node.value
597
+ if isinstance(node, ast.JoinedStr):
598
+ parts = []
599
+ size = 0
600
+ for part in node.values:
601
+ value = self._eval_node(part, scope)
602
+ if not isinstance(value, str):
603
+ raise ValueError("Invalid formatted string")
604
+ size += len(value)
605
+ if size > 60000:
606
+ raise ValueError("String exceeds 60000 characters")
607
+ parts.append(value)
608
+ return "".join(parts)
609
+ if isinstance(node, ast.FormattedValue):
610
+ value = self._eval_node(node.value, scope)
611
+ if not isinstance(value, (str, int, float, bool, type(None))):
612
+ raise ValueError("Formatting this value is not supported")
613
+ if node.conversion == 115:
614
+ value = str(value)
615
+ elif node.conversion == 114:
616
+ value = repr(value)
617
+ elif node.conversion == 97:
618
+ value = ascii(value)
619
+ elif node.conversion != -1:
620
+ raise ValueError("Unsupported string conversion")
621
+ spec = self._eval_node(node.format_spec, scope) if node.format_spec else ""
622
+ if len(spec) > 128 or any(int(n) > 60000 for n in re.findall(r"\d+", spec)):
623
+ raise ValueError("Format specifier exceeds safe limit")
624
+ return format(value, spec)
625
+ if isinstance(node, ast.Name):
626
+ if node.id in {"True", "False", "None"}:
627
+ return {"True": True, "False": False, "None": None}[node.id]
628
+ if node.id in scope:
629
+ return scope[node.id]
630
+ if scope is not self.global_scope and self.local_name_stack and node.id in self.local_name_stack[-1]:
631
+ raise UnboundLocalError(f"Local variable '{node.id}' referenced before assignment")
632
+ if node.id in self.global_scope:
633
+ return self.global_scope[node.id]
634
+ raise NameError(f"Name '{node.id}' is not defined")
635
+ if isinstance(node, ast.List):
636
+ if len(node.elts) > 4096:
637
+ raise ValueError("Collection exceeds 4096 items")
638
+ return [self._eval_node(v, scope) for v in node.elts]
639
+ if isinstance(node, ast.Tuple):
640
+ return tuple(self._eval_node(v, scope) for v in node.elts)
641
+ if isinstance(node, ast.Dict):
642
+ return {self._eval_node(k, scope): self._eval_node(v, scope) for k, v in zip(node.keys, node.values)}
643
+ if isinstance(node, ast.BinOp):
644
+ left = self._eval_node(node.left, scope)
645
+ right = self._eval_node(node.right, scope)
646
+ if isinstance(node.op, ast.Mult):
647
+ for seq, count in ((left, right), (right, left)):
648
+ if isinstance(seq, (str, list, tuple)) and isinstance(count, int):
649
+ limit = 60000 if isinstance(seq, str) else 4096
650
+ if len(seq) * max(count, 0) > limit:
651
+ raise ValueError("Repeated value exceeds safe limit")
652
+ if isinstance(node.op, ast.Add) and isinstance(left, (str, list, tuple)) and isinstance(right, type(left)):
653
+ if len(left) + len(right) > (60000 if isinstance(left, str) else 4096):
654
+ raise ValueError("Combined value exceeds safe limit")
655
+ if isinstance(node.op, ast.Add):
656
+ return left + right
657
+ if isinstance(node.op, ast.Sub):
658
+ return left - right
659
+ if isinstance(node.op, ast.Mult):
660
+ return left * right
661
+ if isinstance(node.op, ast.Div):
662
+ return left / right
663
+ if isinstance(node.op, ast.FloorDiv):
664
+ return left // right
665
+ if isinstance(node.op, ast.Mod):
666
+ return left % right
667
+ if isinstance(node.op, ast.Pow):
668
+ if isinstance(right, int) and abs(right) > 4096:
669
+ raise ValueError("Exponent exceeds safe limit")
670
+ if isinstance(left, int) and isinstance(right, int) and right > 0 and left.bit_length() * right > 8192:
671
+ raise ValueError("Power exceeds safe limit")
672
+ result = left ** right
673
+ if isinstance(result, int) and result.bit_length() > 4096:
674
+ raise ValueError("Integer exceeds 4096 bits")
675
+ return result
676
+ raise ValueError("Unsupported binary operator")
677
+ if isinstance(node, ast.UnaryOp):
678
+ value = self._eval_node(node.operand, scope)
679
+ if isinstance(node.op, ast.Not):
680
+ return not value
681
+ if isinstance(node.op, ast.USub):
682
+ return -value
683
+ if isinstance(node.op, ast.UAdd):
684
+ return +value
685
+ if isinstance(node.op, ast.Invert):
686
+ return ~value
687
+ raise ValueError("Unsupported unary operator")
688
+ if isinstance(node, ast.BoolOp):
689
+ result = self._eval_node(node.values[0], scope)
690
+ for value in node.values[1:]:
691
+ if bool(result) != isinstance(node.op, ast.And):
692
+ return result
693
+ result = self._eval_node(value, scope)
694
+ return result
695
+ if isinstance(node, ast.Compare):
696
+ left = self._eval_node(node.left, scope)
697
+ if len(node.ops) > 1:
698
+ for op, comparator in zip(node.ops, node.comparators):
699
+ right = self._eval_node(comparator, scope)
700
+ ops = {ast.Eq: operator.eq, ast.NotEq: operator.ne, ast.Lt: operator.lt, ast.LtE: operator.le, ast.Gt: operator.gt, ast.GtE: operator.ge, ast.In: lambda a, b: a in b, ast.NotIn: lambda a, b: a not in b}
701
+ if type(op) not in ops:
702
+ raise ValueError("Unsupported comparison")
703
+ if not ops[type(op)](left, right):
704
+ return False
705
+ left = right
706
+ return True
707
+ right = self._eval_node(node.comparators[0], scope)
708
+ kind = type(node.ops[0])
709
+ if kind is ast.Eq:
710
+ return left == right
711
+ if kind is ast.NotEq:
712
+ return left != right
713
+ if kind is ast.Lt:
714
+ return left < right
715
+ if kind is ast.LtE:
716
+ return left <= right
717
+ if kind is ast.Gt:
718
+ return left > right
719
+ if kind is ast.GtE:
720
+ return left >= right
721
+ if kind is ast.In:
722
+ return left in right
723
+ if kind is ast.NotIn:
724
+ return left not in right
725
+ raise ValueError("Unsupported comparison")
726
+ if isinstance(node, ast.IfExp):
727
+ return self._eval_node(node.body if self._eval_node(node.test, scope) else node.orelse, scope)
728
+ if isinstance(node, ast.Call):
729
+ if isinstance(node.func, ast.Name):
730
+ name = node.func.id
731
+ if name == "print":
732
+ return None
733
+ if name == "range":
734
+ values = [self._eval_node(arg, scope) for arg in node.args]
735
+ return range(*values)
736
+ if name == "len":
737
+ return len(self._eval_node(node.args[0], scope))
738
+ if name == "int":
739
+ return int(self._eval_node(node.args[0], scope))
740
+ if name == "float":
741
+ return float(self._eval_node(node.args[0], scope))
742
+ if name == "str":
743
+ return str(self._eval_node(node.args[0], scope))
744
+ if name in scope or name in self.global_scope:
745
+ binding = scope.get(name, self.global_scope.get(name))
746
+ if not isinstance(binding, tuple) or binding[0] != "function":
747
+ raise ValueError(f"{name} is not a supported function")
748
+ item = binding[1]
749
+ if len(self.trace.call_stack) >= 32:
750
+ raise ValueError("Call depth exceeds 32")
751
+ call_line = self.current_line
752
+ args = [self._eval_node(arg, scope) for arg in node.args]
753
+ if node.keywords:
754
+ raise ValueError("Keyword function arguments are not supported")
755
+ params = item["params"]
756
+ defaults = item.get("boundDefaults", [])
757
+ if len(args) > len(params) or len(args) < len(params) - len(defaults):
758
+ raise ValueError(f"Invalid arguments for {name}")
759
+ if len(args) < len(params):
760
+ args += defaults[len(args) - (len(params) - len(defaults)):]
761
+ self.trace.function_calls += 1
762
+ frame: dict[str, Any] = {param["name"]: value for param, value in zip(item["params"], args)}
763
+ self.trace.scopes.append(frame)
764
+ self.trace.call_stack.append(name)
765
+ self.local_name_stack.append(self.function_locals.get((item["name"], item["startLine"]), set()))
766
+ self.trace.add_step(node.lineno if hasattr(node, "lineno") else self.current_line,
767
+ "call", f"Call {name}()", f"Enters `{name}` with {len(args)} argument(s).",
768
+ scope=name)
769
+ is_top_level = len(self.trace.call_stack) == 1
770
+ result_value = None
771
+ try:
772
+ self.exec_block(item["body"]["children"], frame, name)
773
+ except _ReturnSignal as result:
774
+ result_value = result.value
775
+ finally:
776
+ self.trace.call_stack.pop()
777
+ self.trace.scopes.pop()
778
+ self.local_name_stack.pop()
779
+ if is_top_level:
780
+ self.last_top_level_return = {"name": name, "value": display(result_value), "line": call_line}
781
+ return result_value
782
+ raise ValueError("Unsupported function call")
783
+ if isinstance(node, ast.Subscript):
784
+ value = self._eval_node(node.value, scope)
785
+ index = self._eval_node(node.slice, scope)
786
+ try:
787
+ return value[index]
788
+ except Exception as error:
789
+ raise ValueError(f"Invalid subscript: {error}") from error
790
+ raise ValueError(f"Unsupported expression: {type(node).__name__}")
791
+
792
+
793
+ def _line_metrics(source: str, tree: ast.AST, functions: int, classes: int, assignments: int, counts: dict[str, int]) -> dict[str, int]:
794
+ lines = source.split("\n")
795
+ code = 0
796
+ blank = 0
797
+ comments = 0
798
+ for line in lines:
799
+ stripped = line.strip()
800
+ if not stripped:
801
+ blank += 1
802
+ elif stripped.startswith("#"):
803
+ comments += 1
804
+ else:
805
+ code += 1
806
+ return {
807
+ "totalLines": len(lines), "codeLines": code, "blankLines": blank,
808
+ "commentLines": comments, "characters": len(source),
809
+ "functions": functions, "classes": classes,
810
+ "loops": counts["loops"], "conditions": counts["conditions"],
811
+ "returns": counts["returns"], "assignments": assignments,
812
+ "maxDepth": counts["maxDepth"],
813
+ }
814
+
815
+
816
+ def _make_guide(analysis: dict[str, Any], trace: dict[str, Any]) -> dict[str, Any]:
817
+ functions = analysis["functions"]
818
+ metrics = analysis["metrics"]
819
+ output = trace["output"].strip()
820
+ output_display = f"{output} ⏎" if output else "No output"
821
+ if not trace["complete"]:
822
+ output_display = f"Partial output: {output_display} (simulation stopped)"
823
+ summary = f"This Python program "
824
+ if functions:
825
+ summary += f"defines {len(functions)} helper{'s' if len(functions) != 1 else ''}, "
826
+ if metrics["loops"]:
827
+ summary += f"uses {metrics['loops']} loop{'s' if metrics['loops'] != 1 else ''}, "
828
+ summary += f"and produces `{output_display}` in the safe sample run."
829
+ lines = analysis["lines"]
830
+ walkthrough = []
831
+ for fn in functions:
832
+ walkthrough.append({
833
+ "title": f"The reusable helper: {fn['name']}()",
834
+ "body": f"Defines `{fn['name']}` with {len(fn['params'])} input(s). The body runs only when the helper is called.",
835
+ "lines": [fn["startLine"]], "badge": "HELPER",
836
+ "points": [f"Parameter `{param['name']}`" for param in fn["params"]],
837
+ })
838
+ setup = [a for a in analysis["assignments"] if a["line"] <= (analysis.get("entry") or {}).get("node", {}).get("startLine", 1) + 4][:3]
839
+ if setup:
840
+ walkthrough.append({
841
+ "title": "The starting values are put in place",
842
+ "body": "Named values are created before the main work begins.",
843
+ "lines": [a["line"] for a in setup], "badge": "SETUP",
844
+ "points": [f"`{a['target']}` becomes `{a['expressionText']}`" for a in setup],
845
+ })
846
+ walkthrough.append({
847
+ "title": "The sample run",
848
+ "body": "Prism follows the program locally without executing arbitrary code.",
849
+ "lines": [trace["steps"][-2]["line"]] if len(trace["steps"]) > 1 else [1],
850
+ "badge": "TRACE",
851
+ "points": [f"{len(trace['steps'])} recorded steps", f"Output: `{output_display}`"],
852
+ })
853
+ line_notes = []
854
+ for number, item in enumerate(lines, start=1):
855
+ text = item.get("text", "") if isinstance(item, dict) else str(item)
856
+ stripped = text.strip()
857
+ if not stripped:
858
+ continue
859
+ tone = "statement"
860
+ if re.match(r"^(def |class )", stripped):
861
+ tone = "function"
862
+ elif re.match(r"^(if |elif |else\b|for |while )", stripped):
863
+ tone = "decision"
864
+ elif stripped.startswith("return"):
865
+ tone = "return"
866
+ elif stripped.startswith("print"):
867
+ tone = "output"
868
+ line_notes.append({
869
+ "line": number, "endLine": number, "code": stripped,
870
+ "note": f"Python executes this statement in sequence. Source text: `{stripped}`.",
871
+ "tone": tone, "synthetic": False,
872
+ })
873
+ concepts = []
874
+ if functions:
875
+ concepts.append({"term": "Function", "definition": "A reusable block of instructions with a name.", "inThisCode": f"`{functions[0]['name']}` packages reusable logic.", "line": functions[0]["startLine"]})
876
+ if metrics["loops"]:
877
+ concepts.append({"term": "Loop", "definition": "A loop repeats a block for each value or while a condition holds.", "inThisCode": "The sample trace shows each pass and the changed values.", "line": next((n["startLine"] for n in analysis["root"]["body"]["children"] if n["type"] == "for"), 1)})
878
+ concepts.append({"term": "Assignment", "definition": "Assignment stores a value under a name so later lines can reuse it.", "inThisCode": "The setup and accumulator updates create the program state.", "line": analysis["assignments"][0]["line"] if analysis["assignments"] else 1})
879
+ concepts.append({"term": "Print output", "definition": "Print sends text to the program's output stream.", "inThisCode": f"The sample output is `{output_display}`.", "line": max(1, len(lines))})
880
+ quiz = [
881
+ {"question": "What exact text did this run print?", "answer": f"`{output_display}`"},
882
+ {"question": "How many Python statements are in the program?", "answer": f"{len(line_notes)} statements, spread over {analysis['lineCount']} source lines."},
883
+ ]
884
+ if metrics["loops"]:
885
+ quiz.append({"question": "How many times did the loop run in the sample?", "answer": f"{trace['iterations']} passes were recorded."})
886
+ return {
887
+ "version": 1, "author": "local", "headline": "How this Python program works",
888
+ "sourceLineCount": analysis["lineCount"], "summary": summary,
889
+ "overview": {
890
+ "paragraphs": [
891
+ f"It runs from the top of the file to the bottom. The sample run produces `{output_display}`.",
892
+ "The key idea is to follow named values and control flow in order, then connect those values to the output.",
893
+ "Use **Line by line** for the close reading and the trace tab for the recorded values.",
894
+ ],
895
+ "mentalModel": {
896
+ "title": "A short sequence of named steps",
897
+ "body": "Imagine a notebook: each assignment writes a value into a named slot, branches choose which lines to read, and loops repeat a page. The output is the final note left on the page.",
898
+ },
899
+ "glance": [
900
+ {"label": "Language", "value": "Python", "hint": "Readable by design"},
901
+ {"label": "Entry point", "value": "Top-level code", "hint": "Runs from the first line"},
902
+ {"label": "Shape", "value": f"{metrics['functions']} function · {metrics['loops']} loop · {metrics['conditions']} decision", "hint": f"{analysis['lineCount']} lines in total"},
903
+ {"label": "Sample output", "value": output_display, "hint": "From the Python safe run", "mono": True},
904
+ ],
905
+ },
906
+ "walkthrough": walkthrough, "lineNotes": line_notes, "concepts": concepts,
907
+ "watchOuts": [
908
+ {"title": "Indentation is structure", "body": "In Python, indentation decides which lines belong to a block. Keep it consistent."},
909
+ {"title": "Assignments replace or update values", "body": "A later assignment to the same name replaces the previous value unless the expression uses the old value, as an accumulator does."},
910
+ ],
911
+ "quiz": quiz,
912
+ "traceNote": {"complete": trace["complete"], "output": trace["output"], "warnings": trace["warnings"], "stoppedReason": trace["stoppedReason"]},
913
+ "readingMinutes": max(2, min(9, round(len(lines) / 2) + 1)),
914
+ "wordCount": max(120, len(lines) * 55),
915
+ }
916
+
917
+
918
+ def analyze_python(source: str) -> dict[str, Any]:
919
+ text = str(source or "").replace("\r\n", "\n").replace("\r", "\n")
920
+ lines = text.split("\n")
921
+ try:
922
+ tree = ast.parse(text)
923
+ except SyntaxError as error:
924
+ raise ValueError(f"Python syntax error on line {error.lineno}: {error.msg}") from error
925
+ factory = _NodeFactory(text)
926
+ root = {
927
+ "type": "program", "startLine": 1, "endLine": len(lines),
928
+ "body": factory.block(tree.body), "header": "Program",
929
+ "language": "Python", "parseMode": "indentation", "diagnostics": [],
930
+ }
931
+ root["id"] = factory.nid()
932
+ for node in ast.walk(tree):
933
+ if isinstance(node, ast.Assign):
934
+ pass
935
+ metrics = _line_metrics(text, tree, len(factory.functions), len(factory.classes),
936
+ len(factory.assignments), factory.counts)
937
+ analysis = {
938
+ "source": text, "language": LANGUAGE, "languageId": "python", "root": root,
939
+ "diagnostics": [], "lineCount": len(lines), "lines": [
940
+ {"number": index, "text": line} for index, line in enumerate(lines, start=1)
941
+ ], "highlightedLines": [html.escape(line) if line else "" for line in lines],
942
+ "functions": factory.functions, "classes": factory.classes,
943
+ "assignments": factory.assignments, "actionNodes": factory.action_nodes,
944
+ "metrics": metrics,
945
+ "entry": {"kind": "program", "node": root, "name": "Program", "inferred": False},
946
+ "flowFocus": {"kind": "program", "node": root, "name": "Program"},
947
+ "parseDiagnostics": [], "confidence": "high",
948
+ "projectTitle": "Python program",
949
+ "featureSummary": f"Python · {metrics['loops']} loops · {metrics['functions']} functions",
950
+ }
951
+ trace = _PyRunner(root, text, analysis).run()
952
+ guide = _make_guide(analysis, trace)
953
+ return {"analysis": analysis, "trace": trace, "guide": guide}