]>
Commit | Line | Data |
---|---|---|
19a03940 | 1 | import collections |
2 | import contextlib | |
825abb81 | 3 | import json |
9e3f1991 | 4 | import operator |
2b25cb5d PH |
5 | import re |
6 | ||
f8271158 | 7 | from .utils import ExtractorError, remove_quotes |
2b25cb5d | 8 | |
9e3f1991 PH |
9 | _OPERATORS = [ |
10 | ('|', operator.or_), | |
11 | ('^', operator.xor), | |
12 | ('&', operator.and_), | |
13 | ('>>', operator.rshift), | |
14 | ('<<', operator.lshift), | |
15 | ('-', operator.sub), | |
16 | ('+', operator.add), | |
17 | ('%', operator.mod), | |
8cfb6efe | 18 | ('/', operator.truediv), |
9e3f1991 PH |
19 | ('*', operator.mul), |
20 | ] | |
21 | _ASSIGN_OPERATORS = [(op + '=', opfunc) for op, opfunc in _OPERATORS] | |
404f611f | 22 | _ASSIGN_OPERATORS.append(('=', (lambda cur, right: right))) |
9e3f1991 PH |
23 | |
24 | _NAME_RE = r'[a-zA-Z_$][a-zA-Z_$0-9]*' | |
25 | ||
06dfe0a0 | 26 | _MATCHING_PARENS = dict(zip('({[', ')}]')) |
27 | ||
2b25cb5d | 28 | |
404f611f | 29 | class JS_Break(ExtractorError): |
30 | def __init__(self): | |
31 | ExtractorError.__init__(self, 'Invalid break') | |
32 | ||
33 | ||
34 | class JS_Continue(ExtractorError): | |
35 | def __init__(self): | |
36 | ExtractorError.__init__(self, 'Invalid continue') | |
37 | ||
38 | ||
19a03940 | 39 | class LocalNameSpace(collections.ChainMap): |
404f611f | 40 | def __setitem__(self, key, value): |
19a03940 | 41 | for scope in self.maps: |
404f611f | 42 | if key in scope: |
43 | scope[key] = value | |
19a03940 | 44 | return |
45 | self.maps[0][key] = value | |
404f611f | 46 | |
47 | def __delitem__(self, key): | |
48 | raise NotImplementedError('Deleting is not supported') | |
49 | ||
404f611f | 50 | |
86e5f3ed | 51 | class JSInterpreter: |
9e3f1991 PH |
52 | def __init__(self, code, objects=None): |
53 | if objects is None: | |
54 | objects = {} | |
3eff81fb | 55 | self.code = code |
2b25cb5d | 56 | self._functions = {} |
9e3f1991 | 57 | self._objects = objects |
404f611f | 58 | self.__named_object_counter = 0 |
59 | ||
60 | def _named_object(self, namespace, obj): | |
61 | self.__named_object_counter += 1 | |
62 | name = f'__yt_dlp_jsinterp_obj{self.__named_object_counter}' | |
63 | namespace[name] = obj | |
64 | return name | |
65 | ||
66 | @staticmethod | |
e75bb0d6 | 67 | def _separate(expr, delim=',', max_split=None): |
404f611f | 68 | if not expr: |
69 | return | |
06dfe0a0 | 70 | counters = {k: 0 for k in _MATCHING_PARENS.values()} |
71 | start, splits, pos, delim_len = 0, 0, 0, len(delim) - 1 | |
404f611f | 72 | for idx, char in enumerate(expr): |
06dfe0a0 | 73 | if char in _MATCHING_PARENS: |
74 | counters[_MATCHING_PARENS[char]] += 1 | |
75 | elif char in counters: | |
76 | counters[char] -= 1 | |
77 | if char != delim[pos] or any(counters.values()): | |
404f611f | 78 | pos = 0 |
06dfe0a0 | 79 | continue |
80 | elif pos != delim_len: | |
81 | pos += 1 | |
82 | continue | |
83 | yield expr[start: idx - delim_len] | |
84 | start, pos = idx + 1, 0 | |
85 | splits += 1 | |
86 | if max_split and splits >= max_split: | |
87 | break | |
404f611f | 88 | yield expr[start:] |
89 | ||
90 | @staticmethod | |
e75bb0d6 U |
91 | def _separate_at_paren(expr, delim): |
92 | separated = list(JSInterpreter._separate(expr, delim, 1)) | |
93 | if len(separated) < 2: | |
404f611f | 94 | raise ExtractorError(f'No terminating paren {delim} in {expr}') |
e75bb0d6 | 95 | return separated[0][1:].strip(), separated[1].strip() |
9e3f1991 | 96 | |
9e3f1991 | 97 | def interpret_statement(self, stmt, local_vars, allow_recursion=100): |
2b25cb5d PH |
98 | if allow_recursion < 0: |
99 | raise ExtractorError('Recursion limit reached') | |
100 | ||
e75bb0d6 | 101 | sub_statements = list(self._separate(stmt, ';')) |
404f611f | 102 | stmt = (sub_statements or ['']).pop() |
103 | for sub_stmt in sub_statements: | |
104 | ret, should_abort = self.interpret_statement(sub_stmt, local_vars, allow_recursion - 1) | |
105 | if should_abort: | |
106 | return ret | |
107 | ||
9e3f1991 PH |
108 | should_abort = False |
109 | stmt = stmt.lstrip() | |
110 | stmt_m = re.match(r'var\s', stmt) | |
111 | if stmt_m: | |
112 | expr = stmt[len(stmt_m.group(0)):] | |
2b25cb5d | 113 | else: |
9e3f1991 PH |
114 | return_m = re.match(r'return(?:\s+|$)', stmt) |
115 | if return_m: | |
116 | expr = stmt[len(return_m.group(0)):] | |
117 | should_abort = True | |
118 | else: | |
119 | # Try interpreting it as an expression | |
120 | expr = stmt | |
2b25cb5d PH |
121 | |
122 | v = self.interpret_expression(expr, local_vars, allow_recursion) | |
9e3f1991 | 123 | return v, should_abort |
2b25cb5d PH |
124 | |
125 | def interpret_expression(self, expr, local_vars, allow_recursion): | |
9e3f1991 | 126 | expr = expr.strip() |
9e3f1991 PH |
127 | if expr == '': # Empty expression |
128 | return None | |
129 | ||
404f611f | 130 | if expr.startswith('{'): |
e75bb0d6 | 131 | inner, outer = self._separate_at_paren(expr, '}') |
404f611f | 132 | inner, should_abort = self.interpret_statement(inner, local_vars, allow_recursion - 1) |
133 | if not outer or should_abort: | |
134 | return inner | |
135 | else: | |
136 | expr = json.dumps(inner) + outer | |
137 | ||
9e3f1991 | 138 | if expr.startswith('('): |
e75bb0d6 | 139 | inner, outer = self._separate_at_paren(expr, ')') |
404f611f | 140 | inner = self.interpret_expression(inner, local_vars, allow_recursion) |
141 | if not outer: | |
142 | return inner | |
143 | else: | |
144 | expr = json.dumps(inner) + outer | |
145 | ||
146 | if expr.startswith('['): | |
e75bb0d6 | 147 | inner, outer = self._separate_at_paren(expr, ']') |
404f611f | 148 | name = self._named_object(local_vars, [ |
149 | self.interpret_expression(item, local_vars, allow_recursion) | |
e75bb0d6 | 150 | for item in self._separate(inner)]) |
404f611f | 151 | expr = name + outer |
152 | ||
153 | m = re.match(r'try\s*', expr) | |
154 | if m: | |
155 | if expr[m.end()] == '{': | |
e75bb0d6 | 156 | try_expr, expr = self._separate_at_paren(expr[m.end():], '}') |
404f611f | 157 | else: |
158 | try_expr, expr = expr[m.end() - 1:], '' | |
159 | ret, should_abort = self.interpret_statement(try_expr, local_vars, allow_recursion - 1) | |
160 | if should_abort: | |
161 | return ret | |
162 | return self.interpret_statement(expr, local_vars, allow_recursion - 1)[0] | |
163 | ||
164 | m = re.match(r'catch\s*\(', expr) | |
165 | if m: | |
166 | # We ignore the catch block | |
e75bb0d6 | 167 | _, expr = self._separate_at_paren(expr, '}') |
404f611f | 168 | return self.interpret_statement(expr, local_vars, allow_recursion - 1)[0] |
169 | ||
170 | m = re.match(r'for\s*\(', expr) | |
171 | if m: | |
e75bb0d6 | 172 | constructor, remaining = self._separate_at_paren(expr[m.end() - 1:], ')') |
404f611f | 173 | if remaining.startswith('{'): |
e75bb0d6 | 174 | body, expr = self._separate_at_paren(remaining, '}') |
404f611f | 175 | else: |
176 | m = re.match(r'switch\s*\(', remaining) # FIXME | |
177 | if m: | |
e75bb0d6 U |
178 | switch_val, remaining = self._separate_at_paren(remaining[m.end() - 1:], ')') |
179 | body, expr = self._separate_at_paren(remaining, '}') | |
404f611f | 180 | body = 'switch(%s){%s}' % (switch_val, body) |
9e3f1991 | 181 | else: |
404f611f | 182 | body, expr = remaining, '' |
e75bb0d6 | 183 | start, cndn, increment = self._separate(constructor, ';') |
404f611f | 184 | if self.interpret_statement(start, local_vars, allow_recursion - 1)[1]: |
185 | raise ExtractorError( | |
186 | f'Premature return in the initialization of a for loop in {constructor!r}') | |
187 | while True: | |
188 | if not self.interpret_expression(cndn, local_vars, allow_recursion): | |
189 | break | |
190 | try: | |
191 | ret, should_abort = self.interpret_statement(body, local_vars, allow_recursion - 1) | |
192 | if should_abort: | |
193 | return ret | |
194 | except JS_Break: | |
195 | break | |
196 | except JS_Continue: | |
197 | pass | |
198 | if self.interpret_statement(increment, local_vars, allow_recursion - 1)[1]: | |
199 | raise ExtractorError( | |
200 | f'Premature return in the initialization of a for loop in {constructor!r}') | |
201 | return self.interpret_statement(expr, local_vars, allow_recursion - 1)[0] | |
202 | ||
203 | m = re.match(r'switch\s*\(', expr) | |
204 | if m: | |
e75bb0d6 | 205 | switch_val, remaining = self._separate_at_paren(expr[m.end() - 1:], ')') |
404f611f | 206 | switch_val = self.interpret_expression(switch_val, local_vars, allow_recursion) |
e75bb0d6 | 207 | body, expr = self._separate_at_paren(remaining, '}') |
a1fc7ca0 | 208 | items = body.replace('default:', 'case default:').split('case ')[1:] |
209 | for default in (False, True): | |
210 | matched = False | |
211 | for item in items: | |
86e5f3ed | 212 | case, stmt = (i.strip() for i in self._separate(item, ':', 1)) |
a1fc7ca0 | 213 | if default: |
214 | matched = matched or case == 'default' | |
215 | elif not matched: | |
216 | matched = case != 'default' and switch_val == self.interpret_expression(case, local_vars, allow_recursion) | |
217 | if not matched: | |
218 | continue | |
404f611f | 219 | try: |
220 | ret, should_abort = self.interpret_statement(stmt, local_vars, allow_recursion - 1) | |
221 | if should_abort: | |
222 | return ret | |
223 | except JS_Break: | |
9e3f1991 | 224 | break |
a1fc7ca0 | 225 | if matched: |
226 | break | |
404f611f | 227 | return self.interpret_statement(expr, local_vars, allow_recursion - 1)[0] |
228 | ||
e75bb0d6 U |
229 | # Comma separated statements |
230 | sub_expressions = list(self._separate(expr)) | |
404f611f | 231 | expr = sub_expressions.pop().strip() if sub_expressions else '' |
232 | for sub_expr in sub_expressions: | |
233 | self.interpret_expression(sub_expr, local_vars, allow_recursion) | |
234 | ||
235 | for m in re.finditer(rf'''(?x) | |
236 | (?P<pre_sign>\+\+|--)(?P<var1>{_NAME_RE})| | |
237 | (?P<var2>{_NAME_RE})(?P<post_sign>\+\+|--)''', expr): | |
238 | var = m.group('var1') or m.group('var2') | |
239 | start, end = m.span() | |
240 | sign = m.group('pre_sign') or m.group('post_sign') | |
241 | ret = local_vars[var] | |
242 | local_vars[var] += 1 if sign[0] == '+' else -1 | |
243 | if m.group('pre_sign'): | |
244 | ret = local_vars[var] | |
245 | expr = expr[:start] + json.dumps(ret) + expr[end:] | |
9e3f1991 PH |
246 | |
247 | for op, opfunc in _ASSIGN_OPERATORS: | |
86e5f3ed | 248 | m = re.match(rf'''(?x) |
249 | (?P<out>{_NAME_RE})(?:\[(?P<index>[^\]]+?)\])? | |
250 | \s*{re.escape(op)} | |
251 | (?P<expr>.*)$''', expr) | |
9e3f1991 PH |
252 | if not m: |
253 | continue | |
404f611f | 254 | right_val = self.interpret_expression(m.group('expr'), local_vars, allow_recursion) |
9e3f1991 PH |
255 | |
256 | if m.groupdict().get('index'): | |
257 | lvar = local_vars[m.group('out')] | |
404f611f | 258 | idx = self.interpret_expression(m.group('index'), local_vars, allow_recursion) |
259 | if not isinstance(idx, int): | |
260 | raise ExtractorError(f'List indices must be integers: {idx}') | |
9e3f1991 PH |
261 | cur = lvar[idx] |
262 | val = opfunc(cur, right_val) | |
263 | lvar[idx] = val | |
264 | return val | |
265 | else: | |
266 | cur = local_vars.get(m.group('out')) | |
267 | val = opfunc(cur, right_val) | |
268 | local_vars[m.group('out')] = val | |
269 | return val | |
270 | ||
2b25cb5d PH |
271 | if expr.isdigit(): |
272 | return int(expr) | |
273 | ||
404f611f | 274 | if expr == 'break': |
275 | raise JS_Break() | |
276 | elif expr == 'continue': | |
277 | raise JS_Continue() | |
278 | ||
9e3f1991 | 279 | var_m = re.match( |
404f611f | 280 | r'(?!if|return|true|false|null)(?P<name>%s)$' % _NAME_RE, |
9e3f1991 PH |
281 | expr) |
282 | if var_m: | |
283 | return local_vars[var_m.group('name')] | |
2b25cb5d | 284 | |
19a03940 | 285 | with contextlib.suppress(ValueError): |
825abb81 | 286 | return json.loads(expr) |
825abb81 PH |
287 | |
288 | m = re.match( | |
7769f837 S |
289 | r'(?P<in>%s)\[(?P<idx>.+)\]$' % _NAME_RE, expr) |
290 | if m: | |
291 | val = local_vars[m.group('in')] | |
404f611f | 292 | idx = self.interpret_expression(m.group('idx'), local_vars, allow_recursion) |
7769f837 S |
293 | return val[idx] |
294 | ||
404f611f | 295 | for op, opfunc in _OPERATORS: |
e75bb0d6 U |
296 | separated = list(self._separate(expr, op)) |
297 | if len(separated) < 2: | |
404f611f | 298 | continue |
e75bb0d6 U |
299 | right_val = separated.pop() |
300 | left_val = op.join(separated) | |
404f611f | 301 | left_val, should_abort = self.interpret_statement( |
302 | left_val, local_vars, allow_recursion - 1) | |
303 | if should_abort: | |
304 | raise ExtractorError(f'Premature left-side return of {op} in {expr!r}') | |
305 | right_val, should_abort = self.interpret_statement( | |
306 | right_val, local_vars, allow_recursion - 1) | |
307 | if should_abort: | |
308 | raise ExtractorError(f'Premature right-side return of {op} in {expr!r}') | |
309 | return opfunc(left_val or 0, right_val) | |
310 | ||
7769f837 | 311 | m = re.match( |
404f611f | 312 | r'(?P<var>%s)(?:\.(?P<member>[^(]+)|\[(?P<member2>[^]]+)\])\s*' % _NAME_RE, |
825abb81 | 313 | expr) |
2b25cb5d | 314 | if m: |
825abb81 | 315 | variable = m.group('var') |
7769f837 | 316 | member = remove_quotes(m.group('member') or m.group('member2')) |
404f611f | 317 | arg_str = expr[m.end():] |
318 | if arg_str.startswith('('): | |
e75bb0d6 | 319 | arg_str, remaining = self._separate_at_paren(arg_str, ')') |
825abb81 | 320 | else: |
404f611f | 321 | arg_str, remaining = None, arg_str |
322 | ||
323 | def assertion(cndn, msg): | |
324 | """ assert, but without risk of getting optimized out """ | |
325 | if not cndn: | |
326 | raise ExtractorError(f'{member} {msg}: {expr}') | |
327 | ||
328 | def eval_method(): | |
329 | nonlocal member | |
330 | if variable == 'String': | |
331 | obj = str | |
332 | elif variable in local_vars: | |
333 | obj = local_vars[variable] | |
334 | else: | |
335 | if variable not in self._objects: | |
336 | self._objects[variable] = self.extract_object(variable) | |
337 | obj = self._objects[variable] | |
338 | ||
339 | if arg_str is None: | |
340 | # Member access | |
341 | if member == 'length': | |
342 | return len(obj) | |
343 | return obj[member] | |
344 | ||
345 | # Function call | |
346 | argvals = [ | |
825abb81 | 347 | self.interpret_expression(v, local_vars, allow_recursion) |
e75bb0d6 | 348 | for v in self._separate(arg_str)] |
404f611f | 349 | |
350 | if obj == str: | |
351 | if member == 'fromCharCode': | |
352 | assertion(argvals, 'takes one or more arguments') | |
353 | return ''.join(map(chr, argvals)) | |
354 | raise ExtractorError(f'Unsupported string method {member}') | |
355 | ||
356 | if member == 'split': | |
357 | assertion(argvals, 'takes one or more arguments') | |
358 | assertion(argvals == [''], 'with arguments is not implemented') | |
359 | return list(obj) | |
360 | elif member == 'join': | |
361 | assertion(isinstance(obj, list), 'must be applied on a list') | |
362 | assertion(len(argvals) == 1, 'takes exactly one argument') | |
363 | return argvals[0].join(obj) | |
364 | elif member == 'reverse': | |
365 | assertion(not argvals, 'does not take any arguments') | |
366 | obj.reverse() | |
367 | return obj | |
368 | elif member == 'slice': | |
369 | assertion(isinstance(obj, list), 'must be applied on a list') | |
370 | assertion(len(argvals) == 1, 'takes exactly one argument') | |
371 | return obj[argvals[0]:] | |
372 | elif member == 'splice': | |
373 | assertion(isinstance(obj, list), 'must be applied on a list') | |
374 | assertion(argvals, 'takes one or more arguments') | |
57dbe807 | 375 | index, howMany = map(int, (argvals + [len(obj)])[:2]) |
404f611f | 376 | if index < 0: |
377 | index += len(obj) | |
378 | add_items = argvals[2:] | |
379 | res = [] | |
380 | for i in range(index, min(index + howMany, len(obj))): | |
381 | res.append(obj.pop(index)) | |
382 | for i, item in enumerate(add_items): | |
383 | obj.insert(index + i, item) | |
384 | return res | |
385 | elif member == 'unshift': | |
386 | assertion(isinstance(obj, list), 'must be applied on a list') | |
387 | assertion(argvals, 'takes one or more arguments') | |
388 | for item in reversed(argvals): | |
389 | obj.insert(0, item) | |
390 | return obj | |
391 | elif member == 'pop': | |
392 | assertion(isinstance(obj, list), 'must be applied on a list') | |
393 | assertion(not argvals, 'does not take any arguments') | |
394 | if not obj: | |
395 | return | |
396 | return obj.pop() | |
397 | elif member == 'push': | |
398 | assertion(argvals, 'takes one or more arguments') | |
399 | obj.extend(argvals) | |
400 | return obj | |
401 | elif member == 'forEach': | |
402 | assertion(argvals, 'takes one or more arguments') | |
403 | assertion(len(argvals) <= 2, 'takes at-most 2 arguments') | |
404 | f, this = (argvals + [''])[:2] | |
405 | return [f((item, idx, obj), this=this) for idx, item in enumerate(obj)] | |
406 | elif member == 'indexOf': | |
407 | assertion(argvals, 'takes one or more arguments') | |
408 | assertion(len(argvals) <= 2, 'takes at-most 2 arguments') | |
409 | idx, start = (argvals + [0])[:2] | |
410 | try: | |
411 | return obj.index(idx, start) | |
412 | except ValueError: | |
413 | return -1 | |
414 | ||
415 | if isinstance(obj, list): | |
416 | member = int(member) | |
417 | return obj[member](argvals) | |
418 | ||
419 | if remaining: | |
420 | return self.interpret_expression( | |
421 | self._named_object(local_vars, eval_method()) + remaining, | |
422 | local_vars, allow_recursion) | |
423 | else: | |
424 | return eval_method() | |
2b25cb5d | 425 | |
404f611f | 426 | m = re.match(r'^(?P<func>%s)\((?P<args>[a-zA-Z0-9_$,]*)\)$' % _NAME_RE, expr) |
2b25cb5d PH |
427 | if m: |
428 | fname = m.group('func') | |
86e5f3ed | 429 | argvals = tuple( |
825abb81 | 430 | int(v) if v.isdigit() else local_vars[v] |
86e5f3ed | 431 | for v in self._separate(m.group('args'))) |
404f611f | 432 | if fname in local_vars: |
433 | return local_vars[fname](argvals) | |
434 | elif fname not in self._functions: | |
1f749b66 | 435 | self._functions[fname] = self.extract_function(fname) |
2b25cb5d | 436 | return self._functions[fname](argvals) |
9e3f1991 | 437 | |
404f611f | 438 | if expr: |
439 | raise ExtractorError('Unsupported JS expression %r' % expr) | |
2b25cb5d | 440 | |
ad25aee2 | 441 | def extract_object(self, objname): |
7769f837 | 442 | _FUNC_NAME_RE = r'''(?:[a-zA-Z$0-9]+|"[a-zA-Z$0-9]+"|'[a-zA-Z$0-9]+')''' |
ad25aee2 JMF |
443 | obj = {} |
444 | obj_m = re.search( | |
0e2d626d S |
445 | r'''(?x) |
446 | (?<!this\.)%s\s*=\s*{\s* | |
447 | (?P<fields>(%s\s*:\s*function\s*\(.*?\)\s*{.*?}(?:,\s*)?)*) | |
448 | }\s*; | |
449 | ''' % (re.escape(objname), _FUNC_NAME_RE), | |
ad25aee2 JMF |
450 | self.code) |
451 | fields = obj_m.group('fields') | |
452 | # Currently, it only supports function definitions | |
453 | fields_m = re.finditer( | |
0e2d626d S |
454 | r'''(?x) |
455 | (?P<key>%s)\s*:\s*function\s*\((?P<args>[a-z,]+)\){(?P<code>[^}]+)} | |
456 | ''' % _FUNC_NAME_RE, | |
ad25aee2 JMF |
457 | fields) |
458 | for f in fields_m: | |
459 | argnames = f.group('args').split(',') | |
7769f837 | 460 | obj[remove_quotes(f.group('key'))] = self.build_function(argnames, f.group('code')) |
ad25aee2 JMF |
461 | |
462 | return obj | |
463 | ||
404f611f | 464 | def extract_function_code(self, funcname): |
465 | """ @returns argnames, code """ | |
2b25cb5d | 466 | func_m = re.search( |
9e3f1991 | 467 | r'''(?x) |
b46eabec | 468 | (?:function\s+%s|[{;,]\s*%s\s*=\s*function|var\s+%s\s*=\s*function)\s* |
9e3f1991 | 469 | \((?P<args>[^)]*)\)\s* |
404f611f | 470 | (?P<code>\{(?:(?!};)[^"]|"([^"]|\\")*")+\})''' % ( |
ff29bf81 | 471 | re.escape(funcname), re.escape(funcname), re.escape(funcname)), |
2b25cb5d | 472 | self.code) |
e75bb0d6 | 473 | code, _ = self._separate_at_paren(func_m.group('code'), '}') # refine the match |
77ffa957 PH |
474 | if func_m is None: |
475 | raise ExtractorError('Could not find JS function %r' % funcname) | |
404f611f | 476 | return func_m.group('args').split(','), code |
2b25cb5d | 477 | |
404f611f | 478 | def extract_function(self, funcname): |
479 | return self.extract_function_from_code(*self.extract_function_code(funcname)) | |
480 | ||
481 | def extract_function_from_code(self, argnames, code, *global_stack): | |
482 | local_vars = {} | |
483 | while True: | |
484 | mobj = re.search(r'function\((?P<args>[^)]*)\)\s*{', code) | |
485 | if mobj is None: | |
486 | break | |
487 | start, body_start = mobj.span() | |
e75bb0d6 | 488 | body, remaining = self._separate_at_paren(code[body_start - 1:], '}') |
404f611f | 489 | name = self._named_object( |
490 | local_vars, | |
491 | self.extract_function_from_code( | |
492 | [str.strip(x) for x in mobj.group('args').split(',')], | |
493 | body, local_vars, *global_stack)) | |
494 | code = code[:start] + name + remaining | |
495 | return self.build_function(argnames, code, local_vars, *global_stack) | |
ad25aee2 | 496 | |
9e3f1991 | 497 | def call_function(self, funcname, *args): |
404f611f | 498 | return self.extract_function(funcname)(args) |
499 | ||
500 | def build_function(self, argnames, code, *global_stack): | |
501 | global_stack = list(global_stack) or [{}] | |
404f611f | 502 | |
503 | def resf(args, **kwargs): | |
19a03940 | 504 | global_stack[0].update({ |
404f611f | 505 | **dict(zip(argnames, args)), |
506 | **kwargs | |
507 | }) | |
19a03940 | 508 | var_stack = LocalNameSpace(*global_stack) |
e75bb0d6 | 509 | for stmt in self._separate(code.replace('\n', ''), ';'): |
404f611f | 510 | ret, should_abort = self.interpret_statement(stmt, var_stack) |
511 | if should_abort: | |
9e3f1991 | 512 | break |
404f611f | 513 | return ret |
2b25cb5d | 514 | return resf |