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