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,1630 @@
1
+ """A small AST interpreter that produces interactive function challenges."""
2
+
3
+ import ast
4
+ import json
5
+ import math
6
+ import operator
7
+ from string import Formatter
8
+ from dataclasses import dataclass, field
9
+ from pathlib import Path
10
+ from typing import Any, Dict, List, Optional, Sequence, Tuple
11
+
12
+ from ..analyzer import analyze_project, analyze_source
13
+ from ..models import AnalysisResult, FunctionInfo
14
+
15
+ MAX_CALL_DEPTH = 8
16
+ MAX_STEPS = 120
17
+ MAX_AST_NODES = 800
18
+ MAX_INTEGER_BITS = 256
19
+ MAX_COLLECTION_ITEMS = 100
20
+ MAX_LOOP_ITERATIONS = 40
21
+ MAX_SOURCE_CHARS = 60000
22
+
23
+
24
+ class SimulationError(ValueError):
25
+ """Raised when source or values are outside the supported safe subset."""
26
+
27
+
28
+ @dataclass
29
+ class _Function:
30
+ info: FunctionInfo
31
+ node: ast.FunctionDef
32
+
33
+
34
+ @dataclass
35
+ class _Frame:
36
+ function: _Function
37
+ variables: Dict[str, Any]
38
+ caller: Optional[str]
39
+
40
+
41
+ @dataclass(frozen=True)
42
+ class _ReturnFlow:
43
+ value: Any
44
+
45
+
46
+ class _BreakSignal(Exception):
47
+ pass
48
+
49
+
50
+ class _ContinueSignal(Exception):
51
+ pass
52
+
53
+
54
+ def _function_body(function: _Function) -> Sequence[ast.stmt]:
55
+ body = function.node.body
56
+ if (
57
+ body
58
+ and isinstance(body[0], ast.Expr)
59
+ and isinstance(body[0].value, ast.Constant)
60
+ and isinstance(body[0].value.value, str)
61
+ ):
62
+ return body[1:]
63
+ return body
64
+
65
+
66
+ def _local_names(function: _Function) -> set[str]:
67
+ names = {argument.arg for argument in function.node.args.args}
68
+ for node in ast.walk(ast.Module(body=list(_function_body(function)), type_ignores=[])):
69
+ if isinstance(node, ast.Assign):
70
+ names.update(
71
+ target.id for target in node.targets if isinstance(target, ast.Name)
72
+ )
73
+ elif isinstance(node, (ast.AnnAssign, ast.AugAssign)):
74
+ if isinstance(node.target, ast.Name):
75
+ names.add(node.target.id)
76
+ elif isinstance(node, ast.For) and isinstance(node.target, ast.Name):
77
+ names.add(node.target.id)
78
+ return names
79
+
80
+
81
+ @dataclass
82
+ class _Step:
83
+ kind: str
84
+ function_id: str
85
+ function_name: str
86
+ file: str
87
+ line: int
88
+ expression: str
89
+ prompt: str
90
+ variables: Dict[str, Any]
91
+ stack: List[Dict[str, Any]]
92
+ expected: Any = None
93
+ challenge: bool = False
94
+ hint: str = ""
95
+ choices: List[str] = field(default_factory=list)
96
+ target: Optional[str] = None
97
+
98
+ def public_dict(self) -> Dict[str, Any]:
99
+ return {
100
+ "kind": self.kind,
101
+ "function_id": self.function_id,
102
+ "function_name": self.function_name,
103
+ "file": self.file,
104
+ "line": self.line,
105
+ "expression": self.expression,
106
+ "prompt": self.prompt,
107
+ "variables": _json_safe(self.variables),
108
+ "stack": _json_safe(self.stack),
109
+ "challenge": self.challenge,
110
+ "hint": self.hint,
111
+ "choices": list(self.choices),
112
+ "target": self.target,
113
+ }
114
+
115
+
116
+ @dataclass
117
+ class PovSimulation:
118
+ """An immutable challenge sequence with private expected answers."""
119
+
120
+ function_id: str
121
+ steps: Tuple[_Step, ...]
122
+ sources: Dict[str, Dict[str, Any]]
123
+ mode: str = "function"
124
+ entry_name: str = ""
125
+ output: str = ""
126
+ final_variables: Dict[str, Any] = field(default_factory=dict)
127
+
128
+ def public_dict(self) -> Dict[str, Any]:
129
+ return {
130
+ "function_id": self.function_id,
131
+ "mode": self.mode,
132
+ "entry_name": self.entry_name or self.function_id,
133
+ "steps": [step.public_dict() for step in self.steps],
134
+ "sources": self.sources,
135
+ }
136
+
137
+ def check(self, index: int, answer: Any) -> Dict[str, Any]:
138
+ step = self._step(index)
139
+ if not step.challenge:
140
+ return {"correct": True, "feedback": "This step has no answer to check."}
141
+ if _answers_equal(answer, step.expected):
142
+ return {
143
+ "correct": True,
144
+ "feedback": "That's right! Continue tracing the program.",
145
+ "answer": _json_safe(step.expected),
146
+ }
147
+ return {
148
+ "correct": False,
149
+ "feedback": "Not quite. Check the current values and try again.",
150
+ }
151
+
152
+ def hint(self, index: int) -> str:
153
+ return self._step(index).hint
154
+
155
+ def answer(self, index: int) -> Any:
156
+ step = self._step(index)
157
+ return _json_safe(step.expected)
158
+
159
+ def _step(self, index: int) -> _Step:
160
+ if index < 0 or index >= len(self.steps):
161
+ raise SimulationError("The requested POV step does not exist.")
162
+ return self.steps[index]
163
+
164
+
165
+ def build_simulation(
166
+ project_root: str,
167
+ function_id: str,
168
+ arguments: Optional[Dict[str, Any]] = None,
169
+ ) -> PovSimulation:
170
+ """Create an interactive trace without importing or executing project code."""
171
+ root = Path(project_root).resolve()
172
+ analysis = analyze_project(str(root))
173
+ infos = {function.id: function for function in analysis.functions}
174
+ if function_id not in infos:
175
+ raise SimulationError("That function was not found in the analyzed project.")
176
+ return _build_simulation(
177
+ analysis,
178
+ _load_functions(root, infos),
179
+ function_id,
180
+ arguments,
181
+ )
182
+
183
+
184
+ def build_simulation_from_source(
185
+ source: str,
186
+ function_id: str,
187
+ arguments: Optional[Dict[str, Any]] = None,
188
+ filename: str = "pasted.py",
189
+ ) -> PovSimulation:
190
+ """Create a POV trace from virtual source without writing it to disk."""
191
+ if not isinstance(source, str):
192
+ raise SimulationError("Python source must be text.")
193
+ if len(source) > MAX_SOURCE_CHARS:
194
+ raise SimulationError(
195
+ "The source is too long to simulate safely (limit: {} characters).".format(
196
+ MAX_SOURCE_CHARS
197
+ )
198
+ )
199
+ analysis = analyze_source(source, filename)
200
+ syntax_errors = [item for item in analysis.diagnostics if item.severity == "error"]
201
+ if syntax_errors:
202
+ diagnostic = syntax_errors[0]
203
+ location = " on line {}".format(diagnostic.line) if diagnostic.line else ""
204
+ raise SimulationError(
205
+ "Cannot simulate pasted Python{}: {}".format(location, diagnostic.message)
206
+ )
207
+ infos = {function.id: function for function in analysis.functions}
208
+ functions = _load_functions_from_sources({filename: source}, infos)
209
+ return _build_simulation(analysis, functions, function_id, arguments)
210
+
211
+
212
+ def build_program_simulation_from_source(
213
+ source: str,
214
+ filename: str = "main.py",
215
+ ) -> PovSimulation:
216
+ """Create a bounded, interactive simulation of module-level statements."""
217
+ if not isinstance(source, str):
218
+ raise SimulationError("Python source must be text.")
219
+ if len(source) > MAX_SOURCE_CHARS:
220
+ raise SimulationError(
221
+ "The program is too long to simulate safely (limit: {} characters).".format(
222
+ MAX_SOURCE_CHARS
223
+ )
224
+ )
225
+ analysis = analyze_source(source, filename)
226
+ syntax_errors = [item for item in analysis.diagnostics if item.severity == "error"]
227
+ if syntax_errors:
228
+ diagnostic = syntax_errors[0]
229
+ location = " on line {}".format(diagnostic.line) if diagnostic.line else ""
230
+ raise SimulationError(
231
+ "Cannot simulate Python{}: {}".format(location, diagnostic.message)
232
+ )
233
+ try:
234
+ module = ast.parse(source, filename=filename)
235
+ except SyntaxError as error:
236
+ raise SimulationError(
237
+ "Cannot simulate Python on line {}: {}.".format(
238
+ error.lineno or "?", error.msg
239
+ )
240
+ ) from error
241
+
242
+ function_names = [
243
+ node.name for node in module.body if isinstance(node, ast.FunctionDef)
244
+ ]
245
+ if len(function_names) != len(set(function_names)):
246
+ raise SimulationError("Redefining a function is not supported in Be the Code.")
247
+ if "print" in function_names:
248
+ raise SimulationError("The name print is reserved for safe output in Be the Code.")
249
+ infos = {function.id: function for function in analysis.functions}
250
+ functions = _load_functions_from_sources({filename: source}, infos)
251
+ calls = {
252
+ (call.caller, call.line, call.expression): call.callee
253
+ for call in analysis.calls
254
+ }
255
+ entry_id = "{}::<program>".format(Path(filename).stem)
256
+ entry_info = FunctionInfo(
257
+ id=entry_id,
258
+ name="Program",
259
+ module=Path(filename).stem,
260
+ file=filename,
261
+ line=1,
262
+ end_line=max(1, len(source.splitlines())),
263
+ source=source,
264
+ docstring=None,
265
+ parameters=(),
266
+ return_expressions=(),
267
+ )
268
+ arguments = ast.arguments(
269
+ posonlyargs=[],
270
+ args=[],
271
+ kwonlyargs=[],
272
+ kw_defaults=[],
273
+ defaults=[],
274
+ )
275
+ executable: list[ast.stmt] = []
276
+ for node in module.body:
277
+ if isinstance(node, ast.FunctionDef):
278
+ continue
279
+ if (
280
+ isinstance(node, ast.Expr)
281
+ and isinstance(node.value, ast.Constant)
282
+ and isinstance(node.value.value, str)
283
+ ):
284
+ continue
285
+ executable.append(node)
286
+ entry_node = ast.FunctionDef(
287
+ name="Program",
288
+ args=arguments,
289
+ body=executable or [ast.Pass()],
290
+ decorator_list=[],
291
+ returns=None,
292
+ type_comment=None,
293
+ )
294
+ ast.fix_missing_locations(entry_node)
295
+ entry = _Function(entry_info, entry_node)
296
+ builder = _SimulationBuilder(functions, calls)
297
+ return builder.build_program(entry, module.body, source)
298
+
299
+
300
+ def _build_simulation(
301
+ analysis: AnalysisResult,
302
+ functions: Dict[str, _Function],
303
+ function_id: str,
304
+ arguments: Optional[Dict[str, Any]],
305
+ ) -> PovSimulation:
306
+ infos = {function.id: function for function in analysis.functions}
307
+ selected = infos.get(function_id)
308
+ if selected is None:
309
+ raise SimulationError("That function was not found in the analyzed project.")
310
+
311
+ calls = {
312
+ (call.caller, call.line, call.expression): call.callee
313
+ for call in analysis.calls
314
+ }
315
+ builder = _SimulationBuilder(functions, calls)
316
+ input_arguments = _validate_arguments(arguments or {})
317
+ return builder.build(functions[function_id], input_arguments)
318
+
319
+
320
+ def _load_functions(root: Path, infos: Dict[str, FunctionInfo]) -> Dict[str, _Function]:
321
+ by_file: Dict[str, List[FunctionInfo]] = {}
322
+ for info in infos.values():
323
+ by_file.setdefault(info.file, []).append(info)
324
+
325
+ functions: Dict[str, _Function] = {}
326
+ for relative, file_infos in by_file.items():
327
+ source = (root / relative).read_text(encoding="utf-8")
328
+ try:
329
+ tree = ast.parse(source, filename=relative)
330
+ except SyntaxError as error:
331
+ raise SimulationError(
332
+ "Cannot simulate {}: {}".format(relative, error.msg)
333
+ ) from error
334
+ for node in tree.body:
335
+ if isinstance(node, ast.FunctionDef):
336
+ function_id = "{}.{}".format(file_infos[0].module, node.name)
337
+ info = next((item for item in file_infos if item.id == function_id), None)
338
+ if info is not None:
339
+ functions[function_id] = _Function(info, node)
340
+ return functions
341
+
342
+
343
+ def _load_functions_from_sources(
344
+ sources: Dict[str, str],
345
+ infos: Dict[str, FunctionInfo],
346
+ ) -> Dict[str, _Function]:
347
+ by_file: Dict[str, List[FunctionInfo]] = {}
348
+ for info in infos.values():
349
+ by_file.setdefault(info.file, []).append(info)
350
+
351
+ functions: Dict[str, _Function] = {}
352
+ for relative, file_infos in by_file.items():
353
+ try:
354
+ tree = ast.parse(sources[relative], filename=relative)
355
+ except SyntaxError as error:
356
+ raise SimulationError(
357
+ "Cannot simulate {}: {}".format(relative, error.msg)
358
+ ) from error
359
+ for node in tree.body:
360
+ if isinstance(node, ast.FunctionDef):
361
+ function_id = "{}.{}".format(file_infos[0].module, node.name)
362
+ info = next((item for item in file_infos if item.id == function_id), None)
363
+ if info is not None:
364
+ functions[function_id] = _Function(info, node)
365
+ return functions
366
+
367
+
368
+ def _validate_arguments(arguments: Dict[str, Any]) -> Dict[str, Any]:
369
+ if not isinstance(arguments, dict):
370
+ raise SimulationError("Arguments must be an object with parameter names and values.")
371
+ if len(arguments) > 40:
372
+ raise SimulationError("Too many function arguments.")
373
+ validated: Dict[str, Any] = {}
374
+ for name, value in arguments.items():
375
+ if not isinstance(name, str) or not name.isidentifier():
376
+ raise SimulationError("Argument names must be valid parameter names.")
377
+ validated[name] = _validate_json_value(value, name)
378
+ return validated
379
+
380
+
381
+ def _validate_json_value(value: Any, label: str, depth: int = 0) -> Any:
382
+ if depth > 8:
383
+ raise SimulationError("{} is nested too deeply.".format(label))
384
+ if value is None or isinstance(value, (str, bool)):
385
+ if isinstance(value, str) and len(value) > 10000:
386
+ raise SimulationError("{} is too long.".format(label))
387
+ return value
388
+ if isinstance(value, int) and not isinstance(value, bool):
389
+ if value.bit_length() > MAX_INTEGER_BITS:
390
+ raise SimulationError("{} is too large.".format(label))
391
+ return value
392
+ if isinstance(value, float):
393
+ if not math.isfinite(value):
394
+ raise SimulationError("{} must be a finite number.".format(label))
395
+ return value
396
+ if isinstance(value, list):
397
+ if len(value) > MAX_COLLECTION_ITEMS:
398
+ raise SimulationError("{} has too many items.".format(label))
399
+ return [
400
+ _validate_json_value(item, label, depth + 1)
401
+ for item in value
402
+ ]
403
+ if isinstance(value, dict):
404
+ if len(value) > MAX_COLLECTION_ITEMS or not all(
405
+ isinstance(key, str) for key in value
406
+ ):
407
+ raise SimulationError("{} must be a small object with string keys.".format(label))
408
+ return {
409
+ key: _validate_json_value(item, label, depth + 1)
410
+ for key, item in value.items()
411
+ }
412
+ raise SimulationError("{} must be a JSON value.".format(label))
413
+
414
+
415
+ class _SimulationBuilder:
416
+ def __init__(
417
+ self,
418
+ functions: Dict[str, _Function],
419
+ call_targets: Dict[Tuple[str, int, str], str],
420
+ ) -> None:
421
+ self.functions = functions
422
+ self.call_targets = call_targets
423
+ self.steps: List[_Step] = []
424
+ self.frames: List[_Frame] = []
425
+ self.global_variables: Dict[str, Any] = {}
426
+ self.program_entry: Optional[_Function] = None
427
+ self.local_names: Dict[str, set[str]] = {}
428
+ self.output = ""
429
+ self.loop_iterations = 0
430
+ self.node_count = sum(
431
+ 1 for function in functions.values() for _ in ast.walk(function.node)
432
+ )
433
+ if self.node_count > MAX_AST_NODES:
434
+ raise SimulationError("This project is too large for the POV simulator.")
435
+
436
+ def build(self, function: _Function, arguments: Dict[str, Any]) -> PovSimulation:
437
+ self._validate_function(function, set())
438
+ self._invoke(function, arguments, None)
439
+ if not self.steps:
440
+ raise SimulationError("This function has no supported steps to simulate.")
441
+ sources = {
442
+ function_id: {
443
+ "file": item.info.file,
444
+ "line": min(
445
+ (decorator.lineno for decorator in item.node.decorator_list),
446
+ default=item.node.lineno,
447
+ ),
448
+ "source": item.info.source,
449
+ }
450
+ for function_id, item in self.functions.items()
451
+ }
452
+ return PovSimulation(
453
+ function.info.id,
454
+ tuple(self.steps),
455
+ sources,
456
+ mode="function",
457
+ entry_name=function.info.name,
458
+ output=self.output,
459
+ )
460
+
461
+ def build_program(
462
+ self,
463
+ entry: _Function,
464
+ module_body: Sequence[ast.stmt],
465
+ source: str,
466
+ ) -> PovSimulation:
467
+ self.program_entry = entry
468
+ self.node_count += sum(1 for _ in ast.walk(entry.node))
469
+ if self.node_count > MAX_AST_NODES:
470
+ raise SimulationError("This program is too large for the POV simulator.")
471
+ executable = [
472
+ node for node in module_body
473
+ if not isinstance(node, ast.FunctionDef)
474
+ and not (
475
+ isinstance(node, ast.Expr)
476
+ and isinstance(node.value, ast.Constant)
477
+ and isinstance(node.value.value, str)
478
+ )
479
+ ]
480
+ if not executable:
481
+ raise SimulationError("This program has no executable top-level statements.")
482
+
483
+ seen: set[str] = set()
484
+ for node in module_body:
485
+ if isinstance(node, ast.FunctionDef):
486
+ if node.decorator_list:
487
+ self._unsupported(node, "Decorated functions are not supported in Be the Code.")
488
+ function_id = next(
489
+ (
490
+ key for key, item in self.functions.items()
491
+ if item.info.name == node.name
492
+ ),
493
+ None,
494
+ )
495
+ if function_id is not None:
496
+ self._validate_function(self.functions[function_id], seen)
497
+ self._validate_statements(_function_body(entry), entry, seen)
498
+
499
+ self.global_variables = {}
500
+ self.frames.append(_Frame(entry, self.global_variables, None))
501
+ first_operation = _first_meaningful_operation(_function_body(entry))
502
+ self._append_step(
503
+ _Step(
504
+ kind="program_start",
505
+ function_id=entry.info.id,
506
+ function_name=entry.info.name,
507
+ file=entry.info.file,
508
+ line=1,
509
+ expression=entry.info.name,
510
+ prompt="Predict the first meaningful operation.",
511
+ variables={},
512
+ stack=self._stack(),
513
+ expected=first_operation,
514
+ challenge=first_operation is not None,
515
+ hint="Skip simple value assignments and look for the first decision, loop, update, call, or output.",
516
+ choices=[
517
+ "branch",
518
+ "loop",
519
+ "variable update",
520
+ "function call",
521
+ "output",
522
+ ],
523
+ )
524
+ )
525
+ try:
526
+ self._execute_statements(_function_body(entry), self.frames[-1])
527
+ finally:
528
+ self.frames.pop()
529
+ self._append_step(
530
+ _Step(
531
+ kind="program_end",
532
+ function_id=entry.info.id,
533
+ function_name=entry.info.name,
534
+ file=entry.info.file,
535
+ line=max(1, entry.info.end_line),
536
+ expression="",
537
+ prompt="The program has finished.",
538
+ variables=dict(self.global_variables),
539
+ stack=[],
540
+ )
541
+ )
542
+ sources = {
543
+ entry.info.id: {
544
+ "file": entry.info.file,
545
+ "line": 1,
546
+ "source": source,
547
+ }
548
+ }
549
+ sources.update({
550
+ function_id: {
551
+ "file": item.info.file,
552
+ "line": min(
553
+ (decorator.lineno for decorator in item.node.decorator_list),
554
+ default=item.node.lineno,
555
+ ),
556
+ "source": item.info.source,
557
+ }
558
+ for function_id, item in self.functions.items()
559
+ })
560
+ return PovSimulation(
561
+ entry.info.id,
562
+ tuple(self.steps),
563
+ sources,
564
+ mode="code",
565
+ entry_name=entry.info.name,
566
+ output=self.output,
567
+ final_variables=_json_safe(self.global_variables),
568
+ )
569
+
570
+ def _validate_function(self, function: _Function, seen: set) -> None:
571
+ if function.info.id in seen:
572
+ return
573
+ if function.info.name == "print":
574
+ raise SimulationError("The name print is reserved for safe output.")
575
+ seen.add(function.info.id)
576
+ node = function.node
577
+ arguments = node.args
578
+ if arguments.vararg or arguments.kwarg or arguments.kwonlyargs or arguments.posonlyargs:
579
+ raise SimulationError(
580
+ "{} uses advanced parameter syntax. The simulator supports simple positional parameters.".format(
581
+ function.info.name
582
+ )
583
+ )
584
+ self.local_names[function.info.id] = _local_names(function)
585
+ for default in arguments.defaults:
586
+ self._validate_default(default, function)
587
+ self._validate_expr(default, function)
588
+ self._validate_statements(_function_body(function), function, seen)
589
+
590
+ def _validate_statements(
591
+ self,
592
+ statements: Sequence[ast.stmt],
593
+ function: _Function,
594
+ seen: set,
595
+ loop_depth: int = 0,
596
+ ) -> None:
597
+ for statement in statements:
598
+ if isinstance(statement, ast.Return):
599
+ if statement.value is not None:
600
+ self._validate_expr(statement.value, function, seen)
601
+ elif isinstance(statement, ast.Assign):
602
+ if len(statement.targets) != 1 or not isinstance(statement.targets[0], ast.Name):
603
+ self._unsupported(statement, "Only assignments to one local variable are supported.")
604
+ self._validate_expr(statement.value, function, seen)
605
+ elif isinstance(statement, ast.AnnAssign):
606
+ if not isinstance(statement.target, ast.Name):
607
+ self._unsupported(statement, "Only local variable annotations are supported.")
608
+ if not (
609
+ isinstance(statement.annotation, ast.Name)
610
+ or (
611
+ isinstance(statement.annotation, ast.Constant)
612
+ and isinstance(statement.annotation.value, str)
613
+ )
614
+ ):
615
+ self._unsupported(
616
+ statement.annotation,
617
+ "Only simple type-name annotations are supported.",
618
+ )
619
+ if statement.value is not None:
620
+ self._validate_expr(statement.value, function, seen)
621
+ elif isinstance(statement, ast.If):
622
+ self._validate_expr(statement.test, function, seen)
623
+ self._validate_statements(statement.body, function, seen, loop_depth)
624
+ self._validate_statements(statement.orelse, function, seen, loop_depth)
625
+ elif isinstance(statement, ast.AugAssign):
626
+ if not isinstance(statement.target, ast.Name):
627
+ self._unsupported(statement, "Updates must target one simple variable.")
628
+ if type(statement.op) not in _BINARY_OPERATORS:
629
+ self._unsupported(statement, "This variable update operator is not supported.")
630
+ self._validate_expr(statement.value, function, seen)
631
+ elif isinstance(statement, ast.For):
632
+ if not isinstance(statement.target, ast.Name):
633
+ self._unsupported(statement, "For loops must use one simple variable target.")
634
+ if statement.orelse:
635
+ self._unsupported(statement, "Loop else clauses are not supported.")
636
+ self._validate_expr(statement.iter, function, seen)
637
+ self._validate_statements(statement.body, function, seen, loop_depth + 1)
638
+ elif isinstance(statement, ast.While):
639
+ if statement.orelse:
640
+ self._unsupported(statement, "Loop else clauses are not supported.")
641
+ self._validate_expr(statement.test, function, seen)
642
+ self._validate_statements(statement.body, function, seen, loop_depth + 1)
643
+ elif isinstance(statement, ast.Break):
644
+ if loop_depth == 0:
645
+ self._unsupported(statement, "break is only supported inside a loop.")
646
+ elif isinstance(statement, ast.Continue):
647
+ if loop_depth == 0:
648
+ self._unsupported(statement, "continue is only supported inside a loop.")
649
+ elif isinstance(statement, ast.Expr):
650
+ if isinstance(statement.value, ast.Call) and isinstance(
651
+ statement.value.func, ast.Name
652
+ ) and statement.value.func.id == "print":
653
+ if statement.value.keywords:
654
+ self._unsupported(statement, "print keyword arguments are not supported.")
655
+ for argument in statement.value.args:
656
+ self._validate_expr(argument, function, seen)
657
+ else:
658
+ self._validate_expr(statement.value, function, seen)
659
+ elif isinstance(statement, ast.Pass):
660
+ continue
661
+ else:
662
+ self._unsupported(
663
+ statement,
664
+ "Supported statements are assignments, if/else, bounded loops, direct function calls, print, and return.",
665
+ )
666
+
667
+ def _validate_expr(
668
+ self,
669
+ expression: ast.expr,
670
+ function: _Function,
671
+ seen: Optional[set] = None,
672
+ ) -> None:
673
+ if isinstance(expression, ast.Constant):
674
+ _validate_json_value(expression.value, "literal")
675
+ return
676
+ if isinstance(expression, ast.Name):
677
+ return
678
+ if isinstance(expression, ast.BinOp) and type(expression.op) in _BINARY_OPERATORS:
679
+ self._validate_expr(expression.left, function, seen)
680
+ self._validate_expr(expression.right, function, seen)
681
+ return
682
+ if isinstance(expression, ast.UnaryOp) and type(expression.op) in _UNARY_OPERATORS:
683
+ self._validate_expr(expression.operand, function, seen)
684
+ return
685
+ if isinstance(expression, ast.BoolOp) and isinstance(expression.op, (ast.And, ast.Or)):
686
+ for value in expression.values:
687
+ self._validate_expr(value, function, seen)
688
+ return
689
+ if isinstance(expression, ast.Compare):
690
+ if not all(type(operator_node) in _COMPARISON_OPERATORS for operator_node in expression.ops):
691
+ self._unsupported(expression, "This comparison operator is not supported.")
692
+ self._validate_expr(expression.left, function, seen)
693
+ for comparator in expression.comparators:
694
+ self._validate_expr(comparator, function, seen)
695
+ return
696
+ if isinstance(expression, (ast.List, ast.Tuple)):
697
+ if len(expression.elts) > MAX_COLLECTION_ITEMS:
698
+ self._unsupported(expression, "This collection has too many items.")
699
+ for item in expression.elts:
700
+ self._validate_expr(item, function, seen)
701
+ return
702
+ if isinstance(expression, ast.Dict):
703
+ if len(expression.keys) > MAX_COLLECTION_ITEMS:
704
+ self._unsupported(expression, "This object has too many items.")
705
+ for key, value in zip(expression.keys, expression.values):
706
+ if key is None:
707
+ self._unsupported(expression, "Dictionary unpacking is not supported.")
708
+ self._validate_expr(key, function, seen)
709
+ self._validate_expr(value, function, seen)
710
+ return
711
+ if isinstance(expression, ast.Call):
712
+ if _is_string_format_call(expression):
713
+ self._validate_string_format(expression, function, seen)
714
+ return
715
+ if (
716
+ isinstance(expression.func, ast.Name)
717
+ and expression.func.id in _SAFE_BUILTINS
718
+ and self._resolve_call(expression, function) is None
719
+ ):
720
+ if expression.keywords:
721
+ self._unsupported(expression, "Safe built-in calls do not support keyword arguments.")
722
+ for argument in expression.args:
723
+ self._validate_expr(argument, function, seen)
724
+ return
725
+ if not isinstance(expression.func, (ast.Name, ast.Attribute)):
726
+ self._unsupported(expression, "Only direct calls to project functions are supported.")
727
+ if any(keyword.arg is None for keyword in expression.keywords):
728
+ self._unsupported(expression, "Keyword unpacking is not supported.")
729
+ for argument in expression.args:
730
+ if isinstance(argument, ast.Starred):
731
+ self._unsupported(expression, "Starred call arguments are not supported.")
732
+ self._validate_expr(argument, function, seen)
733
+ for keyword in expression.keywords:
734
+ self._validate_expr(keyword.value, function, seen)
735
+ target = self._resolve_call(expression, function)
736
+ if target not in self.functions:
737
+ self._unsupported(
738
+ expression,
739
+ "Call {!r} cannot be resolved to a project function.".format(
740
+ ast.unparse(expression.func)
741
+ ),
742
+ )
743
+ if seen is not None:
744
+ self._validate_function(self.functions[target], seen)
745
+ return
746
+ self._unsupported(
747
+ expression,
748
+ "This expression is outside the safe POV subset: {}.".format(
749
+ type(expression).__name__
750
+ ),
751
+ )
752
+
753
+ def _validate_string_format(
754
+ self,
755
+ call: ast.Call,
756
+ function: _Function,
757
+ seen: Optional[set],
758
+ ) -> None:
759
+ if any(keyword.arg is None for keyword in call.keywords):
760
+ self._unsupported(call, "String formatting does not support keyword unpacking.")
761
+ if any(isinstance(argument, ast.Starred) for argument in call.args):
762
+ self._unsupported(call, "String formatting does not support unpacked arguments.")
763
+ for argument in call.args:
764
+ self._validate_expr(argument, function, seen)
765
+ for keyword in call.keywords:
766
+ self._validate_expr(keyword.value, function, seen)
767
+
768
+ template = call.func.value.value
769
+ if len(template) > 10000:
770
+ self._unsupported(call, "String format templates are limited to 10,000 characters.")
771
+ positional_count = len(call.args)
772
+ keyword_names = {keyword.arg for keyword in call.keywords}
773
+ automatic_index = 0
774
+ try:
775
+ fields = list(Formatter().parse(template))
776
+ except ValueError as error:
777
+ raise SimulationError(
778
+ "This string format template is invalid at line {}.".format(call.lineno)
779
+ ) from error
780
+ for _, field_name, format_spec, conversion in fields:
781
+ if field_name is None:
782
+ continue
783
+ if format_spec or conversion is not None:
784
+ self._unsupported(
785
+ call,
786
+ "String formatting supports simple replacement fields only.",
787
+ )
788
+ if field_name == "":
789
+ field_index = automatic_index
790
+ automatic_index += 1
791
+ if field_index >= positional_count:
792
+ self._unsupported(call, "A string format field has no matching argument.")
793
+ elif field_name.isdecimal():
794
+ if len(field_name) > len(str(positional_count)) or int(field_name) >= positional_count:
795
+ self._unsupported(call, "A string format field has no matching argument.")
796
+ elif field_name.isidentifier():
797
+ if field_name not in keyword_names:
798
+ self._unsupported(call, "A string format field has no matching argument.")
799
+ else:
800
+ self._unsupported(
801
+ call,
802
+ "String formatting does not support attribute or index access.",
803
+ )
804
+
805
+ def _validate_default(self, expression: ast.expr, function: _Function) -> None:
806
+ allowed = (ast.Constant, ast.List, ast.Tuple, ast.Dict, ast.UnaryOp, ast.BinOp)
807
+ if not isinstance(expression, allowed):
808
+ self._unsupported(
809
+ expression,
810
+ "Default values must be safe literals or literal arithmetic.",
811
+ )
812
+ if isinstance(expression, ast.List):
813
+ children = expression.elts
814
+ elif isinstance(expression, ast.Tuple):
815
+ children = expression.elts
816
+ elif isinstance(expression, ast.Dict):
817
+ if any(key is None for key in expression.keys):
818
+ self._unsupported(expression, "Dictionary unpacking is not supported.")
819
+ children = [
820
+ node
821
+ for pair in zip(expression.keys, expression.values)
822
+ for node in pair
823
+ ]
824
+ elif isinstance(expression, ast.UnaryOp):
825
+ children = [expression.operand]
826
+ elif isinstance(expression, ast.BinOp):
827
+ if type(expression.op) not in _BINARY_OPERATORS:
828
+ self._unsupported(expression, "This default operator is not supported.")
829
+ children = [expression.left, expression.right]
830
+ else:
831
+ children = []
832
+ for child in children:
833
+ self._validate_default(child, function)
834
+
835
+ def _unsupported(self, node: ast.AST, message: str) -> None:
836
+ line = getattr(node, "lineno", None)
837
+ detail = " at line {}".format(line) if line is not None else ""
838
+ raise SimulationError(message + detail)
839
+
840
+ def _resolve_call(self, call: ast.Call, function: _Function) -> Optional[str]:
841
+ expression = ast.unparse(call.func)
842
+ target = self.call_targets.get((function.info.id, call.lineno, expression))
843
+ if target is not None:
844
+ return target
845
+ if (
846
+ self.program_entry is not None
847
+ and function.info.id == self.program_entry.info.id
848
+ and isinstance(call.func, ast.Name)
849
+ ):
850
+ matches = [
851
+ function_id for function_id, item in self.functions.items()
852
+ if item.info.name == call.func.id
853
+ ]
854
+ return matches[0] if len(matches) == 1 else None
855
+ return None
856
+
857
+ def _invoke(
858
+ self,
859
+ function: _Function,
860
+ provided: Dict[str, Any],
861
+ caller: Optional[str],
862
+ ) -> Any:
863
+ if len(self.frames) >= MAX_CALL_DEPTH:
864
+ raise SimulationError(
865
+ "Call depth exceeded the safe limit of {}.".format(MAX_CALL_DEPTH)
866
+ )
867
+ frame = _Frame(function, self._bind(function, provided), caller)
868
+ self.frames.append(frame)
869
+ self._append_step(
870
+ _Step(
871
+ kind="enter",
872
+ function_id=function.info.id,
873
+ function_name=function.info.name,
874
+ file=function.info.file,
875
+ line=function.node.lineno,
876
+ expression=function.info.name + "(" + _format_mapping(frame.variables) + ")",
877
+ prompt="You are now {}. The caller handed you these arguments.".format(
878
+ function.info.name
879
+ ),
880
+ variables=dict(frame.variables),
881
+ stack=self._stack(),
882
+ )
883
+ )
884
+ try:
885
+ flow = self._execute_statements(_function_body(function), frame)
886
+ finally:
887
+ self.frames.pop()
888
+ return flow.value if flow is not None else None
889
+
890
+ def _bind(self, function: _Function, provided: Dict[str, Any]) -> Dict[str, Any]:
891
+ node = function.node
892
+ names = [argument.arg for argument in node.args.args]
893
+ unknown = set(provided) - set(names)
894
+ if unknown:
895
+ raise SimulationError(
896
+ "Unknown parameter(s) for {}: {}.".format(
897
+ function.info.name, ", ".join(sorted(unknown))
898
+ )
899
+ )
900
+
901
+ defaults: Dict[str, Any] = {}
902
+ positional_defaults = node.args.defaults
903
+ if positional_defaults:
904
+ default_names = names[-len(positional_defaults):]
905
+ for name, default in zip(default_names, positional_defaults):
906
+ defaults[name] = self._eval(default, {}, function)
907
+
908
+ variables: Dict[str, Any] = {}
909
+ for name in names:
910
+ if name in provided:
911
+ variables[name] = provided[name]
912
+ elif name in defaults:
913
+ variables[name] = defaults[name]
914
+ else:
915
+ raise SimulationError(
916
+ "Enter a value for the required parameter {!r}.".format(name)
917
+ )
918
+ return variables
919
+
920
+ def _execute_statements(
921
+ self,
922
+ statements: Sequence[ast.stmt],
923
+ frame: _Frame,
924
+ ) -> Optional[_ReturnFlow]:
925
+ for statement in statements:
926
+ if isinstance(statement, ast.Pass):
927
+ continue
928
+ if isinstance(statement, ast.Return):
929
+ value = self._eval(statement.value, frame.variables, frame.function) if statement.value else None
930
+ expression = ast.unparse(statement.value) if statement.value else "None"
931
+ self._append_step(
932
+ _Step(
933
+ kind="return",
934
+ function_id=frame.function.info.id,
935
+ function_name=frame.function.info.name,
936
+ file=frame.function.info.file,
937
+ line=statement.lineno,
938
+ expression=expression,
939
+ prompt="What value does {} return to its caller?".format(
940
+ frame.function.info.name
941
+ ),
942
+ variables=dict(frame.variables),
943
+ stack=self._stack(),
944
+ expected=value,
945
+ challenge=True,
946
+ hint="Evaluate the return expression using the local variables shown, then submit that value.",
947
+ )
948
+ )
949
+ return _ReturnFlow(value)
950
+ if isinstance(statement, (ast.Assign, ast.AnnAssign)):
951
+ expression = statement.value
952
+ if expression is None:
953
+ continue
954
+ name = statement.targets[0].id if isinstance(statement, ast.Assign) else statement.target.id
955
+ result = self._eval(expression, frame.variables, frame.function)
956
+ expects_answer = _contains_arithmetic(expression)
957
+ if expects_answer:
958
+ self._append_step(
959
+ _Step(
960
+ kind="arithmetic",
961
+ function_id=frame.function.info.id,
962
+ function_name=frame.function.info.name,
963
+ file=frame.function.info.file,
964
+ line=statement.lineno,
965
+ expression=ast.unparse(expression),
966
+ prompt="Work out the value assigned to {}.".format(name),
967
+ variables=dict(frame.variables),
968
+ stack=self._stack(),
969
+ expected=result,
970
+ challenge=True,
971
+ hint="Substitute the local values into the expression, then follow the operator order.",
972
+ target=name,
973
+ )
974
+ )
975
+ frame.variables[name] = result
976
+ self._append_step(
977
+ _Step(
978
+ kind="assignment",
979
+ function_id=frame.function.info.id,
980
+ function_name=frame.function.info.name,
981
+ file=frame.function.info.file,
982
+ line=statement.lineno,
983
+ expression="{} = {}".format(name, _format_value(result)),
984
+ prompt="{} now holds {}.".format(name, _format_value(result)),
985
+ variables=dict(frame.variables),
986
+ stack=self._stack(),
987
+ target=name,
988
+ )
989
+ )
990
+ continue
991
+ if isinstance(statement, ast.AugAssign):
992
+ name = statement.target.id
993
+ is_program_scope = (
994
+ self.program_entry is not None
995
+ and frame.function.info.id == self.program_entry.info.id
996
+ )
997
+ if name not in frame.variables and not is_program_scope:
998
+ raise SimulationError(
999
+ "Name {!r} is not available for this update.".format(name)
1000
+ )
1001
+ old_value = (
1002
+ frame.variables[name]
1003
+ if name in frame.variables
1004
+ else self.global_variables.get(name)
1005
+ )
1006
+ if name not in frame.variables and name not in self.global_variables:
1007
+ raise SimulationError(
1008
+ "Name {!r} is not available for this update.".format(name)
1009
+ )
1010
+ right_value = self._eval(statement.value, frame.variables, frame.function)
1011
+ result = _apply_binary(statement.op, old_value, right_value)
1012
+ self._append_step(
1013
+ _Step(
1014
+ kind="arithmetic",
1015
+ function_id=frame.function.info.id,
1016
+ function_name=frame.function.info.name,
1017
+ file=frame.function.info.file,
1018
+ line=statement.lineno,
1019
+ expression="{} {} {}".format(name, _AUGMENTED_OPERATORS[type(statement.op)], ast.unparse(statement.value)),
1020
+ prompt="What value does {} hold after this update?".format(name),
1021
+ variables=dict(frame.variables),
1022
+ stack=self._stack(),
1023
+ expected=result,
1024
+ challenge=True,
1025
+ hint="Start with the current value of {}, apply the operator, then use the expression on the right.".format(name),
1026
+ target=name,
1027
+ )
1028
+ )
1029
+ frame.variables[name] = result
1030
+ self._append_step(
1031
+ _Step(
1032
+ kind="assignment",
1033
+ function_id=frame.function.info.id,
1034
+ function_name=frame.function.info.name,
1035
+ file=frame.function.info.file,
1036
+ line=statement.lineno,
1037
+ expression="{} = {}".format(name, _format_value(result)),
1038
+ prompt="{} now holds {}.".format(name, _format_value(result)),
1039
+ variables=dict(frame.variables),
1040
+ stack=self._stack(),
1041
+ target=name,
1042
+ )
1043
+ )
1044
+ continue
1045
+ if isinstance(statement, ast.If):
1046
+ condition = self._eval(statement.test, frame.variables, frame.function)
1047
+ result = bool(condition)
1048
+ self._append_step(
1049
+ _Step(
1050
+ kind="condition",
1051
+ function_id=frame.function.info.id,
1052
+ function_name=frame.function.info.name,
1053
+ file=frame.function.info.file,
1054
+ line=statement.test.lineno,
1055
+ expression=ast.unparse(statement.test),
1056
+ prompt="Does this condition evaluate to True or False?",
1057
+ variables=dict(frame.variables),
1058
+ stack=self._stack(),
1059
+ expected=result,
1060
+ challenge=True,
1061
+ hint="Substitute the local values and compare them. Then choose the branch that matches.",
1062
+ choices=["True", "False"],
1063
+ )
1064
+ )
1065
+ branch = statement.body if result else statement.orelse
1066
+ flow = self._execute_statements(branch, frame)
1067
+ if flow is not None:
1068
+ return flow
1069
+ continue
1070
+ if isinstance(statement, ast.For):
1071
+ iterable = self._eval(statement.iter, frame.variables, frame.function)
1072
+ if not isinstance(iterable, (list, tuple)):
1073
+ raise SimulationError("For loops need a small list, tuple, or range value.")
1074
+ if len(iterable) > MAX_LOOP_ITERATIONS:
1075
+ raise SimulationError(
1076
+ "A loop exceeds the safe limit of {} iterations.".format(
1077
+ MAX_LOOP_ITERATIONS
1078
+ )
1079
+ )
1080
+ for value in iterable:
1081
+ self._count_loop_iteration()
1082
+ name = statement.target.id
1083
+ self._append_step(
1084
+ _Step(
1085
+ kind="loop_value",
1086
+ function_id=frame.function.info.id,
1087
+ function_name=frame.function.info.name,
1088
+ file=frame.function.info.file,
1089
+ line=statement.lineno,
1090
+ expression=ast.unparse(statement.target) + " in " + ast.unparse(statement.iter),
1091
+ prompt="What value is assigned to {} in the next loop pass?".format(name),
1092
+ variables=dict(frame.variables),
1093
+ stack=self._stack(),
1094
+ expected=value,
1095
+ challenge=True,
1096
+ hint="Follow the iterable from left to right and find its next value.",
1097
+ target=name,
1098
+ )
1099
+ )
1100
+ frame.variables[name] = value
1101
+ self._append_step(
1102
+ _Step(
1103
+ kind="iteration",
1104
+ function_id=frame.function.info.id,
1105
+ function_name=frame.function.info.name,
1106
+ file=frame.function.info.file,
1107
+ line=statement.target.lineno,
1108
+ expression="{} = {}".format(name, _format_value(value)),
1109
+ prompt="Loop variable {} is now {}.".format(name, _format_value(value)),
1110
+ variables=dict(frame.variables),
1111
+ stack=self._stack(),
1112
+ )
1113
+ )
1114
+ try:
1115
+ flow = self._execute_statements(statement.body, frame)
1116
+ except _ContinueSignal:
1117
+ continue
1118
+ except _BreakSignal:
1119
+ break
1120
+ if flow is not None:
1121
+ return flow
1122
+ self._append_step(
1123
+ _Step(
1124
+ kind="loop_condition",
1125
+ function_id=frame.function.info.id,
1126
+ function_name=frame.function.info.name,
1127
+ file=frame.function.info.file,
1128
+ line=statement.lineno,
1129
+ expression="next item in " + ast.unparse(statement.iter),
1130
+ prompt="Will the for loop execute another pass?",
1131
+ variables=dict(frame.variables),
1132
+ stack=self._stack(),
1133
+ expected=False,
1134
+ challenge=True,
1135
+ hint="Check whether any values remain in the iterable.",
1136
+ choices=["True", "False"],
1137
+ target=statement.target.id,
1138
+ )
1139
+ )
1140
+ continue
1141
+ if isinstance(statement, ast.While):
1142
+ while True:
1143
+ condition = bool(self._eval(statement.test, frame.variables, frame.function))
1144
+ self._append_step(
1145
+ _Step(
1146
+ kind="loop_condition",
1147
+ function_id=frame.function.info.id,
1148
+ function_name=frame.function.info.name,
1149
+ file=frame.function.info.file,
1150
+ line=statement.test.lineno,
1151
+ expression=ast.unparse(statement.test),
1152
+ prompt="Does the while condition keep the loop running?",
1153
+ variables=dict(frame.variables),
1154
+ stack=self._stack(),
1155
+ expected=condition,
1156
+ challenge=True,
1157
+ hint="Recheck the current variable values after each completed iteration.",
1158
+ choices=["True", "False"],
1159
+ )
1160
+ )
1161
+ if not condition:
1162
+ break
1163
+ self._count_loop_iteration()
1164
+ try:
1165
+ flow = self._execute_statements(statement.body, frame)
1166
+ except _ContinueSignal:
1167
+ continue
1168
+ except _BreakSignal:
1169
+ break
1170
+ if flow is not None:
1171
+ return flow
1172
+ continue
1173
+ if isinstance(statement, ast.Break):
1174
+ raise _BreakSignal
1175
+ if isinstance(statement, ast.Continue):
1176
+ raise _ContinueSignal
1177
+ if isinstance(statement, ast.Expr):
1178
+ if (
1179
+ isinstance(statement.value, ast.Call)
1180
+ and isinstance(statement.value.func, ast.Name)
1181
+ and statement.value.func.id == "print"
1182
+ ):
1183
+ if len(statement.value.args) > 20:
1184
+ self._unsupported(statement, "print supports at most 20 arguments.")
1185
+ values = [
1186
+ self._eval(argument, frame.variables, frame.function)
1187
+ for argument in statement.value.args
1188
+ ]
1189
+ output = " ".join(_python_string(value) for value in values)
1190
+ if len(self.output) + len(output) + 1 > MAX_SOURCE_CHARS:
1191
+ raise SimulationError("Program output exceeded the safe size limit.")
1192
+ self._append_step(
1193
+ _Step(
1194
+ kind="output",
1195
+ function_id=frame.function.info.id,
1196
+ function_name=frame.function.info.name,
1197
+ file=frame.function.info.file,
1198
+ line=statement.lineno,
1199
+ expression=ast.unparse(statement.value),
1200
+ prompt="What text does this print call output?",
1201
+ variables=dict(frame.variables),
1202
+ stack=self._stack(),
1203
+ expected=output,
1204
+ challenge=True,
1205
+ hint="Evaluate each print argument, convert it to text, then join them with spaces.",
1206
+ )
1207
+ )
1208
+ self.output += output + "\n"
1209
+ elif isinstance(statement.value, ast.Call):
1210
+ self._eval(statement.value, frame.variables, frame.function)
1211
+ else:
1212
+ value = self._eval(statement.value, frame.variables, frame.function)
1213
+ if _contains_arithmetic(statement.value):
1214
+ self._append_step(
1215
+ _Step(
1216
+ kind="arithmetic",
1217
+ function_id=frame.function.info.id,
1218
+ function_name=frame.function.info.name,
1219
+ file=frame.function.info.file,
1220
+ line=statement.lineno,
1221
+ expression=ast.unparse(statement.value),
1222
+ prompt="What value does this expression produce?",
1223
+ variables=dict(frame.variables),
1224
+ stack=self._stack(),
1225
+ expected=value,
1226
+ challenge=True,
1227
+ hint="Substitute the current values, then follow operator order.",
1228
+ )
1229
+ )
1230
+ continue
1231
+ self._unsupported(statement, "Unsupported statement.")
1232
+ return None
1233
+
1234
+ def _count_loop_iteration(self) -> None:
1235
+ self.loop_iterations += 1
1236
+ if self.loop_iterations > MAX_LOOP_ITERATIONS:
1237
+ raise SimulationError(
1238
+ "The program exceeds the safe limit of {} total loop iterations.".format(
1239
+ MAX_LOOP_ITERATIONS
1240
+ )
1241
+ )
1242
+
1243
+ def _eval(self, expression: Optional[ast.expr], variables: Dict[str, Any], function: _Function) -> Any:
1244
+ if expression is None:
1245
+ return None
1246
+ if isinstance(expression, ast.Constant):
1247
+ return _validate_json_value(expression.value, "literal")
1248
+ if isinstance(expression, ast.Name):
1249
+ if expression.id in variables:
1250
+ return variables[expression.id]
1251
+ if expression.id in self.local_names.get(function.info.id, set()):
1252
+ raise SimulationError(
1253
+ "Local name {!r} is not available in {}.".format(
1254
+ expression.id, function.info.name
1255
+ )
1256
+ )
1257
+ if expression.id in self.global_variables:
1258
+ return self.global_variables[expression.id]
1259
+ if expression.id not in variables:
1260
+ raise SimulationError(
1261
+ "Name {!r} is not available in {}.".format(
1262
+ expression.id, function.info.name
1263
+ )
1264
+ )
1265
+ if isinstance(expression, ast.List):
1266
+ return [self._eval(item, variables, function) for item in expression.elts]
1267
+ if isinstance(expression, ast.Tuple):
1268
+ return tuple(self._eval(item, variables, function) for item in expression.elts)
1269
+ if isinstance(expression, ast.Dict):
1270
+ try:
1271
+ return {
1272
+ self._eval(key, variables, function): self._eval(value, variables, function)
1273
+ for key, value in zip(expression.keys, expression.values)
1274
+ }
1275
+ except TypeError as error:
1276
+ raise SimulationError("Dictionary keys must be simple immutable values.") from error
1277
+ if isinstance(expression, ast.BinOp):
1278
+ left = self._eval(expression.left, variables, function)
1279
+ right = self._eval(expression.right, variables, function)
1280
+ return _apply_binary(expression.op, left, right)
1281
+ if isinstance(expression, ast.UnaryOp):
1282
+ value = self._eval(expression.operand, variables, function)
1283
+ try:
1284
+ result = _UNARY_OPERATORS[type(expression.op)](value)
1285
+ except (ArithmeticError, TypeError, ValueError) as error:
1286
+ raise SimulationError("Cannot safely calculate this expression: {}.".format(error)) from error
1287
+ return _validate_runtime_result(result)
1288
+ if isinstance(expression, ast.BoolOp):
1289
+ result = self._eval(expression.values[0], variables, function)
1290
+ for item in expression.values[1:]:
1291
+ if isinstance(expression.op, ast.And):
1292
+ if not result:
1293
+ break
1294
+ result = self._eval(item, variables, function)
1295
+ else:
1296
+ if result:
1297
+ break
1298
+ result = self._eval(item, variables, function)
1299
+ return _validate_runtime_result(result)
1300
+ if isinstance(expression, ast.Compare):
1301
+ left = self._eval(expression.left, variables, function)
1302
+ for operation, comparator in zip(expression.ops, expression.comparators):
1303
+ right = self._eval(comparator, variables, function)
1304
+ try:
1305
+ comparison = _COMPARISON_OPERATORS[type(operation)](left, right)
1306
+ except (TypeError, ValueError) as error:
1307
+ raise SimulationError("Cannot safely compare these values.") from error
1308
+ if not comparison:
1309
+ return False
1310
+ left = right
1311
+ return True
1312
+ if isinstance(expression, ast.Call):
1313
+ if (
1314
+ isinstance(expression.func, ast.Name)
1315
+ and expression.func.id in _SAFE_BUILTINS
1316
+ and self._resolve_call(expression, function) is None
1317
+ ):
1318
+ values = [
1319
+ self._eval(argument, variables, function)
1320
+ for argument in expression.args
1321
+ ]
1322
+ try:
1323
+ name = expression.func.id
1324
+ if name == "range":
1325
+ if not 1 <= len(values) <= 3 or any(
1326
+ not isinstance(value, int) or isinstance(value, bool)
1327
+ for value in values
1328
+ ):
1329
+ raise SimulationError("range() needs one to three integer arguments.")
1330
+ result = range(*values)
1331
+ if len(result) > MAX_LOOP_ITERATIONS:
1332
+ raise SimulationError(
1333
+ "range() is limited to {} values.".format(MAX_LOOP_ITERATIONS)
1334
+ )
1335
+ return list(result)
1336
+ if name == "len" and len(values) == 1:
1337
+ return len(values[0])
1338
+ if name == "int" and len(values) == 1:
1339
+ return _validate_runtime_result(int(values[0]))
1340
+ if name == "float" and len(values) == 1:
1341
+ return _validate_runtime_result(float(values[0]))
1342
+ if name == "str" and len(values) == 1:
1343
+ return _validate_runtime_result(_python_string(values[0]))
1344
+ if name == "abs" and len(values) == 1:
1345
+ return _validate_runtime_result(abs(values[0]))
1346
+ if name in {"min", "max"} and values:
1347
+ sequence = values[0] if len(values) == 1 else values
1348
+ result = (min if name == "min" else max)(sequence)
1349
+ return _validate_runtime_result(result)
1350
+ if name == "sum" and len(values) == 1:
1351
+ return _validate_runtime_result(sum(values[0]))
1352
+ except SimulationError:
1353
+ raise
1354
+ except (ArithmeticError, TypeError, ValueError, OverflowError) as error:
1355
+ raise SimulationError(
1356
+ "Cannot safely calculate {}(): {}.".format(name, error)
1357
+ ) from error
1358
+ raise SimulationError(
1359
+ "{}() was called with unsupported arguments.".format(name)
1360
+ )
1361
+ return self._eval_call(expression, variables, function)
1362
+ raise SimulationError(
1363
+ "This expression is outside the safe POV subset: {}.".format(
1364
+ type(expression).__name__
1365
+ )
1366
+ )
1367
+
1368
+ def _eval_call(self, call: ast.Call, variables: Dict[str, Any], caller: _Function) -> Any:
1369
+ if _is_string_format_call(call):
1370
+ return self._eval_string_format(call, variables, caller)
1371
+ if isinstance(call.func, ast.Name) and call.func.id == "print":
1372
+ self._unsupported(call, "print() is only supported as a standalone statement.")
1373
+ target_id = self._resolve_call(call, caller)
1374
+ if target_id is None or target_id not in self.functions:
1375
+ self._unsupported(call, "This call does not resolve to a project function.")
1376
+ target = self.functions[target_id]
1377
+ arguments: Dict[str, Any] = {}
1378
+ positional_values = [self._eval(argument, variables, caller) for argument in call.args]
1379
+ keyword_values = {
1380
+ keyword.arg: self._eval(keyword.value, variables, caller)
1381
+ for keyword in call.keywords
1382
+ }
1383
+ parameter_names = [argument.arg for argument in target.node.args.args]
1384
+ if len(positional_values) > len(parameter_names):
1385
+ raise SimulationError("Too many arguments in call to {}.".format(target.info.name))
1386
+ for name, value in zip(parameter_names, positional_values):
1387
+ arguments[name] = value
1388
+ for name, value in keyword_values.items():
1389
+ if name in arguments:
1390
+ raise SimulationError("Argument {!r} was provided twice.".format(name))
1391
+ arguments[name] = value
1392
+
1393
+ self._append_step(
1394
+ _Step(
1395
+ kind="function_call",
1396
+ function_id=caller.info.id,
1397
+ function_name=caller.info.name,
1398
+ file=caller.info.file,
1399
+ line=call.lineno,
1400
+ expression=ast.unparse(call.func),
1401
+ prompt="Which project function is being called here?",
1402
+ variables=dict(variables),
1403
+ stack=self._stack(),
1404
+ expected=target.info.name,
1405
+ challenge=True,
1406
+ hint="Look at the function name immediately before the parentheses.",
1407
+ choices=sorted({item.info.name for item in self.functions.values()}),
1408
+ target=target_id,
1409
+ )
1410
+ )
1411
+ result = self._invoke(target, arguments, caller.info.id)
1412
+ self._append_step(
1413
+ _Step(
1414
+ kind="call_return",
1415
+ function_id=caller.info.id,
1416
+ function_name=caller.info.name,
1417
+ file=caller.info.file,
1418
+ line=call.lineno,
1419
+ expression=ast.unparse(call) + " → " + _format_value(result),
1420
+ prompt="The called function returned. Its value is back with you.",
1421
+ variables=dict(variables),
1422
+ stack=self._stack(),
1423
+ expected=result,
1424
+ )
1425
+ )
1426
+ return result
1427
+
1428
+ def _eval_string_format(
1429
+ self,
1430
+ call: ast.Call,
1431
+ variables: Dict[str, Any],
1432
+ function: _Function,
1433
+ ) -> str:
1434
+ template = call.func.value.value
1435
+ positional = [self._eval(argument, variables, function) for argument in call.args]
1436
+ named = {
1437
+ keyword.arg: self._eval(keyword.value, variables, function)
1438
+ for keyword in call.keywords
1439
+ }
1440
+ automatic_index = 0
1441
+ result = []
1442
+ total_length = 0
1443
+ for literal, field_name, _, _ in Formatter().parse(template):
1444
+ result.append(literal)
1445
+ total_length += len(literal)
1446
+ if field_name is None:
1447
+ continue
1448
+ if field_name == "":
1449
+ value = positional[automatic_index]
1450
+ automatic_index += 1
1451
+ elif field_name.isdecimal():
1452
+ value = positional[int(field_name)]
1453
+ else:
1454
+ value = named[field_name]
1455
+ rendered = str(value)
1456
+ total_length += len(rendered)
1457
+ if total_length > 10000:
1458
+ raise SimulationError("Formatted strings are limited to 10,000 characters.")
1459
+ result.append(rendered)
1460
+ return _validate_runtime_result("".join(result))
1461
+
1462
+ def _append_step(self, step: _Step) -> None:
1463
+ if len(self.steps) >= MAX_STEPS:
1464
+ raise SimulationError(
1465
+ "The simulation reached its safe limit of {} steps.".format(MAX_STEPS)
1466
+ )
1467
+ self.steps.append(step)
1468
+
1469
+ def _stack(self) -> List[Dict[str, Any]]:
1470
+ return [
1471
+ {
1472
+ "function_id": frame.function.info.id,
1473
+ "function_name": frame.function.info.name,
1474
+ "variables": dict(frame.variables),
1475
+ }
1476
+ for frame in self.frames
1477
+ ]
1478
+
1479
+
1480
+ _BINARY_OPERATORS = {
1481
+ ast.Add: operator.add,
1482
+ ast.Sub: operator.sub,
1483
+ ast.Mult: operator.mul,
1484
+ ast.Div: operator.truediv,
1485
+ ast.FloorDiv: operator.floordiv,
1486
+ ast.Mod: operator.mod,
1487
+ ast.Pow: operator.pow,
1488
+ }
1489
+ _AUGMENTED_OPERATORS = {
1490
+ ast.Add: "+=",
1491
+ ast.Sub: "-=",
1492
+ ast.Mult: "*=",
1493
+ ast.Div: "/=",
1494
+ ast.FloorDiv: "//=",
1495
+ ast.Mod: "%=",
1496
+ ast.Pow: "**=",
1497
+ }
1498
+ _SAFE_BUILTINS = frozenset(
1499
+ {"range", "len", "int", "float", "str", "abs", "min", "max", "sum"}
1500
+ )
1501
+
1502
+
1503
+ def _first_meaningful_operation(statements: Sequence[ast.stmt]) -> Optional[str]:
1504
+ for statement in statements:
1505
+ if isinstance(statement, ast.If):
1506
+ return "branch"
1507
+ if isinstance(statement, (ast.For, ast.While)):
1508
+ return "loop"
1509
+ if isinstance(statement, ast.AugAssign):
1510
+ return "variable update"
1511
+ if isinstance(statement, (ast.Assign, ast.AnnAssign)):
1512
+ expression = statement.value
1513
+ if isinstance(expression, ast.Call):
1514
+ if isinstance(expression.func, ast.Name) and expression.func.id == "print":
1515
+ return "output"
1516
+ if not (
1517
+ isinstance(expression.func, ast.Name)
1518
+ and expression.func.id in _SAFE_BUILTINS
1519
+ ):
1520
+ return "function call"
1521
+ if expression is not None and _contains_arithmetic(expression):
1522
+ return "variable update"
1523
+ if isinstance(statement, ast.Expr):
1524
+ expression = statement.value
1525
+ if isinstance(expression, ast.Call):
1526
+ if isinstance(expression.func, ast.Name) and expression.func.id == "print":
1527
+ return "output"
1528
+ return "function call"
1529
+ if _contains_arithmetic(expression):
1530
+ return "variable update"
1531
+ return None
1532
+
1533
+
1534
+ def _is_string_format_call(expression: ast.Call) -> bool:
1535
+ return (
1536
+ isinstance(expression.func, ast.Attribute)
1537
+ and expression.func.attr == "format"
1538
+ and isinstance(expression.func.value, ast.Constant)
1539
+ and isinstance(expression.func.value.value, str)
1540
+ )
1541
+
1542
+
1543
+ _UNARY_OPERATORS = {
1544
+ ast.UAdd: operator.pos,
1545
+ ast.USub: operator.neg,
1546
+ ast.Not: operator.not_,
1547
+ }
1548
+ _COMPARISON_OPERATORS = {
1549
+ ast.Eq: operator.eq,
1550
+ ast.NotEq: operator.ne,
1551
+ ast.Lt: operator.lt,
1552
+ ast.LtE: operator.le,
1553
+ ast.Gt: operator.gt,
1554
+ ast.GtE: operator.ge,
1555
+ ast.In: lambda left, right: left in right,
1556
+ ast.NotIn: lambda left, right: left not in right,
1557
+ }
1558
+ _BINARY_OPERATORS = {key: value for key, value in _BINARY_OPERATORS.items()}
1559
+
1560
+
1561
+ def _validate_runtime_result(value: Any) -> Any:
1562
+ safe = _validate_json_value(
1563
+ list(value) if isinstance(value, tuple) else value,
1564
+ "result",
1565
+ )
1566
+ return safe
1567
+
1568
+
1569
+ def _json_safe(value: Any) -> Any:
1570
+ if isinstance(value, tuple):
1571
+ return [_json_safe(item) for item in value]
1572
+ if isinstance(value, list):
1573
+ return [_json_safe(item) for item in value]
1574
+ if isinstance(value, dict):
1575
+ return {str(key): _json_safe(item) for key, item in value.items()}
1576
+ if value is None or isinstance(value, (str, int, float, bool)):
1577
+ return value
1578
+ return repr(value)
1579
+
1580
+
1581
+ def _answers_equal(answer: Any, expected: Any) -> bool:
1582
+ if isinstance(expected, bool):
1583
+ return isinstance(answer, bool) and answer is expected
1584
+ if isinstance(expected, (int, float)) and not isinstance(expected, bool):
1585
+ return isinstance(answer, (int, float)) and not isinstance(answer, bool) and answer == expected
1586
+ return answer == _json_safe(expected)
1587
+
1588
+
1589
+ def _format_mapping(values: Dict[str, Any]) -> str:
1590
+ return ", ".join(
1591
+ "{}={}".format(name, _format_value(value))
1592
+ for name, value in values.items()
1593
+ )
1594
+
1595
+
1596
+ def _format_value(value: Any) -> str:
1597
+ return json.dumps(_json_safe(value), ensure_ascii=False, sort_keys=True)
1598
+
1599
+
1600
+ def _python_string(value: Any) -> str:
1601
+ if isinstance(value, str):
1602
+ return value
1603
+ if isinstance(value, bool):
1604
+ return "True" if value else "False"
1605
+ if value is None:
1606
+ return "None"
1607
+ return repr(_json_safe(value))
1608
+
1609
+
1610
+ def _apply_binary(operation: ast.operator, left: Any, right: Any) -> Any:
1611
+ if isinstance(operation, ast.Pow) and isinstance(right, (int, float)) and abs(right) > 10:
1612
+ raise SimulationError("Exponents must be between -10 and 10 in the POV simulator.")
1613
+ if isinstance(operation, ast.Mult) and (
1614
+ isinstance(left, (str, list, tuple)) or isinstance(right, (str, list, tuple))
1615
+ ):
1616
+ sequence = left if isinstance(left, (str, list, tuple)) else right
1617
+ count = right if sequence is left else left
1618
+ if not isinstance(count, int) or isinstance(count, bool) or count < 0 or count > MAX_COLLECTION_ITEMS:
1619
+ raise SimulationError("Repeated values are limited to 100 items.")
1620
+ try:
1621
+ result = _BINARY_OPERATORS[type(operation)](left, right)
1622
+ except (ArithmeticError, TypeError, ValueError, OverflowError) as error:
1623
+ raise SimulationError(
1624
+ "Cannot safely calculate this expression: {}.".format(error)
1625
+ ) from error
1626
+ return _validate_runtime_result(result)
1627
+
1628
+
1629
+ def _contains_arithmetic(expression: ast.AST) -> bool:
1630
+ return any(isinstance(node, ast.BinOp) for node in ast.walk(expression))