-
Notifications
You must be signed in to change notification settings - Fork 31
Expand file tree
/
Copy pathState.py
More file actions
340 lines (276 loc) · 11.1 KB
/
State.py
File metadata and controls
340 lines (276 loc) · 11.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
import asttokens
from functools import partialmethod
from collections.abc import Mapping
from protowhat.failure import debugger
from protowhat.Feedback import FeedbackComponent
from protowhat.selectors import DispatcherInterface
from protowhat.State import State as ProtoState
from protowhat.utils import parameters_attr
from pythonwhat import signatures
from pythonwhat.converters import get_manual_converters
from pythonwhat.feedback import Feedback
from pythonwhat.parsing import (
TargetVars,
FunctionParser,
ObjectAccessParser,
parser_dict,
)
from pythonwhat.utils_ast import wrap_in_module
class Context(Mapping):
def __init__(self, context=None, prev=None):
self.context = context if context else TargetVars()
self.prev = prev if prev else {}
self._items = {**self.prev, **self.context.defined_items()}
def update_ctx(self, new_ctx):
return self.__class__(new_ctx, self._items)
def __getitem__(self, x):
return self._items[x]
def __iter__(self):
return iter(self._items)
def __len__(self):
return len(self._items)
@parameters_attr
class State(ProtoState):
"""State of the SCT environment.
This class holds all information relevevant to test the correctness of an exercise.
It is coded suboptimally and it will be refactored soon, and documented thouroughly
after that.
kwargs:
...
- reporter
"""
feedback_cls = Feedback
def __init__(
self,
student_code,
solution_code,
pre_exercise_code,
student_process,
solution_process,
raw_student_output,
# solution output
reporter,
force_diagnose=False,
highlight=None,
highlight_offset=None,
highlighting_disabled=None,
feedback_context=None,
creator=None,
student_ast=None,
solution_ast=None,
student_ast_tokens=None,
solution_ast_tokens=None,
student_parts=None,
solution_parts=None,
student_context=Context(),
solution_context=Context(),
student_env=Context(),
solution_env=Context(),
):
args = locals().copy()
self.debug = False
for k, v in args.items():
if k != "self":
setattr(self, k, v)
self.ast_dispatcher = self.get_dispatcher()
# Parse solution and student code
# if possible, not done yet and wanted (ast arguments not False)
if isinstance(self.student_code, str) and student_ast is None:
self.student_ast = self.parse(student_code)
if isinstance(self.solution_code, str) and solution_ast is None:
with debugger(self):
self.solution_ast = self.parse(solution_code)
if highlight is None: # todo: check parent_state? (move check to reporting?)
self.highlight = self.student_ast
self.converters = get_manual_converters() # accessed only from root state
self.manual_sigs = None
def get_manual_sigs(self):
if self.manual_sigs is None:
self.manual_sigs = signatures.get_manual_sigs()
return self.manual_sigs
def to_child(self, append_message=None, node_name="", **kwargs):
"""Dive into nested tree.
Set the current state as a state with a subtree of this syntax tree as
student tree and solution tree. This is necessary when testing if statements or
for loops for example.
"""
bad_parameters = set(kwargs) - set(self.parameters)
if bad_parameters:
raise ValueError(
"Invalid init parameters for State: %s" % ", ".join(bad_parameters)
)
base_kwargs = {
attr: getattr(self, attr)
for attr in self.parameters
if hasattr(self, attr) and attr not in ["ast_dispatcher", "highlight"]
}
if append_message and not isinstance(append_message, FeedbackComponent):
append_message = FeedbackComponent(append_message)
kwargs["feedback_context"] = append_message
kwargs["creator"] = {"type": "to_child", "args": {"state": self}}
def update_kwarg(name, func):
kwargs[name] = func(kwargs[name])
def update_context(name):
update_kwarg(name, getattr(self, name).update_ctx)
for ast_arg in ["student_ast", "solution_ast"]:
if isinstance(kwargs.get(ast_arg), list):
update_kwarg(ast_arg, wrap_in_module)
if kwargs.get("student_ast") and kwargs.get("student_code") is None:
kwargs["student_code"] = self.student_ast_tokens.get_text(
kwargs["student_ast"]
)
if kwargs.get("solution_ast") and kwargs.get("solution_code") is None:
kwargs["solution_code"] = self.solution_ast_tokens.get_text(
kwargs["solution_ast"]
)
for context in [
"student_context",
"solution_context",
"student_env",
"solution_env",
]:
if context in kwargs:
if kwargs[context] is not None:
update_context(context)
else:
kwargs.pop(context)
klass = self.SUBCLASSES[node_name] if node_name else State
init_kwargs = {**base_kwargs, **kwargs}
child = klass(**init_kwargs)
extra_attrs = set(vars(self)) - set(self.parameters)
for attr in extra_attrs:
# don't copy attrs set on new instances in init
# the cached manual_sigs is passed
if attr not in {"ast_dispatcher", "converters"}:
setattr(child, attr, getattr(self, attr))
return child
def has_different_processes(self):
# process classes have an _identity field that is a tuple
try:
return (
self.student_process._identity[0] != self.solution_process._identity[0]
)
except:
# play it safe (most common)
return True
def assert_execution_root(self, fun, extra_msg=""):
if not (self.is_root or self.is_creator_type("run")):
with debugger(self):
self.report(
"`%s()` should only be called focusing on a full script, following `Ex()` or `run()`. %s"
% (fun, extra_msg)
)
def is_creator_type(self, type):
return self.creator and self.creator.get("type") == type
def assert_is(self, klasses, fun, prev_fun):
if self.__class__.__name__ not in klasses:
with debugger(self):
self.report(
"`%s()` can only be called on %s."
% (fun, " or ".join(["`%s()`" % pf for pf in prev_fun]))
)
def assert_is_not(self, klasses, fun, prev_fun):
if self.__class__.__name__ in klasses:
with debugger(self):
self.report(
"`%s()` should not be called on %s."
% (fun, " or ".join(["`%s()`" % pf for pf in prev_fun]))
)
def parse_external(self, code):
res = (None, None)
try:
return self.ast_dispatcher.parse(code)
except IndentationError as e:
e.filename = "script.py"
# no line info for now
self.report(
"Your code could not be parsed due to an error in the indentation:<br>`%s.`"
% str(e)
)
except SyntaxError as e:
e.filename = "script.py"
# no line info for now
self.report(
"Your code can not be executed due to a syntax error:<br>`%s.`" % str(e)
)
# Can happen, can't catch this earlier because we can't differentiate between
# TypeError in parsing or TypeError within code (at runtime).
except:
self.report("Something went wrong while parsing your code.")
return res
def parse_internal(self, code):
try:
return self.ast_dispatcher.parse(code)
except Exception as e:
self.report(
"Something went wrong when parsing the solution code: %s" % str(e)
)
def parse(self, text):
if self.debug:
parse_method = self.parse_internal
token_attr = "solution_ast_tokens"
else:
parse_method = self.parse_external
token_attr = "student_ast_tokens"
tokens, ast = parse_method(text)
setattr(self, token_attr, tokens)
return ast
def get_dispatcher(self):
try:
return Dispatcher(self.pre_exercise_code)
except Exception as e:
with debugger(self):
self.report("Something went wrong when parsing the PEC: %s" % str(e))
class Dispatcher(DispatcherInterface):
_context_cache = dict()
def __init__(self, context_code=""):
self._parser_cache = dict()
context_ast = getattr(self._context_cache, context_code, None)
if context_ast is None:
context_ast = self._context_cache[context_code] = self.parse(context_code)[
1
]
self.context_mappings = self._getx(FunctionParser, "mappings", context_ast)
def find(self, name, node, *args, **kwargs):
return getattr(self, name)(node)
def parse(self, code):
res = asttokens.ASTTokens(code, parse=True)
return res, res.tree
# add methods for retrieving parser outputs --------------------------
def _getx(self, Parser, ext_attr, tree):
"""getter for Parser outputs"""
# return cached output if possible
cache_key = Parser.__name__ + str(hash(tree))
if self._parser_cache.get(cache_key):
p = self._parser_cache[cache_key]
else:
# otherwise, run parser over tree
p = Parser()
# set mappings for parsers that inspect attribute access
if ext_attr != "mappings" and Parser in [
FunctionParser,
ObjectAccessParser,
]:
p.mappings = self.context_mappings.copy()
# run parser
p.visit(tree)
# cache
self._parser_cache[cache_key] = p
return getattr(p, ext_attr)
# put a function on the dispatcher
for k, Parser in parser_dict.items():
setattr(Dispatcher, k, partialmethod(Dispatcher._getx, Parser, "out"))
# mappings from ObjectAccessParser
prop_oa_map = partialmethod(Dispatcher._getx, ObjectAccessParser, "mappings")
setattr(Dispatcher, "oa_mappings", prop_oa_map)
# mappings from FunctionParser
prop_map = partialmethod(Dispatcher._getx, FunctionParser, "mappings")
setattr(Dispatcher, "mappings", prop_map)
# State subclasses based on parsed output -------------------------------------
State.SUBCLASSES = {
node_name: type(node_name, (State,), {}) for node_name in parser_dict
}
# global setters on State -----------------------------------------------------
def set_converter(key, fundef):
# note that root state is set on the State class in test_exercise
State.root_state.converters[key] = fundef