[extractor/tvp] Use new API (#6989)
[yt-dlp3.git] / yt_dlp / jsinterp.py
blob5571ecfeb1b692ae8e9f76cef337e778d8f64dec
1 import collections
2 import contextlib
3 import itertools
4 import json
5 import math
6 import operator
7 import re
9 from .utils import (
10 NO_DEFAULT,
11 ExtractorError,
12 function_with_repr,
13 js_to_json,
14 remove_quotes,
15 truncate_string,
16 unified_timestamp,
17 write_string,
21 def _js_bit_op(op):
22 def zeroise(x):
23 return 0 if x in (None, JS_Undefined) else x
25 def wrapped(a, b):
26 return op(zeroise(a), zeroise(b)) & 0xffffffff
28 return wrapped
31 def _js_arith_op(op):
33 def wrapped(a, b):
34 if JS_Undefined in (a, b):
35 return float('nan')
36 return op(a or 0, b or 0)
38 return wrapped
41 def _js_div(a, b):
42 if JS_Undefined in (a, b) or not (a and b):
43 return float('nan')
44 return (a or 0) / b if b else float('inf')
47 def _js_mod(a, b):
48 if JS_Undefined in (a, b) or not b:
49 return float('nan')
50 return (a or 0) % b
53 def _js_exp(a, b):
54 if not b:
55 return 1 # even 0 ** 0 !!
56 elif JS_Undefined in (a, b):
57 return float('nan')
58 return (a or 0) ** b
61 def _js_eq_op(op):
63 def wrapped(a, b):
64 if {a, b} <= {None, JS_Undefined}:
65 return op(a, a)
66 return op(a, b)
68 return wrapped
71 def _js_comp_op(op):
73 def wrapped(a, b):
74 if JS_Undefined in (a, b):
75 return False
76 if isinstance(a, str) or isinstance(b, str):
77 return op(str(a or 0), str(b or 0))
78 return op(a or 0, b or 0)
80 return wrapped
83 def _js_ternary(cndn, if_true=True, if_false=False):
84 """Simulate JS's ternary operator (cndn?if_true:if_false)"""
85 if cndn in (False, None, 0, '', JS_Undefined):
86 return if_false
87 with contextlib.suppress(TypeError):
88 if math.isnan(cndn): # NB: NaN cannot be checked by membership
89 return if_false
90 return if_true
93 # Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
94 _OPERATORS = { # None => Defined in JSInterpreter._operator
95 '?': None,
96 '??': None,
97 '||': None,
98 '&&': None,
100 '|': _js_bit_op(operator.or_),
101 '^': _js_bit_op(operator.xor),
102 '&': _js_bit_op(operator.and_),
104 '===': operator.is_,
105 '!==': operator.is_not,
106 '==': _js_eq_op(operator.eq),
107 '!=': _js_eq_op(operator.ne),
109 '<=': _js_comp_op(operator.le),
110 '>=': _js_comp_op(operator.ge),
111 '<': _js_comp_op(operator.lt),
112 '>': _js_comp_op(operator.gt),
114 '>>': _js_bit_op(operator.rshift),
115 '<<': _js_bit_op(operator.lshift),
117 '+': _js_arith_op(operator.add),
118 '-': _js_arith_op(operator.sub),
120 '*': _js_arith_op(operator.mul),
121 '%': _js_mod,
122 '/': _js_div,
123 '**': _js_exp,
126 _COMP_OPERATORS = {'===', '!==', '==', '!=', '<=', '>=', '<', '>'}
128 _NAME_RE = r'[a-zA-Z_$][\w$]*'
129 _MATCHING_PARENS = dict(zip(*zip('()', '{}', '[]')))
130 _QUOTES = '\'"/'
133 class JS_Undefined:
134 pass
137 class JS_Break(ExtractorError):
138 def __init__(self):
139 ExtractorError.__init__(self, 'Invalid break')
142 class JS_Continue(ExtractorError):
143 def __init__(self):
144 ExtractorError.__init__(self, 'Invalid continue')
147 class JS_Throw(ExtractorError):
148 def __init__(self, e):
149 self.error = e
150 ExtractorError.__init__(self, f'Uncaught exception {e}')
153 class LocalNameSpace(collections.ChainMap):
154 def __setitem__(self, key, value):
155 for scope in self.maps:
156 if key in scope:
157 scope[key] = value
158 return
159 self.maps[0][key] = value
161 def __delitem__(self, key):
162 raise NotImplementedError('Deleting is not supported')
165 class Debugger:
166 import sys
167 ENABLED = False and 'pytest' in sys.modules
169 @staticmethod
170 def write(*args, level=100):
171 write_string(f'[debug] JS: {" " * (100 - level)}'
172 f'{" ".join(truncate_string(str(x), 50, 50) for x in args)}\n')
174 @classmethod
175 def wrap_interpreter(cls, f):
176 def interpret_statement(self, stmt, local_vars, allow_recursion, *args, **kwargs):
177 if cls.ENABLED and stmt.strip():
178 cls.write(stmt, level=allow_recursion)
179 try:
180 ret, should_ret = f(self, stmt, local_vars, allow_recursion, *args, **kwargs)
181 except Exception as e:
182 if cls.ENABLED:
183 if isinstance(e, ExtractorError):
184 e = e.orig_msg
185 cls.write('=> Raises:', e, '<-|', stmt, level=allow_recursion)
186 raise
187 if cls.ENABLED and stmt.strip():
188 if should_ret or not repr(ret) == stmt:
189 cls.write(['->', '=>'][should_ret], repr(ret), '<-|', stmt, level=allow_recursion)
190 return ret, should_ret
191 return interpret_statement
194 class JSInterpreter:
195 __named_object_counter = 0
197 _RE_FLAGS = {
198 # special knowledge: Python's re flags are bitmask values, current max 128
199 # invent new bitmask values well above that for literal parsing
200 # TODO: new pattern class to execute matches with these flags
201 'd': 1024, # Generate indices for substring matches
202 'g': 2048, # Global search
203 'i': re.I, # Case-insensitive search
204 'm': re.M, # Multi-line search
205 's': re.S, # Allows . to match newline characters
206 'u': re.U, # Treat a pattern as a sequence of unicode code points
207 'y': 4096, # Perform a "sticky" search that matches starting at the current position in the target string
210 def __init__(self, code, objects=None):
211 self.code, self._functions = code, {}
212 self._objects = {} if objects is None else objects
214 class Exception(ExtractorError):
215 def __init__(self, msg, expr=None, *args, **kwargs):
216 if expr is not None:
217 msg = f'{msg.rstrip()} in: {truncate_string(expr, 50, 50)}'
218 super().__init__(msg, *args, **kwargs)
220 def _named_object(self, namespace, obj):
221 self.__named_object_counter += 1
222 name = f'__yt_dlp_jsinterp_obj{self.__named_object_counter}'
223 if callable(obj) and not isinstance(obj, function_with_repr):
224 obj = function_with_repr(obj, f'F<{self.__named_object_counter}>')
225 namespace[name] = obj
226 return name
228 @classmethod
229 def _regex_flags(cls, expr):
230 flags = 0
231 if not expr:
232 return flags, expr
233 for idx, ch in enumerate(expr):
234 if ch not in cls._RE_FLAGS:
235 break
236 flags |= cls._RE_FLAGS[ch]
237 return flags, expr[idx + 1:]
239 @staticmethod
240 def _separate(expr, delim=',', max_split=None):
241 OP_CHARS = '+-*/%&|^=<>!,;{}:['
242 if not expr:
243 return
244 counters = {k: 0 for k in _MATCHING_PARENS.values()}
245 start, splits, pos, delim_len = 0, 0, 0, len(delim) - 1
246 in_quote, escaping, after_op, in_regex_char_group, in_unary_op = None, False, True, False, False
247 for idx, char in enumerate(expr):
248 if not in_quote and char in _MATCHING_PARENS:
249 counters[_MATCHING_PARENS[char]] += 1
250 elif not in_quote and char in counters:
251 # Something's wrong if we get negative, but ignore it anyway
252 if counters[char]:
253 counters[char] -= 1
254 elif not escaping:
255 if char in _QUOTES and in_quote in (char, None):
256 if in_quote or after_op or char != '/':
257 in_quote = None if in_quote and not in_regex_char_group else char
258 elif in_quote == '/' and char in '[]':
259 in_regex_char_group = char == '['
260 escaping = not escaping and in_quote and char == '\\'
261 in_unary_op = (not in_quote and not in_regex_char_group
262 and after_op not in (True, False) and char in '-+')
263 after_op = char if (not in_quote and char in OP_CHARS) else (char.isspace() and after_op)
265 if char != delim[pos] or any(counters.values()) or in_quote or in_unary_op:
266 pos = 0
267 continue
268 elif pos != delim_len:
269 pos += 1
270 continue
271 yield expr[start: idx - delim_len]
272 start, pos = idx + 1, 0
273 splits += 1
274 if max_split and splits >= max_split:
275 break
276 yield expr[start:]
278 @classmethod
279 def _separate_at_paren(cls, expr, delim=None):
280 if delim is None:
281 delim = expr and _MATCHING_PARENS[expr[0]]
282 separated = list(cls._separate(expr, delim, 1))
283 if len(separated) < 2:
284 raise cls.Exception(f'No terminating paren {delim}', expr)
285 return separated[0][1:].strip(), separated[1].strip()
287 def _operator(self, op, left_val, right_expr, expr, local_vars, allow_recursion):
288 if op in ('||', '&&'):
289 if (op == '&&') ^ _js_ternary(left_val):
290 return left_val # short circuiting
291 elif op == '??':
292 if left_val not in (None, JS_Undefined):
293 return left_val
294 elif op == '?':
295 right_expr = _js_ternary(left_val, *self._separate(right_expr, ':', 1))
297 right_val = self.interpret_expression(right_expr, local_vars, allow_recursion)
298 if not _OPERATORS.get(op):
299 return right_val
301 try:
302 return _OPERATORS[op](left_val, right_val)
303 except Exception as e:
304 raise self.Exception(f'Failed to evaluate {left_val!r} {op} {right_val!r}', expr, cause=e)
306 def _index(self, obj, idx, allow_undefined=False):
307 if idx == 'length':
308 return len(obj)
309 try:
310 return obj[int(idx)] if isinstance(obj, list) else obj[idx]
311 except Exception as e:
312 if allow_undefined:
313 return JS_Undefined
314 raise self.Exception(f'Cannot get index {idx}', repr(obj), cause=e)
316 def _dump(self, obj, namespace):
317 try:
318 return json.dumps(obj)
319 except TypeError:
320 return self._named_object(namespace, obj)
322 @Debugger.wrap_interpreter
323 def interpret_statement(self, stmt, local_vars, allow_recursion=100):
324 if allow_recursion < 0:
325 raise self.Exception('Recursion limit reached')
326 allow_recursion -= 1
328 should_return = False
329 sub_statements = list(self._separate(stmt, ';')) or ['']
330 expr = stmt = sub_statements.pop().strip()
332 for sub_stmt in sub_statements:
333 ret, should_return = self.interpret_statement(sub_stmt, local_vars, allow_recursion)
334 if should_return:
335 return ret, should_return
337 m = re.match(r'(?P<var>(?:var|const|let)\s)|return(?:\s+|(?=["\'])|$)|(?P<throw>throw\s+)', stmt)
338 if m:
339 expr = stmt[len(m.group(0)):].strip()
340 if m.group('throw'):
341 raise JS_Throw(self.interpret_expression(expr, local_vars, allow_recursion))
342 should_return = not m.group('var')
343 if not expr:
344 return None, should_return
346 if expr[0] in _QUOTES:
347 inner, outer = self._separate(expr, expr[0], 1)
348 if expr[0] == '/':
349 flags, outer = self._regex_flags(outer)
350 # Avoid https://github.com/python/cpython/issues/74534
351 inner = re.compile(inner[1:].replace('[[', r'[\['), flags=flags)
352 else:
353 inner = json.loads(js_to_json(f'{inner}{expr[0]}', strict=True))
354 if not outer:
355 return inner, should_return
356 expr = self._named_object(local_vars, inner) + outer
358 if expr.startswith('new '):
359 obj = expr[4:]
360 if obj.startswith('Date('):
361 left, right = self._separate_at_paren(obj[4:])
362 date = unified_timestamp(
363 self.interpret_expression(left, local_vars, allow_recursion), False)
364 if date is None:
365 raise self.Exception(f'Failed to parse date {left!r}', expr)
366 expr = self._dump(int(date * 1000), local_vars) + right
367 else:
368 raise self.Exception(f'Unsupported object {obj}', expr)
370 if expr.startswith('void '):
371 left = self.interpret_expression(expr[5:], local_vars, allow_recursion)
372 return None, should_return
374 if expr.startswith('{'):
375 inner, outer = self._separate_at_paren(expr)
376 # try for object expression (Map)
377 sub_expressions = [list(self._separate(sub_expr.strip(), ':', 1)) for sub_expr in self._separate(inner)]
378 if all(len(sub_expr) == 2 for sub_expr in sub_expressions):
379 def dict_item(key, val):
380 val = self.interpret_expression(val, local_vars, allow_recursion)
381 if re.match(_NAME_RE, key):
382 return key, val
383 return self.interpret_expression(key, local_vars, allow_recursion), val
385 return dict(dict_item(k, v) for k, v in sub_expressions), should_return
387 inner, should_abort = self.interpret_statement(inner, local_vars, allow_recursion)
388 if not outer or should_abort:
389 return inner, should_abort or should_return
390 else:
391 expr = self._dump(inner, local_vars) + outer
393 if expr.startswith('('):
394 inner, outer = self._separate_at_paren(expr)
395 inner, should_abort = self.interpret_statement(inner, local_vars, allow_recursion)
396 if not outer or should_abort:
397 return inner, should_abort or should_return
398 else:
399 expr = self._dump(inner, local_vars) + outer
401 if expr.startswith('['):
402 inner, outer = self._separate_at_paren(expr)
403 name = self._named_object(local_vars, [
404 self.interpret_expression(item, local_vars, allow_recursion)
405 for item in self._separate(inner)])
406 expr = name + outer
408 m = re.match(r'''(?x)
409 (?P<try>try)\s*\{|
410 (?P<if>if)\s*\(|
411 (?P<switch>switch)\s*\(|
412 (?P<for>for)\s*\(
413 ''', expr)
414 md = m.groupdict() if m else {}
415 if md.get('if'):
416 cndn, expr = self._separate_at_paren(expr[m.end() - 1:])
417 if_expr, expr = self._separate_at_paren(expr.lstrip())
418 # TODO: "else if" is not handled
419 else_expr = None
420 m = re.match(r'else\s*{', expr)
421 if m:
422 else_expr, expr = self._separate_at_paren(expr[m.end() - 1:])
423 cndn = _js_ternary(self.interpret_expression(cndn, local_vars, allow_recursion))
424 ret, should_abort = self.interpret_statement(
425 if_expr if cndn else else_expr, local_vars, allow_recursion)
426 if should_abort:
427 return ret, True
429 if md.get('try'):
430 try_expr, expr = self._separate_at_paren(expr[m.end() - 1:])
431 err = None
432 try:
433 ret, should_abort = self.interpret_statement(try_expr, local_vars, allow_recursion)
434 if should_abort:
435 return ret, True
436 except Exception as e:
437 # XXX: This works for now, but makes debugging future issues very hard
438 err = e
440 pending = (None, False)
441 m = re.match(r'catch\s*(?P<err>\(\s*{_NAME_RE}\s*\))?\{{'.format(**globals()), expr)
442 if m:
443 sub_expr, expr = self._separate_at_paren(expr[m.end() - 1:])
444 if err:
445 catch_vars = {}
446 if m.group('err'):
447 catch_vars[m.group('err')] = err.error if isinstance(err, JS_Throw) else err
448 catch_vars = local_vars.new_child(catch_vars)
449 err, pending = None, self.interpret_statement(sub_expr, catch_vars, allow_recursion)
451 m = re.match(r'finally\s*\{', expr)
452 if m:
453 sub_expr, expr = self._separate_at_paren(expr[m.end() - 1:])
454 ret, should_abort = self.interpret_statement(sub_expr, local_vars, allow_recursion)
455 if should_abort:
456 return ret, True
458 ret, should_abort = pending
459 if should_abort:
460 return ret, True
462 if err:
463 raise err
465 elif md.get('for'):
466 constructor, remaining = self._separate_at_paren(expr[m.end() - 1:])
467 if remaining.startswith('{'):
468 body, expr = self._separate_at_paren(remaining)
469 else:
470 switch_m = re.match(r'switch\s*\(', remaining) # FIXME
471 if switch_m:
472 switch_val, remaining = self._separate_at_paren(remaining[switch_m.end() - 1:])
473 body, expr = self._separate_at_paren(remaining, '}')
474 body = 'switch(%s){%s}' % (switch_val, body)
475 else:
476 body, expr = remaining, ''
477 start, cndn, increment = self._separate(constructor, ';')
478 self.interpret_expression(start, local_vars, allow_recursion)
479 while True:
480 if not _js_ternary(self.interpret_expression(cndn, local_vars, allow_recursion)):
481 break
482 try:
483 ret, should_abort = self.interpret_statement(body, local_vars, allow_recursion)
484 if should_abort:
485 return ret, True
486 except JS_Break:
487 break
488 except JS_Continue:
489 pass
490 self.interpret_expression(increment, local_vars, allow_recursion)
492 elif md.get('switch'):
493 switch_val, remaining = self._separate_at_paren(expr[m.end() - 1:])
494 switch_val = self.interpret_expression(switch_val, local_vars, allow_recursion)
495 body, expr = self._separate_at_paren(remaining, '}')
496 items = body.replace('default:', 'case default:').split('case ')[1:]
497 for default in (False, True):
498 matched = False
499 for item in items:
500 case, stmt = (i.strip() for i in self._separate(item, ':', 1))
501 if default:
502 matched = matched or case == 'default'
503 elif not matched:
504 matched = (case != 'default'
505 and switch_val == self.interpret_expression(case, local_vars, allow_recursion))
506 if not matched:
507 continue
508 try:
509 ret, should_abort = self.interpret_statement(stmt, local_vars, allow_recursion)
510 if should_abort:
511 return ret
512 except JS_Break:
513 break
514 if matched:
515 break
517 if md:
518 ret, should_abort = self.interpret_statement(expr, local_vars, allow_recursion)
519 return ret, should_abort or should_return
521 # Comma separated statements
522 sub_expressions = list(self._separate(expr))
523 if len(sub_expressions) > 1:
524 for sub_expr in sub_expressions:
525 ret, should_abort = self.interpret_statement(sub_expr, local_vars, allow_recursion)
526 if should_abort:
527 return ret, True
528 return ret, False
530 for m in re.finditer(rf'''(?x)
531 (?P<pre_sign>\+\+|--)(?P<var1>{_NAME_RE})|
532 (?P<var2>{_NAME_RE})(?P<post_sign>\+\+|--)''', expr):
533 var = m.group('var1') or m.group('var2')
534 start, end = m.span()
535 sign = m.group('pre_sign') or m.group('post_sign')
536 ret = local_vars[var]
537 local_vars[var] += 1 if sign[0] == '+' else -1
538 if m.group('pre_sign'):
539 ret = local_vars[var]
540 expr = expr[:start] + self._dump(ret, local_vars) + expr[end:]
542 if not expr:
543 return None, should_return
545 m = re.match(fr'''(?x)
546 (?P<assign>
547 (?P<out>{_NAME_RE})(?:\[(?P<index>[^\]]+?)\])?\s*
548 (?P<op>{"|".join(map(re.escape, set(_OPERATORS) - _COMP_OPERATORS))})?
549 =(?!=)(?P<expr>.*)$
550 )|(?P<return>
551 (?!if|return|true|false|null|undefined|NaN)(?P<name>{_NAME_RE})$
552 )|(?P<indexing>
553 (?P<in>{_NAME_RE})\[(?P<idx>.+)\]$
554 )|(?P<attribute>
555 (?P<var>{_NAME_RE})(?:(?P<nullish>\?)?\.(?P<member>[^(]+)|\[(?P<member2>[^\]]+)\])\s*
556 )|(?P<function>
557 (?P<fname>{_NAME_RE})\((?P<args>.*)\)$
558 )''', expr)
559 if m and m.group('assign'):
560 left_val = local_vars.get(m.group('out'))
562 if not m.group('index'):
563 local_vars[m.group('out')] = self._operator(
564 m.group('op'), left_val, m.group('expr'), expr, local_vars, allow_recursion)
565 return local_vars[m.group('out')], should_return
566 elif left_val in (None, JS_Undefined):
567 raise self.Exception(f'Cannot index undefined variable {m.group("out")}', expr)
569 idx = self.interpret_expression(m.group('index'), local_vars, allow_recursion)
570 if not isinstance(idx, (int, float)):
571 raise self.Exception(f'List index {idx} must be integer', expr)
572 idx = int(idx)
573 left_val[idx] = self._operator(
574 m.group('op'), self._index(left_val, idx), m.group('expr'), expr, local_vars, allow_recursion)
575 return left_val[idx], should_return
577 elif expr.isdigit():
578 return int(expr), should_return
580 elif expr == 'break':
581 raise JS_Break()
582 elif expr == 'continue':
583 raise JS_Continue()
584 elif expr == 'undefined':
585 return JS_Undefined, should_return
586 elif expr == 'NaN':
587 return float('NaN'), should_return
589 elif m and m.group('return'):
590 return local_vars.get(m.group('name'), JS_Undefined), should_return
592 with contextlib.suppress(ValueError):
593 return json.loads(js_to_json(expr, strict=True)), should_return
595 if m and m.group('indexing'):
596 val = local_vars[m.group('in')]
597 idx = self.interpret_expression(m.group('idx'), local_vars, allow_recursion)
598 return self._index(val, idx), should_return
600 for op in _OPERATORS:
601 separated = list(self._separate(expr, op))
602 right_expr = separated.pop()
603 while True:
604 if op in '?<>*-' and len(separated) > 1 and not separated[-1].strip():
605 separated.pop()
606 elif not (separated and op == '?' and right_expr.startswith('.')):
607 break
608 right_expr = f'{op}{right_expr}'
609 if op != '-':
610 right_expr = f'{separated.pop()}{op}{right_expr}'
611 if not separated:
612 continue
613 left_val = self.interpret_expression(op.join(separated), local_vars, allow_recursion)
614 return self._operator(op, left_val, right_expr, expr, local_vars, allow_recursion), should_return
616 if m and m.group('attribute'):
617 variable, member, nullish = m.group('var', 'member', 'nullish')
618 if not member:
619 member = self.interpret_expression(m.group('member2'), local_vars, allow_recursion)
620 arg_str = expr[m.end():]
621 if arg_str.startswith('('):
622 arg_str, remaining = self._separate_at_paren(arg_str)
623 else:
624 arg_str, remaining = None, arg_str
626 def assertion(cndn, msg):
627 """ assert, but without risk of getting optimized out """
628 if not cndn:
629 raise self.Exception(f'{member} {msg}', expr)
631 def eval_method():
632 if (variable, member) == ('console', 'debug'):
633 if Debugger.ENABLED:
634 Debugger.write(self.interpret_expression(f'[{arg_str}]', local_vars, allow_recursion))
635 return
637 types = {
638 'String': str,
639 'Math': float,
641 obj = local_vars.get(variable, types.get(variable, NO_DEFAULT))
642 if obj is NO_DEFAULT:
643 if variable not in self._objects:
644 try:
645 self._objects[variable] = self.extract_object(variable)
646 except self.Exception:
647 if not nullish:
648 raise
649 obj = self._objects.get(variable, JS_Undefined)
651 if nullish and obj is JS_Undefined:
652 return JS_Undefined
654 # Member access
655 if arg_str is None:
656 return self._index(obj, member, nullish)
658 # Function call
659 argvals = [
660 self.interpret_expression(v, local_vars, allow_recursion)
661 for v in self._separate(arg_str)]
663 if obj == str:
664 if member == 'fromCharCode':
665 assertion(argvals, 'takes one or more arguments')
666 return ''.join(map(chr, argvals))
667 raise self.Exception(f'Unsupported String method {member}', expr)
668 elif obj == float:
669 if member == 'pow':
670 assertion(len(argvals) == 2, 'takes two arguments')
671 return argvals[0] ** argvals[1]
672 raise self.Exception(f'Unsupported Math method {member}', expr)
674 if member == 'split':
675 assertion(argvals, 'takes one or more arguments')
676 assertion(len(argvals) == 1, 'with limit argument is not implemented')
677 return obj.split(argvals[0]) if argvals[0] else list(obj)
678 elif member == 'join':
679 assertion(isinstance(obj, list), 'must be applied on a list')
680 assertion(len(argvals) == 1, 'takes exactly one argument')
681 return argvals[0].join(obj)
682 elif member == 'reverse':
683 assertion(not argvals, 'does not take any arguments')
684 obj.reverse()
685 return obj
686 elif member == 'slice':
687 assertion(isinstance(obj, list), 'must be applied on a list')
688 assertion(len(argvals) == 1, 'takes exactly one argument')
689 return obj[argvals[0]:]
690 elif member == 'splice':
691 assertion(isinstance(obj, list), 'must be applied on a list')
692 assertion(argvals, 'takes one or more arguments')
693 index, howMany = map(int, (argvals + [len(obj)])[:2])
694 if index < 0:
695 index += len(obj)
696 add_items = argvals[2:]
697 res = []
698 for i in range(index, min(index + howMany, len(obj))):
699 res.append(obj.pop(index))
700 for i, item in enumerate(add_items):
701 obj.insert(index + i, item)
702 return res
703 elif member == 'unshift':
704 assertion(isinstance(obj, list), 'must be applied on a list')
705 assertion(argvals, 'takes one or more arguments')
706 for item in reversed(argvals):
707 obj.insert(0, item)
708 return obj
709 elif member == 'pop':
710 assertion(isinstance(obj, list), 'must be applied on a list')
711 assertion(not argvals, 'does not take any arguments')
712 if not obj:
713 return
714 return obj.pop()
715 elif member == 'push':
716 assertion(argvals, 'takes one or more arguments')
717 obj.extend(argvals)
718 return obj
719 elif member == 'forEach':
720 assertion(argvals, 'takes one or more arguments')
721 assertion(len(argvals) <= 2, 'takes at-most 2 arguments')
722 f, this = (argvals + [''])[:2]
723 return [f((item, idx, obj), {'this': this}, allow_recursion) for idx, item in enumerate(obj)]
724 elif member == 'indexOf':
725 assertion(argvals, 'takes one or more arguments')
726 assertion(len(argvals) <= 2, 'takes at-most 2 arguments')
727 idx, start = (argvals + [0])[:2]
728 try:
729 return obj.index(idx, start)
730 except ValueError:
731 return -1
732 elif member == 'charCodeAt':
733 assertion(isinstance(obj, str), 'must be applied on a string')
734 assertion(len(argvals) == 1, 'takes exactly one argument')
735 idx = argvals[0] if isinstance(argvals[0], int) else 0
736 if idx >= len(obj):
737 return None
738 return ord(obj[idx])
740 idx = int(member) if isinstance(obj, list) else member
741 return obj[idx](argvals, allow_recursion=allow_recursion)
743 if remaining:
744 ret, should_abort = self.interpret_statement(
745 self._named_object(local_vars, eval_method()) + remaining,
746 local_vars, allow_recursion)
747 return ret, should_return or should_abort
748 else:
749 return eval_method(), should_return
751 elif m and m.group('function'):
752 fname = m.group('fname')
753 argvals = [self.interpret_expression(v, local_vars, allow_recursion)
754 for v in self._separate(m.group('args'))]
755 if fname in local_vars:
756 return local_vars[fname](argvals, allow_recursion=allow_recursion), should_return
757 elif fname not in self._functions:
758 self._functions[fname] = self.extract_function(fname)
759 return self._functions[fname](argvals, allow_recursion=allow_recursion), should_return
761 raise self.Exception(
762 f'Unsupported JS expression {truncate_string(expr, 20, 20) if expr != stmt else ""}', stmt)
764 def interpret_expression(self, expr, local_vars, allow_recursion):
765 ret, should_return = self.interpret_statement(expr, local_vars, allow_recursion)
766 if should_return:
767 raise self.Exception('Cannot return from an expression', expr)
768 return ret
770 def extract_object(self, objname):
771 _FUNC_NAME_RE = r'''(?:[a-zA-Z$0-9]+|"[a-zA-Z$0-9]+"|'[a-zA-Z$0-9]+')'''
772 obj = {}
773 obj_m = re.search(
774 r'''(?x)
775 (?<!this\.)%s\s*=\s*{\s*
776 (?P<fields>(%s\s*:\s*function\s*\(.*?\)\s*{.*?}(?:,\s*)?)*)
777 }\s*;
778 ''' % (re.escape(objname), _FUNC_NAME_RE),
779 self.code)
780 if not obj_m:
781 raise self.Exception(f'Could not find object {objname}')
782 fields = obj_m.group('fields')
783 # Currently, it only supports function definitions
784 fields_m = re.finditer(
785 r'''(?x)
786 (?P<key>%s)\s*:\s*function\s*\((?P<args>(?:%s|,)*)\){(?P<code>[^}]+)}
787 ''' % (_FUNC_NAME_RE, _NAME_RE),
788 fields)
789 for f in fields_m:
790 argnames = f.group('args').split(',')
791 name = remove_quotes(f.group('key'))
792 obj[name] = function_with_repr(self.build_function(argnames, f.group('code')), f'F<{name}>')
794 return obj
796 def extract_function_code(self, funcname):
797 """ @returns argnames, code """
798 func_m = re.search(
799 r'''(?xs)
801 function\s+%(name)s|
802 [{;,]\s*%(name)s\s*=\s*function|
803 (?:var|const|let)\s+%(name)s\s*=\s*function
804 )\s*
805 \((?P<args>[^)]*)\)\s*
806 (?P<code>{.+})''' % {'name': re.escape(funcname)},
807 self.code)
808 code, _ = self._separate_at_paren(func_m.group('code'))
809 if func_m is None:
810 raise self.Exception(f'Could not find JS function "{funcname}"')
811 return [x.strip() for x in func_m.group('args').split(',')], code
813 def extract_function(self, funcname):
814 return function_with_repr(
815 self.extract_function_from_code(*self.extract_function_code(funcname)),
816 f'F<{funcname}>')
818 def extract_function_from_code(self, argnames, code, *global_stack):
819 local_vars = {}
820 while True:
821 mobj = re.search(r'function\((?P<args>[^)]*)\)\s*{', code)
822 if mobj is None:
823 break
824 start, body_start = mobj.span()
825 body, remaining = self._separate_at_paren(code[body_start - 1:])
826 name = self._named_object(local_vars, self.extract_function_from_code(
827 [x.strip() for x in mobj.group('args').split(',')],
828 body, local_vars, *global_stack))
829 code = code[:start] + name + remaining
830 return self.build_function(argnames, code, local_vars, *global_stack)
832 def call_function(self, funcname, *args):
833 return self.extract_function(funcname)(args)
835 def build_function(self, argnames, code, *global_stack):
836 global_stack = list(global_stack) or [{}]
837 argnames = tuple(argnames)
839 def resf(args, kwargs={}, allow_recursion=100):
840 global_stack[0].update(itertools.zip_longest(argnames, args, fillvalue=None))
841 global_stack[0].update(kwargs)
842 var_stack = LocalNameSpace(*global_stack)
843 ret, should_abort = self.interpret_statement(code.replace('\n', ' '), var_stack, allow_recursion - 1)
844 if should_abort:
845 return ret
846 return resf