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