prism-code-workspace 1.0.0__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- prism_code_workspace-1.0.0.dist-info/METADATA +272 -0
- prism_code_workspace-1.0.0.dist-info/RECORD +30 -0
- prism_code_workspace-1.0.0.dist-info/WHEEL +4 -0
- prism_code_workspace-1.0.0.dist-info/entry_points.txt +3 -0
- prism_code_workspace-1.0.0.dist-info/licenses/LICENSE +21 -0
- python_app/__init__.py +3 -0
- python_app/ai.py +225 -0
- python_app/analysis.py +953 -0
- python_app/compare.py +685 -0
- python_app/compare_engine.py +284 -0
- python_app/compiled_analysis.py +727 -0
- python_app/desktop.py +181 -0
- python_app/function_pov/__init__.py +16 -0
- python_app/function_pov/analyzer.py +464 -0
- python_app/function_pov/graph.py +50 -0
- python_app/function_pov/models.py +53 -0
- python_app/function_pov/pov/__init__.py +17 -0
- python_app/function_pov/pov/engine.py +1630 -0
- python_app/function_pov/pov/exercises.py +1263 -0
- python_app/function_pov_ui.py +1749 -0
- python_app/i18n.py +570 -0
- python_app/installer.nsi +70 -0
- python_app/installer_runtime.nsi +70 -0
- python_app/js_analysis.py +709 -0
- python_app/launch.py +6 -0
- python_app/launch_native.py +14 -0
- python_app/metrics_advisor.py +79 -0
- python_app/native_app.py +1709 -0
- python_app/requirements.txt +7 -0
- python_app/server.py +453 -0
|
@@ -0,0 +1,1263 @@
|
|
|
1
|
+
"""Deterministic, safe exercise variants for Function POV."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import ast
|
|
6
|
+
import copy
|
|
7
|
+
import json
|
|
8
|
+
import math
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from typing import Any, Iterator
|
|
11
|
+
|
|
12
|
+
from ..analyzer import analyze_source
|
|
13
|
+
from .engine import (
|
|
14
|
+
PovSimulation,
|
|
15
|
+
SimulationError,
|
|
16
|
+
build_program_simulation_from_source,
|
|
17
|
+
build_simulation_from_source,
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
MAX_GENERATION_ATTEMPTS = 64
|
|
21
|
+
|
|
22
|
+
|
|
23
|
+
class ExerciseGenerationError(ValueError):
|
|
24
|
+
"""Raised when no supported, unused exercise can be generated."""
|
|
25
|
+
|
|
26
|
+
|
|
27
|
+
@dataclass(frozen=True)
|
|
28
|
+
class GeneratedExercise:
|
|
29
|
+
level: str
|
|
30
|
+
mode: str
|
|
31
|
+
source: str
|
|
32
|
+
filename: str
|
|
33
|
+
function_id: str | None
|
|
34
|
+
arguments: dict[str, Any]
|
|
35
|
+
concepts: tuple[str, ...]
|
|
36
|
+
simulation: PovSimulation
|
|
37
|
+
logic_change: str | None = None
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
class PracticeExerciseGenerator:
|
|
41
|
+
"""Generate bounded variants without executing generated or user code."""
|
|
42
|
+
|
|
43
|
+
def __init__(self) -> None:
|
|
44
|
+
self._considered: set[str] = set()
|
|
45
|
+
|
|
46
|
+
def similar_logic_availability(
|
|
47
|
+
self,
|
|
48
|
+
mode: str,
|
|
49
|
+
source: str,
|
|
50
|
+
filename: str,
|
|
51
|
+
function_id: str | None = None,
|
|
52
|
+
arguments: dict[str, Any] | None = None,
|
|
53
|
+
) -> str | None:
|
|
54
|
+
candidates = self._similar_logic_candidates(
|
|
55
|
+
mode, source, filename, function_id, arguments or {}
|
|
56
|
+
)
|
|
57
|
+
found_pattern = False
|
|
58
|
+
for candidate_source, candidate_function, candidate_arguments, _ in candidates:
|
|
59
|
+
if _logic_change_explanation(
|
|
60
|
+
source,
|
|
61
|
+
candidate_source,
|
|
62
|
+
mode,
|
|
63
|
+
function_id,
|
|
64
|
+
filename,
|
|
65
|
+
) is None:
|
|
66
|
+
continue
|
|
67
|
+
found_pattern = True
|
|
68
|
+
key = self._variant_key(
|
|
69
|
+
mode, candidate_source, candidate_function, candidate_arguments
|
|
70
|
+
)
|
|
71
|
+
if key in self._considered:
|
|
72
|
+
continue
|
|
73
|
+
try:
|
|
74
|
+
simulation = self._build_simulation(
|
|
75
|
+
mode,
|
|
76
|
+
candidate_source,
|
|
77
|
+
filename,
|
|
78
|
+
candidate_function,
|
|
79
|
+
candidate_arguments,
|
|
80
|
+
)
|
|
81
|
+
except SimulationError:
|
|
82
|
+
continue
|
|
83
|
+
if any(step.challenge for step in simulation.steps):
|
|
84
|
+
return None
|
|
85
|
+
if not found_pattern:
|
|
86
|
+
return "This code does not match a supported Similar Logic pattern."
|
|
87
|
+
return "No unused Similar Logic exercise passed safe simulation."
|
|
88
|
+
|
|
89
|
+
def generate(
|
|
90
|
+
self,
|
|
91
|
+
level: str,
|
|
92
|
+
mode: str,
|
|
93
|
+
source: str,
|
|
94
|
+
filename: str,
|
|
95
|
+
function_id: str | None = None,
|
|
96
|
+
arguments: dict[str, Any] | None = None,
|
|
97
|
+
) -> GeneratedExercise:
|
|
98
|
+
if mode not in {"code", "function"}:
|
|
99
|
+
raise ExerciseGenerationError("This practice mode is not supported.")
|
|
100
|
+
if level == "new_values":
|
|
101
|
+
candidates = self._new_value_candidates(
|
|
102
|
+
mode, source, filename, function_id, arguments or {}
|
|
103
|
+
)
|
|
104
|
+
elif level == "similar_logic":
|
|
105
|
+
candidates = self._similar_logic_candidates(
|
|
106
|
+
mode, source, filename, function_id, arguments or {}
|
|
107
|
+
)
|
|
108
|
+
else:
|
|
109
|
+
raise ExerciseGenerationError("This exercise level is not supported.")
|
|
110
|
+
|
|
111
|
+
supported_pattern = False
|
|
112
|
+
generation_attempts = 0
|
|
113
|
+
attempt_limit_reached = False
|
|
114
|
+
for candidate_source, candidate_function, candidate_arguments, concepts in candidates:
|
|
115
|
+
logic_change = None
|
|
116
|
+
if level == "similar_logic":
|
|
117
|
+
logic_change = _logic_change_explanation(
|
|
118
|
+
source,
|
|
119
|
+
candidate_source,
|
|
120
|
+
mode,
|
|
121
|
+
function_id,
|
|
122
|
+
filename,
|
|
123
|
+
)
|
|
124
|
+
if logic_change is None:
|
|
125
|
+
continue
|
|
126
|
+
supported_pattern = True
|
|
127
|
+
key = self._variant_key(
|
|
128
|
+
mode, candidate_source, candidate_function, candidate_arguments
|
|
129
|
+
)
|
|
130
|
+
if key in self._considered:
|
|
131
|
+
continue
|
|
132
|
+
generation_attempts += 1
|
|
133
|
+
if generation_attempts > MAX_GENERATION_ATTEMPTS:
|
|
134
|
+
attempt_limit_reached = True
|
|
135
|
+
break
|
|
136
|
+
self._considered.add(key)
|
|
137
|
+
try:
|
|
138
|
+
simulation = self._build_simulation(
|
|
139
|
+
mode,
|
|
140
|
+
candidate_source,
|
|
141
|
+
filename,
|
|
142
|
+
candidate_function,
|
|
143
|
+
candidate_arguments,
|
|
144
|
+
)
|
|
145
|
+
except SimulationError:
|
|
146
|
+
continue
|
|
147
|
+
if not any(step.challenge for step in simulation.steps):
|
|
148
|
+
continue
|
|
149
|
+
return GeneratedExercise(
|
|
150
|
+
level=level,
|
|
151
|
+
mode=mode,
|
|
152
|
+
source=candidate_source,
|
|
153
|
+
filename=filename,
|
|
154
|
+
function_id=candidate_function,
|
|
155
|
+
arguments=dict(candidate_arguments),
|
|
156
|
+
concepts=concepts,
|
|
157
|
+
simulation=simulation,
|
|
158
|
+
logic_change=logic_change,
|
|
159
|
+
)
|
|
160
|
+
|
|
161
|
+
if level == "similar_logic" and not supported_pattern:
|
|
162
|
+
raise ExerciseGenerationError(
|
|
163
|
+
"This code does not match a supported Similar Logic pattern."
|
|
164
|
+
)
|
|
165
|
+
if attempt_limit_reached:
|
|
166
|
+
raise ExerciseGenerationError(
|
|
167
|
+
"Exercise search reached its safe candidate limit without finding a new variant."
|
|
168
|
+
)
|
|
169
|
+
if level == "new_values":
|
|
170
|
+
raise ExerciseGenerationError(
|
|
171
|
+
"No safe, unused New Values exercise is available for this code."
|
|
172
|
+
)
|
|
173
|
+
raise ExerciseGenerationError(
|
|
174
|
+
"No unused Similar Logic exercise passed safe simulation."
|
|
175
|
+
)
|
|
176
|
+
|
|
177
|
+
@staticmethod
|
|
178
|
+
def _variant_key(
|
|
179
|
+
mode: str,
|
|
180
|
+
source: str,
|
|
181
|
+
function_id: str | None,
|
|
182
|
+
arguments: dict[str, Any],
|
|
183
|
+
) -> str:
|
|
184
|
+
return json.dumps(
|
|
185
|
+
[mode, source, function_id, arguments],
|
|
186
|
+
sort_keys=True,
|
|
187
|
+
ensure_ascii=False,
|
|
188
|
+
separators=(",", ":"),
|
|
189
|
+
)
|
|
190
|
+
|
|
191
|
+
@staticmethod
|
|
192
|
+
def _build_simulation(
|
|
193
|
+
mode: str,
|
|
194
|
+
source: str,
|
|
195
|
+
filename: str,
|
|
196
|
+
function_id: str | None,
|
|
197
|
+
arguments: dict[str, Any],
|
|
198
|
+
) -> PovSimulation:
|
|
199
|
+
if mode == "code":
|
|
200
|
+
return build_program_simulation_from_source(source, filename)
|
|
201
|
+
if function_id is None:
|
|
202
|
+
raise SimulationError("A function must be selected for this exercise.")
|
|
203
|
+
analysis = analyze_source(source, filename)
|
|
204
|
+
selected = next(
|
|
205
|
+
(function for function in analysis.functions if function.id == function_id),
|
|
206
|
+
None,
|
|
207
|
+
)
|
|
208
|
+
if selected is None:
|
|
209
|
+
selected = next(
|
|
210
|
+
(
|
|
211
|
+
function for function in analysis.functions
|
|
212
|
+
if function.name == function_id
|
|
213
|
+
),
|
|
214
|
+
None,
|
|
215
|
+
)
|
|
216
|
+
if selected is None:
|
|
217
|
+
raise SimulationError("The generated function could not be resolved.")
|
|
218
|
+
return build_simulation_from_source(
|
|
219
|
+
source, selected.id, arguments, filename
|
|
220
|
+
)
|
|
221
|
+
|
|
222
|
+
def _new_value_candidates(
|
|
223
|
+
self,
|
|
224
|
+
mode: str,
|
|
225
|
+
source: str,
|
|
226
|
+
filename: str,
|
|
227
|
+
function_id: str | None,
|
|
228
|
+
arguments: dict[str, Any],
|
|
229
|
+
) -> Iterator[tuple[str, str | None, dict[str, Any], tuple[str, ...]]]:
|
|
230
|
+
if mode == "code":
|
|
231
|
+
yield from self._program_value_candidates(source)
|
|
232
|
+
return
|
|
233
|
+
if function_id is None:
|
|
234
|
+
return
|
|
235
|
+
effective = self._effective_function_arguments(
|
|
236
|
+
source, filename, function_id, arguments
|
|
237
|
+
)
|
|
238
|
+
concepts = _selected_function_concepts(source, filename, function_id)
|
|
239
|
+
function = _selected_function_node(source, filename, function_id)
|
|
240
|
+
if function is not None:
|
|
241
|
+
for name, variant in _branch_boundary_candidates(function, effective):
|
|
242
|
+
updated = dict(effective)
|
|
243
|
+
updated[name] = variant
|
|
244
|
+
yield source, function_id, updated, concepts
|
|
245
|
+
for name, value in effective.items():
|
|
246
|
+
for variant in _value_variants(value):
|
|
247
|
+
updated = dict(effective)
|
|
248
|
+
updated[name] = variant
|
|
249
|
+
yield source, function_id, updated, concepts
|
|
250
|
+
|
|
251
|
+
@staticmethod
|
|
252
|
+
def _program_value_candidates(
|
|
253
|
+
source: str,
|
|
254
|
+
) -> Iterator[tuple[str, str | None, dict[str, Any], tuple[str, ...]]]:
|
|
255
|
+
try:
|
|
256
|
+
module = ast.parse(source)
|
|
257
|
+
except SyntaxError:
|
|
258
|
+
return
|
|
259
|
+
updated_names = {
|
|
260
|
+
node.target.id
|
|
261
|
+
for node in ast.walk(module)
|
|
262
|
+
if isinstance(node, ast.AugAssign) and isinstance(node.target, ast.Name)
|
|
263
|
+
}
|
|
264
|
+
concepts = _concepts(module)
|
|
265
|
+
input_nodes: dict[str, ast.AST] = {}
|
|
266
|
+
input_values: dict[str, Any] = {}
|
|
267
|
+
for statement in module.body:
|
|
268
|
+
if isinstance(statement, ast.Assign):
|
|
269
|
+
if len(statement.targets) != 1 or not isinstance(statement.targets[0], ast.Name):
|
|
270
|
+
continue
|
|
271
|
+
name = statement.targets[0].id
|
|
272
|
+
value_node = statement.value
|
|
273
|
+
elif isinstance(statement, ast.AnnAssign):
|
|
274
|
+
if not isinstance(statement.target, ast.Name) or statement.value is None:
|
|
275
|
+
continue
|
|
276
|
+
name = statement.target.id
|
|
277
|
+
value_node = statement.value
|
|
278
|
+
else:
|
|
279
|
+
continue
|
|
280
|
+
if name in updated_names:
|
|
281
|
+
continue
|
|
282
|
+
try:
|
|
283
|
+
value = ast.literal_eval(value_node)
|
|
284
|
+
except (ValueError, TypeError):
|
|
285
|
+
continue
|
|
286
|
+
input_nodes[name] = value_node
|
|
287
|
+
input_values[name] = value
|
|
288
|
+
for name, variant in _branch_boundary_candidates(module, input_values):
|
|
289
|
+
candidate = _replace_source_segment(
|
|
290
|
+
source, input_nodes[name], repr(variant)
|
|
291
|
+
)
|
|
292
|
+
if candidate is not None:
|
|
293
|
+
yield candidate, None, {}, concepts
|
|
294
|
+
for name, value_node in input_nodes.items():
|
|
295
|
+
value = input_values[name]
|
|
296
|
+
for variant in _value_variants(value):
|
|
297
|
+
candidate = _replace_source_segment(source, value_node, repr(variant))
|
|
298
|
+
if candidate is not None:
|
|
299
|
+
yield candidate, None, {}, concepts
|
|
300
|
+
for node in ast.walk(module):
|
|
301
|
+
if (
|
|
302
|
+
not isinstance(node, ast.Call)
|
|
303
|
+
or not isinstance(node.func, ast.Name)
|
|
304
|
+
or node.func.id != "range"
|
|
305
|
+
):
|
|
306
|
+
continue
|
|
307
|
+
for argument in node.args[:2]:
|
|
308
|
+
try:
|
|
309
|
+
value = ast.literal_eval(argument)
|
|
310
|
+
except (ValueError, TypeError):
|
|
311
|
+
continue
|
|
312
|
+
if isinstance(value, bool) or not isinstance(value, int):
|
|
313
|
+
continue
|
|
314
|
+
for variant in _value_variants(value):
|
|
315
|
+
candidate = _replace_source_segment(
|
|
316
|
+
source, argument, repr(variant)
|
|
317
|
+
)
|
|
318
|
+
if candidate is not None:
|
|
319
|
+
yield candidate, None, {}, concepts
|
|
320
|
+
|
|
321
|
+
@staticmethod
|
|
322
|
+
def _effective_function_arguments(
|
|
323
|
+
source: str,
|
|
324
|
+
filename: str,
|
|
325
|
+
function_id: str,
|
|
326
|
+
arguments: dict[str, Any],
|
|
327
|
+
) -> dict[str, Any]:
|
|
328
|
+
analysis = analyze_source(source, filename)
|
|
329
|
+
function_info = next(
|
|
330
|
+
(item for item in analysis.functions if item.id == function_id),
|
|
331
|
+
None,
|
|
332
|
+
)
|
|
333
|
+
if function_info is None:
|
|
334
|
+
function_info = next(
|
|
335
|
+
(item for item in analysis.functions if item.name == function_id),
|
|
336
|
+
None,
|
|
337
|
+
)
|
|
338
|
+
if function_info is None:
|
|
339
|
+
return dict(arguments)
|
|
340
|
+
try:
|
|
341
|
+
module = ast.parse(source, filename=filename)
|
|
342
|
+
except SyntaxError:
|
|
343
|
+
return dict(arguments)
|
|
344
|
+
function = next(
|
|
345
|
+
(
|
|
346
|
+
node for node in module.body
|
|
347
|
+
if isinstance(node, ast.FunctionDef)
|
|
348
|
+
and node.name == function_info.name
|
|
349
|
+
),
|
|
350
|
+
None,
|
|
351
|
+
)
|
|
352
|
+
if function is None:
|
|
353
|
+
return dict(arguments)
|
|
354
|
+
names = [item.arg for item in function.args.args]
|
|
355
|
+
defaults: dict[str, Any] = {}
|
|
356
|
+
default_names = names[-len(function.args.defaults):] if function.args.defaults else []
|
|
357
|
+
for name, node in zip(default_names, function.args.defaults):
|
|
358
|
+
try:
|
|
359
|
+
defaults[name] = ast.literal_eval(node)
|
|
360
|
+
except (ValueError, TypeError):
|
|
361
|
+
continue
|
|
362
|
+
effective: dict[str, Any] = {}
|
|
363
|
+
for name in names:
|
|
364
|
+
if name in arguments:
|
|
365
|
+
effective[name] = arguments[name]
|
|
366
|
+
elif name in defaults:
|
|
367
|
+
effective[name] = defaults[name]
|
|
368
|
+
return effective
|
|
369
|
+
|
|
370
|
+
def _similar_logic_candidates(
|
|
371
|
+
self,
|
|
372
|
+
mode: str,
|
|
373
|
+
source: str,
|
|
374
|
+
filename: str,
|
|
375
|
+
function_id: str | None,
|
|
376
|
+
arguments: dict[str, Any],
|
|
377
|
+
) -> Iterator[tuple[str, str | None, dict[str, Any], tuple[str, ...]]]:
|
|
378
|
+
if mode == "code":
|
|
379
|
+
yield from self._program_logic_templates(source)
|
|
380
|
+
return
|
|
381
|
+
if function_id is None:
|
|
382
|
+
return
|
|
383
|
+
yield from self._function_logic_templates(
|
|
384
|
+
source, filename, function_id, arguments
|
|
385
|
+
)
|
|
386
|
+
|
|
387
|
+
@staticmethod
|
|
388
|
+
def _program_logic_templates(
|
|
389
|
+
source: str,
|
|
390
|
+
) -> Iterator[tuple[str, str | None, dict[str, Any], tuple[str, ...]]]:
|
|
391
|
+
try:
|
|
392
|
+
module = ast.parse(source)
|
|
393
|
+
except SyntaxError:
|
|
394
|
+
return
|
|
395
|
+
if any(isinstance(node, ast.FunctionDef) for node in module.body):
|
|
396
|
+
return
|
|
397
|
+
body = _module_body_without_docstring(module.body)
|
|
398
|
+
nodes = list(ast.walk(module))
|
|
399
|
+
fors = [node for node in nodes if isinstance(node, ast.For)]
|
|
400
|
+
whiles = [node for node in nodes if isinstance(node, ast.While)]
|
|
401
|
+
branches = [node for node in nodes if isinstance(node, ast.If)]
|
|
402
|
+
updates = [node for node in nodes if isinstance(node, ast.AugAssign)]
|
|
403
|
+
prints = [
|
|
404
|
+
node for node in nodes
|
|
405
|
+
if isinstance(node, ast.Call)
|
|
406
|
+
and isinstance(node.func, ast.Name)
|
|
407
|
+
and node.func.id == "print"
|
|
408
|
+
]
|
|
409
|
+
other_calls = [
|
|
410
|
+
node for node in nodes
|
|
411
|
+
if isinstance(node, ast.Call)
|
|
412
|
+
and not (
|
|
413
|
+
isinstance(node.func, ast.Name)
|
|
414
|
+
and node.func.id in {"print", "range"}
|
|
415
|
+
)
|
|
416
|
+
]
|
|
417
|
+
if other_calls:
|
|
418
|
+
return
|
|
419
|
+
|
|
420
|
+
if (
|
|
421
|
+
len(prints) == 1
|
|
422
|
+
and len(fors) == 1
|
|
423
|
+
and not whiles
|
|
424
|
+
and len(branches) == 1
|
|
425
|
+
and len(updates) == 1
|
|
426
|
+
and len(body) == 4
|
|
427
|
+
and isinstance(body[0], (ast.Assign, ast.AnnAssign))
|
|
428
|
+
and isinstance(body[1], (ast.Assign, ast.AnnAssign))
|
|
429
|
+
and body[2] is fors[0]
|
|
430
|
+
and isinstance(body[3], ast.Expr)
|
|
431
|
+
and len(fors[0].body) == 1
|
|
432
|
+
and isinstance(fors[0].body[0], ast.If)
|
|
433
|
+
and len(fors[0].body[0].body) == 1
|
|
434
|
+
and isinstance(fors[0].body[0].body[0], ast.AugAssign)
|
|
435
|
+
and not fors[0].body[0].orelse
|
|
436
|
+
and isinstance(fors[0].iter, ast.Name)
|
|
437
|
+
and branches[0] in list(ast.walk(fors[0]))
|
|
438
|
+
and updates[0] in list(ast.walk(branches[0]))
|
|
439
|
+
):
|
|
440
|
+
templates = (
|
|
441
|
+
(
|
|
442
|
+
"prices = [5, 2, 8]\n"
|
|
443
|
+
"total = 0\n"
|
|
444
|
+
"for price in prices:\n"
|
|
445
|
+
" if price >= 5:\n"
|
|
446
|
+
" total += price + 1\n"
|
|
447
|
+
"print(total)\n",
|
|
448
|
+
("condition", "loop", "variable update", "arithmetic", "output"),
|
|
449
|
+
),
|
|
450
|
+
(
|
|
451
|
+
"scores = [4, 9, 6]\n"
|
|
452
|
+
"passed = 0\n"
|
|
453
|
+
"for score in scores:\n"
|
|
454
|
+
" if score >= 6:\n"
|
|
455
|
+
" passed += score + 1\n"
|
|
456
|
+
"print(passed)\n",
|
|
457
|
+
("condition", "loop", "variable update", "arithmetic", "output"),
|
|
458
|
+
),
|
|
459
|
+
)
|
|
460
|
+
for template, concepts in templates:
|
|
461
|
+
yield template, None, {}, concepts
|
|
462
|
+
return
|
|
463
|
+
|
|
464
|
+
if (
|
|
465
|
+
len(prints) == 1
|
|
466
|
+
and len(fors) == 1
|
|
467
|
+
and not whiles
|
|
468
|
+
and not branches
|
|
469
|
+
and len(updates) == 1
|
|
470
|
+
and len(body) == 4
|
|
471
|
+
and isinstance(body[0], (ast.Assign, ast.AnnAssign))
|
|
472
|
+
and isinstance(body[1], (ast.Assign, ast.AnnAssign))
|
|
473
|
+
and body[2] is fors[0]
|
|
474
|
+
and isinstance(body[3], ast.Expr)
|
|
475
|
+
and len(fors[0].body) == 1
|
|
476
|
+
and isinstance(fors[0].body[0], ast.AugAssign)
|
|
477
|
+
and isinstance(fors[0].iter, ast.Name)
|
|
478
|
+
):
|
|
479
|
+
templates = (
|
|
480
|
+
(
|
|
481
|
+
"values = [3, 1, 4]\n"
|
|
482
|
+
"total = 0\n"
|
|
483
|
+
"for value in values:\n"
|
|
484
|
+
" total += value + 1\n"
|
|
485
|
+
"print(total)\n",
|
|
486
|
+
("loop", "variable update", "arithmetic", "output"),
|
|
487
|
+
),
|
|
488
|
+
(
|
|
489
|
+
"values = [2, 5, 3]\n"
|
|
490
|
+
"total = 0\n"
|
|
491
|
+
"for value in values:\n"
|
|
492
|
+
" total += value - 1\n"
|
|
493
|
+
"print(total)\n",
|
|
494
|
+
("loop", "variable update", "arithmetic", "output"),
|
|
495
|
+
),
|
|
496
|
+
)
|
|
497
|
+
for template, concepts in templates:
|
|
498
|
+
yield template, None, {}, concepts
|
|
499
|
+
return
|
|
500
|
+
|
|
501
|
+
if (
|
|
502
|
+
len(prints) == 1
|
|
503
|
+
and len(whiles) == 1
|
|
504
|
+
and not fors
|
|
505
|
+
and not branches
|
|
506
|
+
and len(updates) >= 2
|
|
507
|
+
and len(body) == 4
|
|
508
|
+
and isinstance(body[0], (ast.Assign, ast.AnnAssign))
|
|
509
|
+
and isinstance(body[1], (ast.Assign, ast.AnnAssign))
|
|
510
|
+
and body[2] is whiles[0]
|
|
511
|
+
and isinstance(body[3], ast.Expr)
|
|
512
|
+
and len(whiles[0].body) == 2
|
|
513
|
+
and all(isinstance(item, ast.AugAssign) for item in whiles[0].body)
|
|
514
|
+
):
|
|
515
|
+
templates = (
|
|
516
|
+
(
|
|
517
|
+
"count = 3\n"
|
|
518
|
+
"total = 0\n"
|
|
519
|
+
"while count > 0:\n"
|
|
520
|
+
" total += count + 1\n"
|
|
521
|
+
" count -= 1\n"
|
|
522
|
+
"print(total)\n",
|
|
523
|
+
("loop", "condition", "variable update", "arithmetic", "output"),
|
|
524
|
+
),
|
|
525
|
+
(
|
|
526
|
+
"count = 4\n"
|
|
527
|
+
"total = 0\n"
|
|
528
|
+
"while count > 0:\n"
|
|
529
|
+
" total += count - 1\n"
|
|
530
|
+
" count -= 1\n"
|
|
531
|
+
"print(total)\n",
|
|
532
|
+
("loop", "condition", "variable update", "arithmetic", "output"),
|
|
533
|
+
),
|
|
534
|
+
)
|
|
535
|
+
for template, concepts in templates:
|
|
536
|
+
yield template, None, {}, concepts
|
|
537
|
+
return
|
|
538
|
+
|
|
539
|
+
if (
|
|
540
|
+
len(prints) >= 1
|
|
541
|
+
and len(branches) == 1
|
|
542
|
+
and not fors and not whiles and not updates
|
|
543
|
+
and len(body) == 2
|
|
544
|
+
and isinstance(body[0], (ast.Assign, ast.AnnAssign))
|
|
545
|
+
and body[1] is branches[0]
|
|
546
|
+
and branches[0].body
|
|
547
|
+
and branches[0].orelse
|
|
548
|
+
and all(
|
|
549
|
+
isinstance(item, ast.Expr)
|
|
550
|
+
and isinstance(item.value, ast.Call)
|
|
551
|
+
and isinstance(item.value.func, ast.Name)
|
|
552
|
+
and item.value.func.id == "print"
|
|
553
|
+
for item in branches[0].body + branches[0].orelse
|
|
554
|
+
)
|
|
555
|
+
):
|
|
556
|
+
templates = (
|
|
557
|
+
(
|
|
558
|
+
"score = 6\n"
|
|
559
|
+
"if score >= 5:\n"
|
|
560
|
+
" print('ready')\n"
|
|
561
|
+
"else:\n"
|
|
562
|
+
" print('keep practising')\n",
|
|
563
|
+
("condition", "branch", "output"),
|
|
564
|
+
),
|
|
565
|
+
(
|
|
566
|
+
"temperature = 2\n"
|
|
567
|
+
"if temperature > 0:\n"
|
|
568
|
+
" print('above zero')\n"
|
|
569
|
+
"else:\n"
|
|
570
|
+
" print('zero or below')\n",
|
|
571
|
+
("condition", "branch", "output"),
|
|
572
|
+
),
|
|
573
|
+
)
|
|
574
|
+
for template, concepts in templates:
|
|
575
|
+
yield template, None, {}, concepts
|
|
576
|
+
|
|
577
|
+
@staticmethod
|
|
578
|
+
def _function_logic_templates(
|
|
579
|
+
source: str,
|
|
580
|
+
filename: str,
|
|
581
|
+
function_id: str,
|
|
582
|
+
arguments: dict[str, Any],
|
|
583
|
+
) -> Iterator[tuple[str, str | None, dict[str, Any], tuple[str, ...]]]:
|
|
584
|
+
analysis = analyze_source(source, filename)
|
|
585
|
+
info = next(
|
|
586
|
+
(item for item in analysis.functions if item.id == function_id),
|
|
587
|
+
None,
|
|
588
|
+
)
|
|
589
|
+
if info is None:
|
|
590
|
+
info = next(
|
|
591
|
+
(item for item in analysis.functions if item.name == function_id),
|
|
592
|
+
None,
|
|
593
|
+
)
|
|
594
|
+
if info is None:
|
|
595
|
+
return
|
|
596
|
+
try:
|
|
597
|
+
module = ast.parse(source, filename=filename)
|
|
598
|
+
except SyntaxError:
|
|
599
|
+
return
|
|
600
|
+
function = next(
|
|
601
|
+
(
|
|
602
|
+
node for node in module.body
|
|
603
|
+
if isinstance(node, ast.FunctionDef) and node.name == info.name
|
|
604
|
+
),
|
|
605
|
+
None,
|
|
606
|
+
)
|
|
607
|
+
if (
|
|
608
|
+
function is None
|
|
609
|
+
or function.args.posonlyargs
|
|
610
|
+
or function.args.kwonlyargs
|
|
611
|
+
or function.decorator_list
|
|
612
|
+
or function.returns is not None
|
|
613
|
+
):
|
|
614
|
+
return
|
|
615
|
+
if function.args.vararg or function.args.kwarg:
|
|
616
|
+
return
|
|
617
|
+
if any(argument.annotation is not None for argument in function.args.args):
|
|
618
|
+
return
|
|
619
|
+
if any(
|
|
620
|
+
isinstance(node, ast.FunctionDef) and node is not function
|
|
621
|
+
for node in ast.walk(function)
|
|
622
|
+
):
|
|
623
|
+
return
|
|
624
|
+
names = [item.arg for item in function.args.args]
|
|
625
|
+
body = _function_body_without_docstring(function.body)
|
|
626
|
+
effective_arguments = PracticeExerciseGenerator._effective_function_arguments(
|
|
627
|
+
source, filename, info.id, arguments
|
|
628
|
+
)
|
|
629
|
+
optional_names = (
|
|
630
|
+
set(names[-len(function.args.defaults):])
|
|
631
|
+
if function.args.defaults else set()
|
|
632
|
+
)
|
|
633
|
+
nodes = list(ast.walk(function))
|
|
634
|
+
branches = [node for node in nodes if isinstance(node, ast.If)]
|
|
635
|
+
fors = [node for node in nodes if isinstance(node, ast.For)]
|
|
636
|
+
whiles = [node for node in nodes if isinstance(node, ast.While)]
|
|
637
|
+
returns = [node for node in nodes if isinstance(node, ast.Return)]
|
|
638
|
+
updates = [node for node in nodes if isinstance(node, ast.AugAssign)]
|
|
639
|
+
calls = [
|
|
640
|
+
node for node in nodes
|
|
641
|
+
if isinstance(node, ast.Call) and isinstance(node.func, ast.Name)
|
|
642
|
+
]
|
|
643
|
+
call_names = {node.func.id for node in calls}
|
|
644
|
+
helper_names = {
|
|
645
|
+
node.name for node in module.body
|
|
646
|
+
if isinstance(node, ast.FunctionDef) and node.name != info.name
|
|
647
|
+
}
|
|
648
|
+
project_calls = call_names & helper_names
|
|
649
|
+
|
|
650
|
+
if (
|
|
651
|
+
fors and len(fors) == 1 and not whiles and not branches
|
|
652
|
+
and updates and returns and len(names) == 1
|
|
653
|
+
and len(body) == 3
|
|
654
|
+
and isinstance(body[0], ast.Assign)
|
|
655
|
+
and isinstance(body[1], ast.For)
|
|
656
|
+
and body[1] is fors[0]
|
|
657
|
+
and isinstance(body[2], ast.Return)
|
|
658
|
+
and len(fors[0].body) == 1
|
|
659
|
+
and isinstance(fors[0].body[0], ast.AugAssign)
|
|
660
|
+
and isinstance(fors[0].iter, ast.Name)
|
|
661
|
+
and fors[0].iter.id == names[0]
|
|
662
|
+
and isinstance(body[2].value, ast.Name)
|
|
663
|
+
and isinstance(body[1].target, ast.Name)
|
|
664
|
+
and isinstance(fors[0].body[0].target, ast.Name)
|
|
665
|
+
and body[2].value.id == fors[0].body[0].target.id
|
|
666
|
+
and isinstance(body[0].targets[0], ast.Name)
|
|
667
|
+
and body[0].targets[0].id == body[2].value.id
|
|
668
|
+
and not calls
|
|
669
|
+
):
|
|
670
|
+
parameter = names[0]
|
|
671
|
+
for values, expression in (
|
|
672
|
+
([2, 5, 3], "item + 1"),
|
|
673
|
+
([4, 1, 6], "item - 1"),
|
|
674
|
+
):
|
|
675
|
+
template = (
|
|
676
|
+
f"def {info.name}({_function_signature(function)}):\n"
|
|
677
|
+
" total = 0\n"
|
|
678
|
+
f" for item in {parameter}:\n"
|
|
679
|
+
f" total += {expression}\n"
|
|
680
|
+
" return total\n"
|
|
681
|
+
)
|
|
682
|
+
yield template, info.id, {parameter: values}, (
|
|
683
|
+
"function parameters", "loop", "variable update", "arithmetic", "return"
|
|
684
|
+
)
|
|
685
|
+
return
|
|
686
|
+
|
|
687
|
+
if (
|
|
688
|
+
project_calls and len(names) == 1 and returns
|
|
689
|
+
and not branches and not fors and not whiles
|
|
690
|
+
and len(body) == 1 and isinstance(body[0], ast.Return)
|
|
691
|
+
and isinstance(body[0].value, ast.BinOp)
|
|
692
|
+
and any(isinstance(node, ast.BinOp) for node in nodes)
|
|
693
|
+
and _is_number(effective_arguments.get(names[0]))
|
|
694
|
+
and len(calls) == 1
|
|
695
|
+
and len(project_calls) == 1
|
|
696
|
+
):
|
|
697
|
+
parameter = names[0]
|
|
698
|
+
helper = "_pov_adjust"
|
|
699
|
+
while helper == info.name or helper in helper_names:
|
|
700
|
+
helper += "_"
|
|
701
|
+
template = (
|
|
702
|
+
f"def {helper}(value):\n"
|
|
703
|
+
" return value * 2\n\n"
|
|
704
|
+
f"def {info.name}({_function_signature(function)}):\n"
|
|
705
|
+
f" return {helper}({parameter}) * 2\n"
|
|
706
|
+
)
|
|
707
|
+
for value in (3, 5):
|
|
708
|
+
candidate_arguments = dict(arguments)
|
|
709
|
+
candidate_arguments[parameter] = value
|
|
710
|
+
yield template, info.id, candidate_arguments, (
|
|
711
|
+
"function parameters", "function call", "arithmetic", "return"
|
|
712
|
+
)
|
|
713
|
+
return
|
|
714
|
+
|
|
715
|
+
branch_body_supported = (
|
|
716
|
+
len(body) == 1
|
|
717
|
+
and isinstance(body[0], ast.If)
|
|
718
|
+
and len(body[0].body) == 1
|
|
719
|
+
and isinstance(body[0].body[0], ast.Return)
|
|
720
|
+
and len(body[0].orelse) == 1
|
|
721
|
+
and isinstance(body[0].orelse[0], ast.Return)
|
|
722
|
+
) or (
|
|
723
|
+
len(body) == 2
|
|
724
|
+
and isinstance(body[0], ast.If)
|
|
725
|
+
and len(body[0].body) == 1
|
|
726
|
+
and isinstance(body[0].body[0], ast.Return)
|
|
727
|
+
and not body[0].orelse
|
|
728
|
+
and isinstance(body[1], ast.Return)
|
|
729
|
+
)
|
|
730
|
+
if (
|
|
731
|
+
branches and len(branches) == 1 and returns and not fors and not whiles
|
|
732
|
+
and len(names) in {1, 2}
|
|
733
|
+
and branch_body_supported
|
|
734
|
+
and not project_calls
|
|
735
|
+
and not calls
|
|
736
|
+
and any(isinstance(node, (ast.BinOp, ast.AugAssign)) for node in nodes)
|
|
737
|
+
):
|
|
738
|
+
first = names[0]
|
|
739
|
+
second = names[1] if len(names) == 2 else None
|
|
740
|
+
boolean_names = [
|
|
741
|
+
name for name in names
|
|
742
|
+
if isinstance(effective_arguments.get(name), bool)
|
|
743
|
+
]
|
|
744
|
+
numeric_names = [
|
|
745
|
+
name for name in names
|
|
746
|
+
if _is_number(effective_arguments.get(name))
|
|
747
|
+
]
|
|
748
|
+
if len(names) == 2 and len(boolean_names) == 1 and len(numeric_names) == 1:
|
|
749
|
+
branch = body[0]
|
|
750
|
+
if not (
|
|
751
|
+
isinstance(branch, ast.If)
|
|
752
|
+
and isinstance(branch.test, ast.Name)
|
|
753
|
+
and branch.test.id == boolean_names[0]
|
|
754
|
+
):
|
|
755
|
+
return
|
|
756
|
+
flag = boolean_names[0]
|
|
757
|
+
value_name = numeric_names[0]
|
|
758
|
+
discount_rules = (
|
|
759
|
+
(f"{value_name} - 2", value_name),
|
|
760
|
+
(f"{value_name} * 0.8", value_name),
|
|
761
|
+
)
|
|
762
|
+
for member_value, nonmember_value in discount_rules:
|
|
763
|
+
template = (
|
|
764
|
+
f"def {info.name}({_function_signature(function)}):\n"
|
|
765
|
+
f" if {flag}:\n"
|
|
766
|
+
f" return {member_value}\n"
|
|
767
|
+
f" return {nonmember_value}\n"
|
|
768
|
+
)
|
|
769
|
+
yield template, info.id, dict(arguments), (
|
|
770
|
+
"function parameters", "condition", "branch", "arithmetic", "return"
|
|
771
|
+
)
|
|
772
|
+
return
|
|
773
|
+
if not all(_is_number(effective_arguments.get(name)) for name in names):
|
|
774
|
+
return
|
|
775
|
+
for threshold in (5, 7):
|
|
776
|
+
candidate_arguments = dict(arguments)
|
|
777
|
+
if second:
|
|
778
|
+
body = (
|
|
779
|
+
f" if {first} >= {threshold}:\n"
|
|
780
|
+
f" return {first} + {second}\n"
|
|
781
|
+
f" return {first} - {second}\n"
|
|
782
|
+
)
|
|
783
|
+
if first not in candidate_arguments:
|
|
784
|
+
candidate_arguments[first] = threshold + 1
|
|
785
|
+
if second not in candidate_arguments:
|
|
786
|
+
candidate_arguments[second] = 2
|
|
787
|
+
else:
|
|
788
|
+
body = (
|
|
789
|
+
f" if {first} >= {threshold}:\n"
|
|
790
|
+
f" return {first} + 1\n"
|
|
791
|
+
f" return {first} - 1\n"
|
|
792
|
+
)
|
|
793
|
+
if first not in candidate_arguments and first not in optional_names:
|
|
794
|
+
candidate_arguments[first] = threshold + 1
|
|
795
|
+
template = f"def {info.name}({_function_signature(function)}):\n" + body
|
|
796
|
+
yield template, info.id, candidate_arguments, (
|
|
797
|
+
"function parameters", "condition", "branch", "arithmetic", "return"
|
|
798
|
+
)
|
|
799
|
+
return
|
|
800
|
+
|
|
801
|
+
if (
|
|
802
|
+
returns and not branches and not fors and not whiles
|
|
803
|
+
and not calls and not project_calls and len(names) in {1, 2}
|
|
804
|
+
and len(body) == 1 and isinstance(body[0], ast.Return)
|
|
805
|
+
):
|
|
806
|
+
if not any(isinstance(node, ast.BinOp) for node in nodes):
|
|
807
|
+
return
|
|
808
|
+
if not all(_is_number(effective_arguments.get(name)) for name in names):
|
|
809
|
+
return
|
|
810
|
+
for multiplier in (2, 3):
|
|
811
|
+
if len(names) == 1:
|
|
812
|
+
first = names[0]
|
|
813
|
+
expression = f"{first} * {multiplier} + 1"
|
|
814
|
+
candidate_arguments = dict(arguments)
|
|
815
|
+
if first not in candidate_arguments:
|
|
816
|
+
candidate_arguments[first] = 4 + multiplier
|
|
817
|
+
else:
|
|
818
|
+
first, second = names
|
|
819
|
+
expression = f"{first} + {second} * {multiplier}"
|
|
820
|
+
candidate_arguments = dict(arguments)
|
|
821
|
+
if first not in candidate_arguments and first not in optional_names:
|
|
822
|
+
candidate_arguments[first] = 3
|
|
823
|
+
if second not in candidate_arguments and second not in optional_names:
|
|
824
|
+
candidate_arguments[second] = 2 + multiplier
|
|
825
|
+
template = (
|
|
826
|
+
f"def {info.name}({_function_signature(function)}):\n"
|
|
827
|
+
f" return {expression}\n"
|
|
828
|
+
)
|
|
829
|
+
yield template, info.id, candidate_arguments, (
|
|
830
|
+
"function parameters", "arithmetic", "return"
|
|
831
|
+
)
|
|
832
|
+
|
|
833
|
+
|
|
834
|
+
def _replace_source_segment(source: str, node: ast.AST, replacement: str) -> str | None:
|
|
835
|
+
if node.end_lineno is None or node.end_col_offset is None:
|
|
836
|
+
return None
|
|
837
|
+
lines = source.splitlines(keepends=True)
|
|
838
|
+
if node.lineno < 1 or node.end_lineno > len(lines):
|
|
839
|
+
return None
|
|
840
|
+
|
|
841
|
+
def absolute_offset(line_number: int, byte_column: int) -> int:
|
|
842
|
+
prefix = lines[line_number - 1].encode("utf-8")[:byte_column]
|
|
843
|
+
character_column = len(prefix.decode("utf-8"))
|
|
844
|
+
return sum(len(line) for line in lines[:line_number - 1]) + character_column
|
|
845
|
+
|
|
846
|
+
start = absolute_offset(node.lineno, node.col_offset)
|
|
847
|
+
end = absolute_offset(node.end_lineno, node.end_col_offset)
|
|
848
|
+
if start < 0 or end < start or end > len(source):
|
|
849
|
+
return None
|
|
850
|
+
return source[:start] + replacement + source[end:]
|
|
851
|
+
|
|
852
|
+
|
|
853
|
+
def _module_body_without_docstring(body: list[ast.stmt]) -> list[ast.stmt]:
|
|
854
|
+
if (
|
|
855
|
+
body
|
|
856
|
+
and isinstance(body[0], ast.Expr)
|
|
857
|
+
and isinstance(body[0].value, ast.Constant)
|
|
858
|
+
and isinstance(body[0].value.value, str)
|
|
859
|
+
):
|
|
860
|
+
return body[1:]
|
|
861
|
+
return body
|
|
862
|
+
|
|
863
|
+
|
|
864
|
+
def _function_body_without_docstring(body: list[ast.stmt]) -> list[ast.stmt]:
|
|
865
|
+
return _module_body_without_docstring(body)
|
|
866
|
+
|
|
867
|
+
|
|
868
|
+
def _function_signature(function: ast.FunctionDef) -> str:
|
|
869
|
+
names = [item.arg for item in function.args.args]
|
|
870
|
+
defaults = function.args.defaults
|
|
871
|
+
default_names = names[-len(defaults):] if defaults else []
|
|
872
|
+
default_values = {
|
|
873
|
+
name: ast.unparse(value)
|
|
874
|
+
for name, value in zip(default_names, defaults)
|
|
875
|
+
}
|
|
876
|
+
return ", ".join(
|
|
877
|
+
name + ("=" + default_values[name] if name in default_values else "")
|
|
878
|
+
for name in names
|
|
879
|
+
)
|
|
880
|
+
|
|
881
|
+
|
|
882
|
+
def _is_number(value: Any) -> bool:
|
|
883
|
+
return isinstance(value, (int, float)) and not isinstance(value, bool)
|
|
884
|
+
|
|
885
|
+
|
|
886
|
+
def _selected_function_concepts(
|
|
887
|
+
source: str,
|
|
888
|
+
filename: str,
|
|
889
|
+
function_id: str,
|
|
890
|
+
) -> tuple[str, ...]:
|
|
891
|
+
analysis = analyze_source(source, filename)
|
|
892
|
+
info = next(
|
|
893
|
+
(item for item in analysis.functions if item.id == function_id),
|
|
894
|
+
None,
|
|
895
|
+
)
|
|
896
|
+
if info is None:
|
|
897
|
+
info = next(
|
|
898
|
+
(item for item in analysis.functions if item.name == function_id),
|
|
899
|
+
None,
|
|
900
|
+
)
|
|
901
|
+
if info is None:
|
|
902
|
+
return ("function parameters",)
|
|
903
|
+
try:
|
|
904
|
+
module = ast.parse(source, filename=filename)
|
|
905
|
+
except SyntaxError:
|
|
906
|
+
return ("function parameters",)
|
|
907
|
+
function = next(
|
|
908
|
+
(
|
|
909
|
+
node for node in module.body
|
|
910
|
+
if isinstance(node, ast.FunctionDef) and node.name == info.name
|
|
911
|
+
),
|
|
912
|
+
None,
|
|
913
|
+
)
|
|
914
|
+
if function is None:
|
|
915
|
+
return ("function parameters",)
|
|
916
|
+
concepts = list(_concepts(function))
|
|
917
|
+
if function.args.args:
|
|
918
|
+
concepts.insert(0, "function parameters")
|
|
919
|
+
return tuple(dict.fromkeys(concepts))
|
|
920
|
+
|
|
921
|
+
|
|
922
|
+
def _selected_function_node(
|
|
923
|
+
source: str,
|
|
924
|
+
filename: str,
|
|
925
|
+
function_id: str,
|
|
926
|
+
) -> ast.FunctionDef | None:
|
|
927
|
+
try:
|
|
928
|
+
module = ast.parse(source, filename=filename)
|
|
929
|
+
except SyntaxError:
|
|
930
|
+
return None
|
|
931
|
+
analysis = analyze_source(source, filename)
|
|
932
|
+
info = next(
|
|
933
|
+
(item for item in analysis.functions if item.id == function_id),
|
|
934
|
+
None,
|
|
935
|
+
)
|
|
936
|
+
if info is None:
|
|
937
|
+
info = next(
|
|
938
|
+
(item for item in analysis.functions if item.name == function_id),
|
|
939
|
+
None,
|
|
940
|
+
)
|
|
941
|
+
if info is None:
|
|
942
|
+
return None
|
|
943
|
+
return next(
|
|
944
|
+
(
|
|
945
|
+
node for node in module.body
|
|
946
|
+
if isinstance(node, ast.FunctionDef) and node.name == info.name
|
|
947
|
+
),
|
|
948
|
+
None,
|
|
949
|
+
)
|
|
950
|
+
|
|
951
|
+
|
|
952
|
+
def _branch_boundary_candidates(
|
|
953
|
+
scope: ast.AST,
|
|
954
|
+
input_values: dict[str, Any],
|
|
955
|
+
) -> Iterator[tuple[str, Any]]:
|
|
956
|
+
loop_inputs = {
|
|
957
|
+
node.target.id: node.iter.id
|
|
958
|
+
for node in ast.walk(scope)
|
|
959
|
+
if isinstance(node, ast.For)
|
|
960
|
+
and isinstance(node.target, ast.Name)
|
|
961
|
+
and isinstance(node.iter, ast.Name)
|
|
962
|
+
and node.iter.id in input_values
|
|
963
|
+
}
|
|
964
|
+
|
|
965
|
+
def input_name(name: str) -> str | None:
|
|
966
|
+
if name in input_values:
|
|
967
|
+
return name
|
|
968
|
+
return loop_inputs.get(name)
|
|
969
|
+
|
|
970
|
+
for node in ast.walk(scope):
|
|
971
|
+
if not isinstance(node, ast.Compare) or len(node.ops) != 1:
|
|
972
|
+
continue
|
|
973
|
+
if len(node.comparators) != 1:
|
|
974
|
+
continue
|
|
975
|
+
left, right = node.left, node.comparators[0]
|
|
976
|
+
for value_node, threshold_node, value_is_left in (
|
|
977
|
+
(left, right, True),
|
|
978
|
+
(right, left, False),
|
|
979
|
+
):
|
|
980
|
+
if not isinstance(value_node, ast.Name):
|
|
981
|
+
continue
|
|
982
|
+
name = input_name(value_node.id)
|
|
983
|
+
if name is None:
|
|
984
|
+
continue
|
|
985
|
+
if isinstance(threshold_node, ast.Constant):
|
|
986
|
+
threshold = threshold_node.value
|
|
987
|
+
elif isinstance(threshold_node, ast.Name):
|
|
988
|
+
threshold = input_values.get(threshold_node.id)
|
|
989
|
+
else:
|
|
990
|
+
continue
|
|
991
|
+
if not _is_number(threshold):
|
|
992
|
+
continue
|
|
993
|
+
for variant in _boundary_value_variants(
|
|
994
|
+
input_values[name], threshold, node.ops[0], value_is_left
|
|
995
|
+
):
|
|
996
|
+
yield name, variant
|
|
997
|
+
|
|
998
|
+
|
|
999
|
+
def _boundary_value_variants(
|
|
1000
|
+
value: Any,
|
|
1001
|
+
threshold: int | float,
|
|
1002
|
+
operator: ast.cmpop,
|
|
1003
|
+
value_is_left: bool,
|
|
1004
|
+
) -> list[Any]:
|
|
1005
|
+
if not math.isfinite(float(threshold)):
|
|
1006
|
+
return []
|
|
1007
|
+
if isinstance(value, (list, tuple)):
|
|
1008
|
+
if not value or not all(
|
|
1009
|
+
_is_number(item) and type(item) is type(value[0]) for item in value
|
|
1010
|
+
):
|
|
1011
|
+
return []
|
|
1012
|
+
points = _boundary_points(value[0], threshold)
|
|
1013
|
+
if not points:
|
|
1014
|
+
return []
|
|
1015
|
+
candidate = [points[index % len(points)] for index in range(len(value))]
|
|
1016
|
+
if candidate == list(value):
|
|
1017
|
+
return []
|
|
1018
|
+
return [tuple(candidate) if isinstance(value, tuple) else candidate]
|
|
1019
|
+
if not _is_number(value):
|
|
1020
|
+
return []
|
|
1021
|
+
points = _boundary_points(value, threshold)
|
|
1022
|
+
original_result = (
|
|
1023
|
+
_compare(operator, value, threshold)
|
|
1024
|
+
if value_is_left
|
|
1025
|
+
else _compare(operator, threshold, value)
|
|
1026
|
+
)
|
|
1027
|
+
|
|
1028
|
+
def priority(candidate: int | float) -> tuple[int, int, float]:
|
|
1029
|
+
result = (
|
|
1030
|
+
_compare(operator, candidate, threshold)
|
|
1031
|
+
if value_is_left
|
|
1032
|
+
else _compare(operator, threshold, candidate)
|
|
1033
|
+
)
|
|
1034
|
+
return (
|
|
1035
|
+
0 if result != original_result else 1,
|
|
1036
|
+
0 if candidate == threshold else 1,
|
|
1037
|
+
abs(candidate - threshold),
|
|
1038
|
+
)
|
|
1039
|
+
|
|
1040
|
+
return [
|
|
1041
|
+
candidate
|
|
1042
|
+
for candidate in sorted(points, key=priority)
|
|
1043
|
+
if candidate != value
|
|
1044
|
+
]
|
|
1045
|
+
|
|
1046
|
+
|
|
1047
|
+
def _boundary_points(value: int | float, threshold: int | float) -> list[int | float]:
|
|
1048
|
+
if isinstance(value, float):
|
|
1049
|
+
return [float(threshold - 1), float(threshold), float(threshold + 1)]
|
|
1050
|
+
lower = math.floor(threshold)
|
|
1051
|
+
upper = math.ceil(threshold)
|
|
1052
|
+
return list(dict.fromkeys((lower - 1, lower, upper, upper + 1)))
|
|
1053
|
+
|
|
1054
|
+
|
|
1055
|
+
def _compare(operator: ast.cmpop, left: int | float, right: int | float) -> bool:
|
|
1056
|
+
if isinstance(operator, ast.Lt):
|
|
1057
|
+
return left < right
|
|
1058
|
+
if isinstance(operator, ast.LtE):
|
|
1059
|
+
return left <= right
|
|
1060
|
+
if isinstance(operator, ast.Gt):
|
|
1061
|
+
return left > right
|
|
1062
|
+
if isinstance(operator, ast.GtE):
|
|
1063
|
+
return left >= right
|
|
1064
|
+
if isinstance(operator, ast.Eq):
|
|
1065
|
+
return left == right
|
|
1066
|
+
if isinstance(operator, ast.NotEq):
|
|
1067
|
+
return left != right
|
|
1068
|
+
return False
|
|
1069
|
+
|
|
1070
|
+
|
|
1071
|
+
def _logic_change_explanation(
|
|
1072
|
+
original_source: str,
|
|
1073
|
+
candidate_source: str,
|
|
1074
|
+
mode: str,
|
|
1075
|
+
function_id: str | None,
|
|
1076
|
+
filename: str,
|
|
1077
|
+
) -> str | None:
|
|
1078
|
+
original_function = (
|
|
1079
|
+
_selected_function_node(original_source, filename, function_id)
|
|
1080
|
+
if mode == "function" and function_id is not None
|
|
1081
|
+
else None
|
|
1082
|
+
)
|
|
1083
|
+
if mode == "function" and original_function is None:
|
|
1084
|
+
return None
|
|
1085
|
+
candidate_function_id = (
|
|
1086
|
+
original_function.name if original_function is not None else function_id
|
|
1087
|
+
)
|
|
1088
|
+
original = _logic_ast(original_source, mode, function_id, filename)
|
|
1089
|
+
candidate = _logic_ast(
|
|
1090
|
+
candidate_source, mode, candidate_function_id, filename
|
|
1091
|
+
)
|
|
1092
|
+
if original is None or candidate is None:
|
|
1093
|
+
return None
|
|
1094
|
+
if _normalized_logic_signature(original) == _normalized_logic_signature(candidate):
|
|
1095
|
+
if mode != "function":
|
|
1096
|
+
return None
|
|
1097
|
+
try:
|
|
1098
|
+
original_module = ast.parse(original_source, filename=filename)
|
|
1099
|
+
candidate_module = ast.parse(candidate_source, filename=filename)
|
|
1100
|
+
except SyntaxError:
|
|
1101
|
+
return None
|
|
1102
|
+
if _normalized_logic_signature(
|
|
1103
|
+
original_module
|
|
1104
|
+
) == _normalized_logic_signature(candidate_module):
|
|
1105
|
+
return None
|
|
1106
|
+
original, candidate = original_module, candidate_module
|
|
1107
|
+
|
|
1108
|
+
original_comparisons = [
|
|
1109
|
+
type(operator)
|
|
1110
|
+
for node in ast.walk(original)
|
|
1111
|
+
if isinstance(node, ast.Compare)
|
|
1112
|
+
for operator in node.ops
|
|
1113
|
+
]
|
|
1114
|
+
candidate_comparisons = [
|
|
1115
|
+
type(operator)
|
|
1116
|
+
for node in ast.walk(candidate)
|
|
1117
|
+
if isinstance(node, ast.Compare)
|
|
1118
|
+
for operator in node.ops
|
|
1119
|
+
]
|
|
1120
|
+
if original_comparisons != candidate_comparisons:
|
|
1121
|
+
return "The comparison rule changed; practise evaluating the condition and choosing a branch."
|
|
1122
|
+
|
|
1123
|
+
operator_types = (ast.operator, ast.boolop, ast.unaryop)
|
|
1124
|
+
original_operators = [
|
|
1125
|
+
type(node)
|
|
1126
|
+
for node in ast.walk(original)
|
|
1127
|
+
if isinstance(node, operator_types)
|
|
1128
|
+
]
|
|
1129
|
+
candidate_operators = [
|
|
1130
|
+
type(node)
|
|
1131
|
+
for node in ast.walk(candidate)
|
|
1132
|
+
if isinstance(node, operator_types)
|
|
1133
|
+
]
|
|
1134
|
+
if original_operators != candidate_operators:
|
|
1135
|
+
return "The arithmetic or variable-update rule changed; practise tracing each calculation."
|
|
1136
|
+
|
|
1137
|
+
flow_types = (ast.If, ast.For, ast.While)
|
|
1138
|
+
original_flow = [
|
|
1139
|
+
type(node) for node in ast.walk(original) if isinstance(node, flow_types)
|
|
1140
|
+
]
|
|
1141
|
+
candidate_flow = [
|
|
1142
|
+
type(node) for node in ast.walk(candidate) if isinstance(node, flow_types)
|
|
1143
|
+
]
|
|
1144
|
+
if original_flow != candidate_flow:
|
|
1145
|
+
return "The branch or loop structure changed; practise tracing the new execution path."
|
|
1146
|
+
return "The expression structure changed; practise tracing how it affects the result."
|
|
1147
|
+
|
|
1148
|
+
|
|
1149
|
+
def _logic_ast(
|
|
1150
|
+
source: str,
|
|
1151
|
+
mode: str,
|
|
1152
|
+
function_id: str | None,
|
|
1153
|
+
filename: str,
|
|
1154
|
+
) -> ast.AST | None:
|
|
1155
|
+
try:
|
|
1156
|
+
module = ast.parse(source, filename=filename)
|
|
1157
|
+
except SyntaxError:
|
|
1158
|
+
return None
|
|
1159
|
+
if mode == "code":
|
|
1160
|
+
return module
|
|
1161
|
+
if function_id is None:
|
|
1162
|
+
return None
|
|
1163
|
+
function = _selected_function_node(source, filename, function_id)
|
|
1164
|
+
if function is None:
|
|
1165
|
+
return None
|
|
1166
|
+
return ast.Module(body=function.body, type_ignores=[])
|
|
1167
|
+
|
|
1168
|
+
|
|
1169
|
+
def _normalized_logic_signature(node: ast.AST) -> str:
|
|
1170
|
+
normalized = copy.deepcopy(node)
|
|
1171
|
+
for item in ast.walk(normalized):
|
|
1172
|
+
if isinstance(item, ast.Name):
|
|
1173
|
+
item.id = "_"
|
|
1174
|
+
elif isinstance(item, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef)):
|
|
1175
|
+
item.name = "_"
|
|
1176
|
+
elif isinstance(item, ast.arg):
|
|
1177
|
+
item.arg = "_"
|
|
1178
|
+
elif isinstance(item, ast.keyword) and item.arg is not None:
|
|
1179
|
+
item.arg = "_"
|
|
1180
|
+
elif isinstance(item, ast.Constant):
|
|
1181
|
+
item.value = None
|
|
1182
|
+
return ast.dump(normalized, include_attributes=False)
|
|
1183
|
+
|
|
1184
|
+
|
|
1185
|
+
def _value_variants(value: Any) -> list[Any]:
|
|
1186
|
+
if isinstance(value, bool):
|
|
1187
|
+
return [not value]
|
|
1188
|
+
if isinstance(value, int):
|
|
1189
|
+
return [value + offset for offset in (5, -5, 10, -10, 2, -2)]
|
|
1190
|
+
if isinstance(value, float) and math.isfinite(value):
|
|
1191
|
+
return [
|
|
1192
|
+
value + offset
|
|
1193
|
+
for offset in (5.0, -5.0, 10.0, -10.0, 2.0, -2.0)
|
|
1194
|
+
if math.isfinite(value + offset)
|
|
1195
|
+
]
|
|
1196
|
+
if isinstance(value, str):
|
|
1197
|
+
if len(value) > 9990:
|
|
1198
|
+
return []
|
|
1199
|
+
return [value + " " + str(number) for number in range(1, 5)]
|
|
1200
|
+
if isinstance(value, (list, tuple)):
|
|
1201
|
+
variants: list[Any] = []
|
|
1202
|
+
if value and all(_is_number(item) for item in value):
|
|
1203
|
+
for offset in (5, -5, 10, -10):
|
|
1204
|
+
changed = [item + offset for item in value]
|
|
1205
|
+
variants.append(
|
|
1206
|
+
tuple(changed) if isinstance(value, tuple) else changed
|
|
1207
|
+
)
|
|
1208
|
+
elif value and all(isinstance(item, bool) for item in value):
|
|
1209
|
+
changed = [not item for item in value]
|
|
1210
|
+
variants.append(tuple(changed) if isinstance(value, tuple) else changed)
|
|
1211
|
+
elif value and all(isinstance(item, str) for item in value):
|
|
1212
|
+
for number in range(1, 5):
|
|
1213
|
+
changed = [item + " " + str(number) for item in value]
|
|
1214
|
+
variants.append(tuple(changed) if isinstance(value, tuple) else changed)
|
|
1215
|
+
for index, item in enumerate(value):
|
|
1216
|
+
if isinstance(item, (list, tuple)):
|
|
1217
|
+
continue
|
|
1218
|
+
for replacement in _value_variants(item):
|
|
1219
|
+
changed = list(value)
|
|
1220
|
+
changed[index] = replacement
|
|
1221
|
+
variants.append(tuple(changed) if isinstance(value, tuple) else changed)
|
|
1222
|
+
if len(variants) >= 24:
|
|
1223
|
+
return variants
|
|
1224
|
+
return variants
|
|
1225
|
+
return []
|
|
1226
|
+
|
|
1227
|
+
|
|
1228
|
+
def _concepts(node: ast.AST) -> tuple[str, ...]:
|
|
1229
|
+
nodes = list(ast.walk(node))
|
|
1230
|
+
concepts: list[str] = []
|
|
1231
|
+
if any(isinstance(item, ast.If) for item in nodes):
|
|
1232
|
+
concepts.append("condition")
|
|
1233
|
+
concepts.append("branch")
|
|
1234
|
+
if any(isinstance(item, (ast.For, ast.While)) for item in nodes):
|
|
1235
|
+
concepts.append("loop")
|
|
1236
|
+
if any(isinstance(item, ast.AugAssign) for item in nodes):
|
|
1237
|
+
concepts.append("variable update")
|
|
1238
|
+
if any(isinstance(item, (ast.BinOp, ast.AugAssign)) for item in nodes):
|
|
1239
|
+
concepts.append("arithmetic")
|
|
1240
|
+
if any(
|
|
1241
|
+
isinstance(item, ast.FunctionDef) and item.args.args
|
|
1242
|
+
for item in nodes
|
|
1243
|
+
):
|
|
1244
|
+
concepts.append("function parameters")
|
|
1245
|
+
if any(isinstance(item, ast.Return) for item in nodes):
|
|
1246
|
+
concepts.append("return")
|
|
1247
|
+
if any(
|
|
1248
|
+
isinstance(item, ast.Call)
|
|
1249
|
+
and isinstance(item.func, ast.Name)
|
|
1250
|
+
and item.func.id == "print"
|
|
1251
|
+
for item in nodes
|
|
1252
|
+
):
|
|
1253
|
+
concepts.append("output")
|
|
1254
|
+
if any(
|
|
1255
|
+
isinstance(item, ast.Call)
|
|
1256
|
+
and not (
|
|
1257
|
+
isinstance(item.func, ast.Name)
|
|
1258
|
+
and item.func.id in {"print", "range"}
|
|
1259
|
+
)
|
|
1260
|
+
for item in nodes
|
|
1261
|
+
):
|
|
1262
|
+
concepts.append("function call")
|
|
1263
|
+
return tuple(dict.fromkeys(concepts))
|