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,709 @@
1
+ """Native Python analyst for JavaScript and TypeScript.
2
+
3
+ Uses tree-sitter grammars for parsing, then builds the same structural model
4
+ consumed by Prism's four native views. The trace is a deliberately bounded
5
+ evaluator for common beginner JavaScript, never an execution of the source.
6
+ """
7
+
8
+ from __future__ import annotations
9
+
10
+ import ast
11
+ import html
12
+ from dataclasses import dataclass, field
13
+ from typing import Any
14
+
15
+ from tree_sitter import Language, Parser
16
+
17
+ import tree_sitter_javascript as tsjs
18
+ import tree_sitter_typescript as tsts
19
+
20
+ MAX_STEPS = 420
21
+ PARSERS = {
22
+ "javascript": Language(tsjs.language()),
23
+ "typescript": Language(tsts.language_typescript()),
24
+ "tsx": Language(tsts.language_tsx()),
25
+ }
26
+
27
+ LANGUAGES = {
28
+ "javascript": {"id": "javascript", "name": "JavaScript", "extension": "js"},
29
+ "typescript": {"id": "typescript", "name": "TypeScript", "extension": "ts"},
30
+ }
31
+
32
+
33
+ def _parser(language: str) -> Parser:
34
+ return Parser(PARSERS.get(language, PARSERS["javascript"]))
35
+
36
+
37
+ class _Factory:
38
+ def __init__(self, source: str, language: str):
39
+ self.source = source
40
+ self.language = language
41
+ self.bytes = source.encode("utf-8")
42
+ self.lines = source.split("\n")
43
+ self.parser = _parser(language)
44
+ self.counter = 0
45
+ self.functions: list[dict[str, Any]] = []
46
+ self.classes: list[dict[str, Any]] = []
47
+ self.assignments: list[dict[str, Any]] = []
48
+ self.actions: list[dict[str, Any]] = []
49
+ self.counts = {"loops": 0, "conditions": 0, "returns": 0, "maxDepth": 0}
50
+
51
+ def nid(self) -> str:
52
+ self.counter += 1
53
+ return f"js-node-{self.counter}"
54
+
55
+ def text(self, node) -> str:
56
+ return self.bytes[node.start_byte:node.end_byte].decode("utf-8", "replace")
57
+
58
+ def line(self, node) -> int:
59
+ return node.start_point.row + 1
60
+
61
+ def end_line(self, node) -> int:
62
+ return node.end_point.row + 1
63
+
64
+ def field(self, node, name: str):
65
+ return node.child_by_field_name(name)
66
+
67
+ def block(self, node, depth: int) -> dict[str, Any]:
68
+ if node is None:
69
+ return {"type": "block", "startLine": 1, "endLine": 1, "children": []}
70
+ if node.type == "statement_block":
71
+ children = [self.convert(child, depth + 1) for child in node.named_children]
72
+ start = self.line(node)
73
+ else:
74
+ children = [self.convert(node, depth + 1)]
75
+ start = self.line(node)
76
+ end = self.end_line(node)
77
+ return {"type": "block", "startLine": start, "endLine": end,
78
+ "children": [child for child in children if child]}
79
+
80
+ def action(self, node, subtype: str, **extra: Any) -> dict[str, Any]:
81
+ raw = self.text(node).strip()
82
+ action = {"subtype": subtype, "raw": raw, "line": self.line(node),
83
+ "expressionText": raw, **extra}
84
+ return {"type": "action", "id": self.nid(), "startLine": self.line(node),
85
+ "endLine": self.end_line(node), "header": raw, "text": raw,
86
+ "action": action}
87
+
88
+ def record(self, node: dict[str, Any], target: str, expression: str,
89
+ dependencies: list[str], operator: str, declaration: bool) -> None:
90
+ node["action"].update({
91
+ "subtype": "declaration" if declaration else "assignment",
92
+ "assignment": True, "targetDisplay": target, "targetName": target,
93
+ "isDeclaration": declaration, "operator": operator,
94
+ "expressionText": expression, "dependencies": dependencies,
95
+ })
96
+ record = {
97
+ "id": f"assignment-{len(self.assignments) + 1}", "nodeId": node["id"],
98
+ "line": node["startLine"], "endLine": node["endLine"], "target": target,
99
+ "targetName": target, "expressionText": expression,
100
+ "dependencies": dependencies, "operator": operator,
101
+ "isDeclaration": declaration, "scope": "Global", "action": node["action"],
102
+ }
103
+ self.assignments.append(record)
104
+ node["assignmentRecord"] = record
105
+
106
+ def names_in(self, node) -> list[str]:
107
+ found = []
108
+ def walk(n):
109
+ if n.type in {"identifier", "shorthand_property_identifier"}:
110
+ name = self.text(n)
111
+ if name not in found:
112
+ found.append(name)
113
+ for child in n.named_children:
114
+ walk(child)
115
+ walk(node)
116
+ return found
117
+
118
+ def convert(self, node, depth: int = 0) -> dict[str, Any] | None:
119
+ self.counts["maxDepth"] = max(self.counts["maxDepth"], depth)
120
+ kind = node.type
121
+ if kind in {"comment", "hash_bang_line"}:
122
+ return None
123
+ if kind in {"lexical_declaration", "variable_declaration"}:
124
+ results = []
125
+ declaration_kind = self.text(node).split(maxsplit=1)[0] if self.text(node) else "let"
126
+ for declarator in [c for c in node.named_children if c.type == "variable_declarator"]:
127
+ name_node = self.field(declarator, "name")
128
+ value_node = self.field(declarator, "value")
129
+ target = self.text(name_node) if name_node else "value"
130
+ expression = self.text(value_node) if value_node else ""
131
+ action = self.action(node, "declaration" if declaration_kind == "const" else "assignment",
132
+ expressionText=expression)
133
+ self.record(action, target, expression, self.names_in(value_node) if value_node else [], "=", True)
134
+ self.actions.append(action)
135
+ results.append(action)
136
+ return results[0] if len(results) == 1 else {
137
+ "type": "block", "startLine": self.line(node), "endLine": self.end_line(node),
138
+ "children": results,
139
+ }
140
+ if kind == "function_declaration":
141
+ name_node = self.field(node, "name")
142
+ body = self.field(node, "body")
143
+ params_node = self.field(node, "parameters")
144
+ params = []
145
+ if params_node:
146
+ for param in params_node.named_children:
147
+ raw_param = self.text(param)
148
+ pattern = self.field(param, "pattern") or self.field(param, "name")
149
+ param_name = self.text(pattern) if pattern else raw_param.split(":", 1)[0].split("=", 1)[0].strip()
150
+ params.append({"name": param_name, "type": "", "defaultValue": None, "raw": raw_param})
151
+ item = {
152
+ "type": "function", "id": self.nid(), "startLine": self.line(node),
153
+ "endLine": self.end_line(node),
154
+ "header": self.text(node).split("{", 1)[0].strip(),
155
+ "name": self.text(name_node) if name_node else "function",
156
+ "params": params, "returnType": "", "body": self.block(body, depth),
157
+ "keyword": "function", "scopeName": self.text(name_node) if name_node else "function",
158
+ }
159
+ item["actionCount"] = len([n for n in self._all(body) if n.type in {"lexical_declaration", "expression_statement", "return_statement"}]) if body else 0
160
+ self.functions.append(item)
161
+ return item
162
+ if kind == "class_declaration":
163
+ name_node = self.field(node, "name")
164
+ body = self.field(node, "body")
165
+ item = {
166
+ "type": "class", "id": self.nid(), "startLine": self.line(node),
167
+ "endLine": self.end_line(node), "header": f"class {self.text(name_node) if name_node else 'Class'}",
168
+ "name": self.text(name_node) if name_node else "Class",
169
+ "body": {"type": "block", "startLine": self.line(node), "endLine": self.end_line(node), "children": []},
170
+ "keyword": "class",
171
+ }
172
+ self.classes.append(item)
173
+ return item
174
+ if kind == "if_statement":
175
+ self.counts["conditions"] += 1
176
+ condition = self.field(node, "condition")
177
+ consequence = self.field(node, "consequence")
178
+ alternative = self.field(node, "alternative")
179
+ return {
180
+ "type": "if", "id": self.nid(), "startLine": self.line(node),
181
+ "endLine": self.end_line(node), "header": self.text(node).split("{", 1)[0].strip(),
182
+ "condition": self.text(condition).strip("()") if condition else "condition",
183
+ "consequent": self.block(consequence, depth),
184
+ "alternate": self.block(alternative, depth) if alternative else None,
185
+ "hasElse": alternative is not None, "keyword": "if",
186
+ }
187
+ if kind in {"for_statement", "for_in_statement"}:
188
+ self.counts["loops"] += 1
189
+ body = self.field(node, "body")
190
+ return {
191
+ "type": "for", "id": self.nid(), "startLine": self.line(node),
192
+ "endLine": self.end_line(node), "header": self.text(node).split("{", 1)[0].strip(),
193
+ "loopHeader": self.text(node).split("{", 1)[0].strip(),
194
+ "body": self.block(body, depth), "keyword": "for",
195
+ "loopMeta": {"style": "for"},
196
+ }
197
+ if kind == "while_statement":
198
+ self.counts["loops"] += 1
199
+ condition = self.field(node, "condition")
200
+ body = self.field(node, "body")
201
+ return {
202
+ "type": "while", "id": self.nid(), "startLine": self.line(node),
203
+ "endLine": self.end_line(node), "header": self.text(node).split("{", 1)[0].strip(),
204
+ "condition": self.text(condition).strip("()") if condition else "true",
205
+ "body": self.block(body, depth), "keyword": "while",
206
+ }
207
+ if kind == "return_statement":
208
+ self.counts["returns"] += 1
209
+ expression = self.text(node).removeprefix("return").rstrip(";").strip()
210
+ return self.action(node, "return", expressionText=expression)
211
+ if kind == "break_statement":
212
+ return self.action(node, "break")
213
+ if kind == "continue_statement":
214
+ return self.action(node, "continue")
215
+ if kind == "expression_statement":
216
+ expression = node.named_children[0] if node.named_children else None
217
+ if expression is None:
218
+ return None
219
+ if expression.type in {"assignment_expression", "augmented_assignment_expression"}:
220
+ left = self.field(expression, "left")
221
+ right = self.field(expression, "right")
222
+ target = self.text(left) if left else "value"
223
+ value = self.text(right) if right else ""
224
+ operator = self.text(expression).split(target, 1)[1].split(value, 1)[0].strip() if right else "="
225
+ operator = operator or "="
226
+ action = self.action(node, "assignment", expressionText=value, operator=operator)
227
+ self.record(action, target, value, self.names_in(right) if right else [], operator, False)
228
+ self.actions.append(action)
229
+ return action
230
+ if expression.type == "call_expression":
231
+ function = self.field(expression, "function")
232
+ function_name = self.text(function) if function else ""
233
+ if function_name == "console.log":
234
+ action = self.action(node, "print", printKind="console",
235
+ expressionText=self.text(expression))
236
+ self.actions.append(action)
237
+ return action
238
+ action = self.action(node, "call", expressionText=self.text(expression), calleeName=function_name)
239
+ self.actions.append(action)
240
+ return action
241
+ if expression.type == "update_expression":
242
+ action = self.action(node, "update", expressionText=self.text(expression))
243
+ self.actions.append(action)
244
+ return action
245
+ return self.action(node, "expression", expressionText=self.text(expression))
246
+ # Unknown statement: retain it as an action so nothing silently disappears.
247
+ raw = self.text(node).strip()
248
+ if not raw:
249
+ return None
250
+ return self.action(node, "expression", expressionText=raw)
251
+
252
+ def _all(self, node):
253
+ yield node
254
+ for child in node.named_children:
255
+ yield from self._all(child)
256
+
257
+
258
+ def _metrics(source: str, factory: _Factory) -> dict[str, int]:
259
+ lines = source.split("\n")
260
+ code = sum(1 for line in lines if line.strip() and not line.strip().startswith("//"))
261
+ comments = sum(1 for line in lines if line.strip().startswith("//"))
262
+ blank = sum(1 for line in lines if not line.strip())
263
+ return {
264
+ "totalLines": len(lines), "codeLines": code, "blankLines": blank,
265
+ "commentLines": comments, "characters": len(source),
266
+ "functions": len(factory.functions), "classes": len(factory.classes),
267
+ "loops": factory.counts["loops"], "conditions": factory.counts["conditions"],
268
+ "returns": factory.counts["returns"], "assignments": len(factory.assignments),
269
+ "maxDepth": factory.counts["maxDepth"],
270
+ }
271
+
272
+
273
+ @dataclass
274
+ class _Trace:
275
+ steps: list[dict[str, Any]] = field(default_factory=list)
276
+ events: list[dict[str, Any]] = field(default_factory=list)
277
+ output: str = ""
278
+ warnings: list[str] = field(default_factory=list)
279
+ complete: bool = False
280
+ stopped_reason: str | None = None
281
+ function_calls: int = 0
282
+ iterations: int = 0
283
+ globals: dict[str, Any] = field(default_factory=dict)
284
+ scopes: list[dict[str, Any]] = field(default_factory=list)
285
+
286
+ def display(self, value: Any) -> str:
287
+ if isinstance(value, bool):
288
+ return "true" if value else "false"
289
+ if value is None:
290
+ return "null"
291
+ if isinstance(value, list):
292
+ return "[" + ", ".join(self.display(v) for v in value) + "]"
293
+ if isinstance(value, dict):
294
+ return "{" + ", ".join(f"{k}: {self.display(v)}" for k, v in value.items()) + "}"
295
+ return str(value)
296
+
297
+ def snapshot(self) -> list[dict[str, Any]]:
298
+ result = []
299
+ seen = set()
300
+ for scope in reversed(self.scopes + [self.globals]):
301
+ for name, value in scope.items():
302
+ if name in seen:
303
+ continue
304
+ seen.add(name)
305
+ result.append({"name": name, "display": self.display(value),
306
+ "type": "array" if isinstance(value, list) else "number" if isinstance(value, (int, float)) else "string"})
307
+ return result[:20]
308
+
309
+ def add(self, line: int, kind: str, title: str, detail: str, code: str = "", extra=None) -> None:
310
+ if len(self.steps) >= MAX_STEPS:
311
+ self.warnings.append(f"The trace reached its {MAX_STEPS}-step limit.")
312
+ raise StopIteration
313
+ self.steps.append({
314
+ "index": len(self.steps), "line": line, "endLine": line, "kind": kind,
315
+ "title": title, "detail": detail, "vars": self.snapshot(), "output": self.output,
316
+ "outputDelta": "", "callStack": [], "scope": "Global", "code": code, "extra": extra,
317
+ })
318
+
319
+ def event(self, kind: str, line: int, **data: Any) -> None:
320
+ self.events.append({
321
+ "kind": kind, "line": line, "target": data.get("target"),
322
+ "name": data.get("target"), "expressionText": data.get("expressionText"),
323
+ "operator": data.get("operator"), "value": self.display(data.get("value")),
324
+ "valueType": "array" if isinstance(data.get("value"), list) else "number",
325
+ "scope": "Global", "dependencies": data.get("dependencies", []),
326
+ "stepIndex": len(self.steps) - 1 if self.steps else 0, "index": len(self.events),
327
+ })
328
+
329
+
330
+ class _Return(Exception):
331
+ def __init__(self, value):
332
+ self.value = value
333
+
334
+
335
+ class _Break(Exception):
336
+ pass
337
+
338
+
339
+ class _Continue(Exception):
340
+ pass
341
+
342
+
343
+ class _Runner:
344
+ def __init__(self, analysis: dict[str, Any], source: str):
345
+ self.analysis = analysis
346
+ self.source = source
347
+ self.lines = source.split("\n")
348
+ self.parser = _parser(analysis["languageId"])
349
+ self.trace = _Trace()
350
+ self.functions = {item["name"]: item for item in analysis["functions"]}
351
+ self.trace.scopes = []
352
+
353
+ def run(self) -> dict[str, Any]:
354
+ self.trace.add(1, "start", "Program starts", "Prism follows the program locally; the source is not executed.")
355
+ try:
356
+ self.exec_block(self.analysis["root"]["body"]["children"], self.trace.globals)
357
+ self.trace.complete = True
358
+ self.trace.add(max(1, len(self.lines)), "end", "Program ends", "The simulated run finished.")
359
+ except StopIteration:
360
+ self.trace.stopped_reason = "step_limit"
361
+ except _Return:
362
+ self.trace.complete = True
363
+ except Exception as error: # pragma: no cover - defensive
364
+ self.trace.warnings.append(f"The trace stopped at line {getattr(error, 'line', '?')}: {error}")
365
+ self.trace.stopped_reason = "error"
366
+ return {
367
+ "steps": self.trace.steps, "events": self.trace.events, "output": self.trace.output,
368
+ "warnings": self.trace.warnings, "complete": self.trace.complete,
369
+ "stoppedReason": self.trace.stopped_reason, "entryName": "Program",
370
+ "functionCalls": self.trace.function_calls, "iterations": self.trace.iterations,
371
+ "finalVars": self.trace.snapshot(), "callStackSupported": False,
372
+ "interpreter": "js-tree-sitter-safe",
373
+ }
374
+
375
+ def exec_block(self, nodes, scope) -> None:
376
+ for node in nodes:
377
+ self.exec_node(node, scope)
378
+
379
+ def exec_node(self, node, scope) -> None:
380
+ kind = node.get("type")
381
+ if kind == "function":
382
+ scope[node["name"]] = ("function", node)
383
+ return
384
+ if kind == "class":
385
+ return
386
+ if kind == "if":
387
+ value = self.eval(node.get("condition", "false"), scope)
388
+ self.trace.add(node["startLine"], "condition", f"Check {node.get('condition')}",
389
+ f"The condition is `{self.trace.display(value)}`.", node.get("header", ""))
390
+ branch = node.get("consequent") if value else node.get("alternate")
391
+ if branch:
392
+ self.exec_block(branch.get("children", []), scope)
393
+ return
394
+ if kind == "for":
395
+ header = node.get("loopHeader", "")
396
+ match = __import__("re").search(r"for\s*\(\s*(?:const|let|var)?\s*(\w+)\s+of\s+(.+?)\)", header)
397
+ if match:
398
+ target, iterable_text = match.group(1), match.group(2).strip()
399
+ iterable = self.eval(iterable_text, scope)
400
+ if not isinstance(iterable, list):
401
+ self.trace.warnings.append(f"The loop on line {node['startLine']} could not be iterated safely.")
402
+ return
403
+ for value in iterable:
404
+ self.trace.iterations += 1
405
+ scope[target] = value
406
+ self.trace.event("loop-target", node["startLine"], target=target, value=value)
407
+ self.trace.add(node["startLine"], "iteration", f"Loop pass {self.trace.iterations}",
408
+ f"`{target}` receives `{self.trace.display(value)}`.", header)
409
+ try:
410
+ self.exec_block(node.get("body", {}).get("children", []), scope)
411
+ except _Continue:
412
+ continue
413
+ except _Break:
414
+ break
415
+ return
416
+ if kind == "while":
417
+ guard = 0
418
+ while self.eval(node.get("condition", "false"), scope) and guard < 60:
419
+ guard += 1
420
+ self.trace.iterations += 1
421
+ self.trace.add(node["startLine"], "iteration", f"Loop pass {self.trace.iterations}",
422
+ "The condition is still true.", node.get("header", ""))
423
+ try:
424
+ self.exec_block(node.get("body", {}).get("children", []), scope)
425
+ except _Continue:
426
+ continue
427
+ except _Break:
428
+ break
429
+ return
430
+ if kind == "action":
431
+ self.exec_action(node, scope)
432
+
433
+ def exec_action(self, node, scope) -> None:
434
+ action = node.get("action") or {}
435
+ subtype = action.get("subtype")
436
+ if subtype == "return":
437
+ value = self.eval(action.get("expressionText", ""), scope)
438
+ self.trace.add(node["startLine"], "return", "Return a value",
439
+ f"Returns `{self.trace.display(value)}`.", node.get("text", ""))
440
+ raise _Return(value)
441
+ if subtype == "break":
442
+ raise _Break
443
+ if subtype == "continue":
444
+ raise _Continue
445
+ if subtype in {"declaration", "assignment"}:
446
+ target = action.get("targetDisplay") or action.get("targetName")
447
+ expression = action.get("expressionText", "")
448
+ operator = action.get("operator", "=")
449
+ if operator != "=" and operator in {"+=", "-=", "*=", "/="}:
450
+ right = self.eval(expression, scope)
451
+ old = scope.get(str(target), 0)
452
+ value = old + right if operator == "+=" else old - right if operator == "-=" else old * right if operator == "*=" else old / right
453
+ else:
454
+ value = self.eval(expression, scope)
455
+ scope[str(target)] = value
456
+ self.trace.event("assignment", node["startLine"], target=target, expressionText=expression,
457
+ operator=operator, value=value, dependencies=action.get("dependencies", []))
458
+ self.trace.add(node["startLine"], "assign", f"Set {target}",
459
+ f"`{target}` becomes `{self.trace.display(value)}`.", node.get("text", ""))
460
+ return
461
+ if subtype == "print":
462
+ call = self._parse_expr(action.get("expressionText", ""))
463
+ args = []
464
+ if call and call.type == "call_expression":
465
+ args_node = call.child_by_field_name("arguments")
466
+ if args_node:
467
+ args = [self.eval(self.bytes_text(arg), scope) for arg in args_node.named_children]
468
+ text = " ".join(self.trace.display(value) for value in args)
469
+ self.trace.output += text + "\n"
470
+ self.trace.event("print", node["startLine"], value=text)
471
+ self.trace.add(node["startLine"], "print", "Print output", f"Output: `{text}`.",
472
+ node.get("text", ""))
473
+ return
474
+ if subtype == "call":
475
+ expression = action.get("expressionText", "")
476
+ self.eval(expression, scope)
477
+
478
+ def _parse_expr(self, text: str):
479
+ tree = self.parser.parse(text.encode("utf-8"))
480
+ node = tree.root_node
481
+ while node.type in {"program", "expression_statement"} and node.named_children:
482
+ node = node.named_children[0]
483
+ return node
484
+
485
+ def bytes_text(self, node) -> str:
486
+ return node.text.decode("utf-8", "replace")
487
+
488
+ def eval(self, text: str, scope) -> Any:
489
+ if not text:
490
+ return None
491
+ node = self._parse_expr(text)
492
+ return self.eval_node(node, scope) if node else None
493
+
494
+ def eval_node(self, node, scope) -> Any:
495
+ if node is None:
496
+ return None
497
+ kind = node.type
498
+ if kind in {"program", "expression_statement"}:
499
+ return self.eval_node(node.named_children[0], scope) if node.named_children else None
500
+ if kind == "number":
501
+ value = self.bytes_text(node)
502
+ return float(value) if "." in value else int(value)
503
+ if kind in {"string", "template_string"}:
504
+ return self.bytes_text(node).strip("'\"`")
505
+ if kind in {"true", "false"}:
506
+ return kind == "true"
507
+ if kind == "null":
508
+ return None
509
+ if kind == "identifier":
510
+ name = self.bytes_text(node)
511
+ value = scope.get(name)
512
+ if isinstance(value, tuple) and value and value[0] == "function":
513
+ return value[1]
514
+ return value if value is not None else 0
515
+ if kind == "array":
516
+ return [self.eval_node(child, scope) for child in node.named_children]
517
+ if kind == "parenthesized_expression":
518
+ return self.eval_node(node.named_children[0], scope) if node.named_children else None
519
+ if kind == "binary_expression":
520
+ left_node = node.child_by_field_name("left")
521
+ right_node = node.child_by_field_name("right")
522
+ left = self.eval_node(left_node, scope)
523
+ right = self.eval_node(right_node, scope)
524
+ op = self.bytes_text(node.child_by_field_name("operator")) if node.child_by_field_name("operator") else ""
525
+ if op == "+":
526
+ return left + right
527
+ if op == "-":
528
+ return left - right
529
+ if op == "*":
530
+ return left * right
531
+ if op == "/":
532
+ return left / right
533
+ if op == "%":
534
+ return left % right
535
+ if op == ">":
536
+ return left > right
537
+ if op == "<":
538
+ return left < right
539
+ if op == ">=":
540
+ return left >= right
541
+ if op == "<=":
542
+ return left <= right
543
+ if op in {"==", "==="}:
544
+ return left == right
545
+ if op in {"!=", "!=="}:
546
+ return left != right
547
+ if op == "&&":
548
+ return bool(left) and bool(right)
549
+ if op == "||":
550
+ return bool(left) or bool(right)
551
+ return None
552
+ if kind == "unary_expression":
553
+ operator = node.child_by_field_name("operator")
554
+ operand = node.child_by_field_name("argument")
555
+ value = self.eval_node(operand, scope)
556
+ if operator and self.bytes_text(operator) == "!":
557
+ return not bool(value)
558
+ if operator and self.bytes_text(operator) == "-":
559
+ return -value
560
+ return value
561
+ if kind == "ternary_expression":
562
+ condition = node.child_by_field_name("condition")
563
+ return self.eval_node(node.child_by_field_name("consequence") if self.eval_node(condition, scope) else node.child_by_field_name("alternative"), scope)
564
+ if kind in {"call_expression", "member_expression"}:
565
+ # Only user functions and console.log need evaluation for the trace.
566
+ if kind == "call_expression":
567
+ function = node.child_by_field_name("function")
568
+ function_name = self.bytes_text(function) if function else ""
569
+ args_node = node.child_by_field_name("arguments")
570
+ args = [self.eval_node(arg, scope) for arg in args_node.named_children] if args_node else []
571
+ if function_name in self.functions:
572
+ item = self.functions[function_name]
573
+ self.trace.function_calls += 1
574
+ local = {param["name"]: value for param, value in zip(item["params"], args)}
575
+ self.trace.scopes.append(local)
576
+ self.trace.add(item["startLine"], "call", f"Call {function_name}()",
577
+ "Enters the helper.")
578
+ try:
579
+ self.exec_block(item["body"]["children"], local)
580
+ except _Return as result:
581
+ return result.value
582
+ finally:
583
+ self.trace.scopes.pop()
584
+ return None
585
+ return None
586
+ if kind == "subscript_expression":
587
+ value = self.eval_node(node.child_by_field_name("object"), scope)
588
+ index = self.eval_node(node.child_by_field_name("index"), scope)
589
+ try:
590
+ return value[index]
591
+ except Exception:
592
+ return None
593
+ return None
594
+
595
+
596
+ def _guide(analysis: dict[str, Any], trace: dict[str, Any], language_name: str) -> dict[str, Any]:
597
+ metrics = analysis["metrics"]
598
+ output = trace["output"].strip()
599
+ display = f"{output} ⏎" if output else "No output"
600
+ line_count = analysis["lineCount"]
601
+ lines = [line for line in analysis["source"].split("\n")]
602
+ notes = []
603
+ for index, line in enumerate(lines, start=1):
604
+ stripped = line.strip()
605
+ if not stripped:
606
+ continue
607
+ tone = "statement"
608
+ if stripped.startswith(("//", "/*", "*")):
609
+ tone = "comment"
610
+ elif stripped.startswith(("if ", "if(", "for ", "for(", "while ", "while(")):
611
+ tone = "decision"
612
+ elif stripped.startswith("return"):
613
+ tone = "return"
614
+ elif "console.log" in stripped:
615
+ tone = "output"
616
+ notes.append({"line": index, "endLine": index, "code": stripped,
617
+ "note": "Executed in sequence as part of the program.", "tone": tone,
618
+ "synthetic": False})
619
+ concepts = [
620
+ {"term": "Variable", "definition": "A named slot that stores a value.", "inThisCode": "Assignments create and update the running state.", "line": 1},
621
+ {"term": "Control flow", "definition": "Conditions and loops decide which statements run.", "inThisCode": f"There are {metrics['conditions']} decisions and {metrics['loops']} loops.", "line": 1},
622
+ {"term": "Output", "definition": "console.log writes values to the program output.", "inThisCode": f"The sample output is `{display}`.", "line": max(1, line_count)},
623
+ ]
624
+ walkthrough = [{
625
+ "title": "Read from top to bottom",
626
+ "body": "Start with the values created near the top, then follow conditions, loops and calls.",
627
+ "lines": [1], "badge": "FLOW", "points": [
628
+ f"{metrics['assignments']} assignments",
629
+ f"{trace['iterations']} loop passes",
630
+ f"Output: `{display}`",
631
+ ],
632
+ }]
633
+ for fn in analysis["functions"][:3]:
634
+ walkthrough.append({
635
+ "title": f"Helper: {fn['name']}()", "body": "A function groups reusable statements.",
636
+ "lines": [fn["startLine"]], "badge": "HELPER",
637
+ "points": [f"{len(fn['params'])} parameter(s)"],
638
+ })
639
+ return {
640
+ "version": 1, "author": "local", "headline": f"How this {language_name} program works",
641
+ "sourceLineCount": line_count,
642
+ "summary": f"This {language_name} program has {metrics['assignments']} assignments, {metrics['loops']} loop(s), and produces `{display}` in the safe sample run.",
643
+ "overview": {
644
+ "paragraphs": [
645
+ f"The program runs from top to bottom. The sample run produces `{display}`.",
646
+ "Follow the named values first, then trace the conditions and repeated blocks.",
647
+ ],
648
+ "mentalModel": {"title": "A sequence of named values", "body": "Each assignment writes a value into a name. Conditions choose a path; loops repeat a block."},
649
+ "glance": [
650
+ {"label": "Language", "value": language_name, "hint": "Parsed locally"},
651
+ {"label": "Shape", "value": f"{metrics['functions']} function · {metrics['loops']} loop · {metrics['conditions']} decision", "hint": f"{line_count} lines"},
652
+ {"label": "Output", "value": display, "hint": "Safe sample run", "mono": True},
653
+ ],
654
+ },
655
+ "walkthrough": walkthrough, "lineNotes": notes, "concepts": concepts,
656
+ "watchOuts": [{"title": "Equality matters", "body": "Use === when you mean exact equality; avoid relying on loose coercion in beginner code."}],
657
+ "quiz": [
658
+ {"question": "What did the sample run print?", "answer": f"`{display}`"},
659
+ {"question": "How many loop passes were recorded?", "answer": str(trace["iterations"])},
660
+ ],
661
+ "traceNote": {"complete": trace["complete"], "output": trace["output"], "warnings": trace["warnings"], "stoppedReason": trace["stoppedReason"]},
662
+ "readingMinutes": max(2, min(8, line_count // 2 + 1)), "wordCount": max(120, line_count * 40),
663
+ }
664
+
665
+
666
+ def analyze_javascript(source: str, language: str = "javascript") -> dict[str, Any]:
667
+ text = str(source or "").replace("\r\n", "\n").replace("\r", "\n")
668
+ parser = _parser(language)
669
+ tree = parser.parse(text.encode("utf-8"))
670
+ if tree.root_node.has_error:
671
+ # Tree-sitter can still produce a useful partial tree; expose a warning rather than failing.
672
+ diagnostics = [{"severity": "warning", "message": "Some JavaScript could not be parsed completely.", "line": 1}]
673
+ else:
674
+ diagnostics = []
675
+ factory = _Factory(text, language)
676
+ children = [factory.convert(child) for child in tree.root_node.named_children]
677
+ body_children = []
678
+ for child in children:
679
+ if isinstance(child, list):
680
+ body_children.extend(child)
681
+ elif child:
682
+ body_children.append(child)
683
+ root = {
684
+ "type": "program", "id": factory.nid(), "startLine": 1,
685
+ "endLine": len(text.split("\n")), "header": "Program",
686
+ "body": {"type": "block", "startLine": 1, "endLine": len(text.split("\n")),
687
+ "children": body_children},
688
+ "language": LANGUAGES.get(language, LANGUAGES["javascript"])["name"],
689
+ "parseMode": "braces", "diagnostics": diagnostics,
690
+ }
691
+ metrics = _metrics(text, factory)
692
+ language_info = LANGUAGES.get(language, LANGUAGES["javascript"])
693
+ analysis = {
694
+ "source": text, "language": language_info, "languageId": language,
695
+ "root": root, "diagnostics": diagnostics, "lineCount": len(text.split("\n")),
696
+ "lines": [{"number": i, "text": line} for i, line in enumerate(text.split("\n"), 1)],
697
+ "highlightedLines": [html.escape(line) for line in text.split("\n")],
698
+ "functions": factory.functions, "classes": factory.classes,
699
+ "assignments": factory.assignments, "actionNodes": factory.actions,
700
+ "metrics": metrics,
701
+ "entry": {"kind": "program", "node": root, "name": "Program", "inferred": False},
702
+ "flowFocus": {"kind": "program", "node": root, "name": "Program"},
703
+ "parseDiagnostics": diagnostics, "confidence": "medium" if diagnostics else "high",
704
+ "projectTitle": f"{language_info['name']} program",
705
+ "featureSummary": f"{language_info['name']} · {metrics['loops']} loops · {metrics['functions']} functions",
706
+ }
707
+ trace = _Runner(analysis, text).run()
708
+ guide = _guide(analysis, trace, language_info["name"])
709
+ return {"analysis": analysis, "trace": trace, "guide": guide}