]> jfr.im git - yt-dlp.git/blob - yt_dlp/jsinterp.py
[jsinterp] Fix escape in regex
[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:
249 if char in _QUOTES and in_quote in (char, None):
250 if in_quote or after_op or char != '/':
251 in_quote = None if in_quote and not in_regex_char_group else char
252 elif in_quote == '/' and char in '[]':
253 in_regex_char_group = char == '['
254 escaping = not escaping and in_quote and char == '\\'
255 after_op = not in_quote and char in OP_CHARS or (char.isspace() and after_op)
256
257 if char != delim[pos] or any(counters.values()) or in_quote:
258 pos = 0
259 continue
260 elif pos != delim_len:
261 pos += 1
262 continue
263 yield expr[start: idx - delim_len]
264 start, pos = idx + 1, 0
265 splits += 1
266 if max_split and splits >= max_split:
267 break
268 yield expr[start:]
269
270 @classmethod
271 def _separate_at_paren(cls, expr, delim):
272 separated = list(cls._separate(expr, delim, 1))
273 if len(separated) < 2:
274 raise cls.Exception(f'No terminating paren {delim}', expr)
275 return separated[0][1:].strip(), separated[1].strip()
276
277 def _operator(self, op, left_val, right_expr, expr, local_vars, allow_recursion):
278 if op in ('||', '&&'):
279 if (op == '&&') ^ _js_ternary(left_val):
280 return left_val # short circuiting
281 elif op == '??':
282 if left_val not in (None, JS_Undefined):
283 return left_val
284 elif op == '?':
285 right_expr = _js_ternary(left_val, *self._separate(right_expr, ':', 1))
286
287 right_val = self.interpret_expression(right_expr, local_vars, allow_recursion)
288 if not _OPERATORS.get(op):
289 return right_val
290
291 try:
292 return _OPERATORS[op](left_val, right_val)
293 except Exception as e:
294 raise self.Exception(f'Failed to evaluate {left_val!r} {op} {right_val!r}', expr, cause=e)
295
296 def _index(self, obj, idx, allow_undefined=False):
297 if idx == 'length':
298 return len(obj)
299 try:
300 return obj[int(idx)] if isinstance(obj, list) else obj[idx]
301 except Exception as e:
302 if allow_undefined:
303 return JS_Undefined
304 raise self.Exception(f'Cannot get index {idx}', repr(obj), cause=e)
305
306 def _dump(self, obj, namespace):
307 try:
308 return json.dumps(obj)
309 except TypeError:
310 return self._named_object(namespace, obj)
311
312 @Debugger.wrap_interpreter
313 def interpret_statement(self, stmt, local_vars, allow_recursion=100):
314 if allow_recursion < 0:
315 raise self.Exception('Recursion limit reached')
316 allow_recursion -= 1
317
318 should_return = False
319 sub_statements = list(self._separate(stmt, ';')) or ['']
320 expr = stmt = sub_statements.pop().strip()
321
322 for sub_stmt in sub_statements:
323 ret, should_return = self.interpret_statement(sub_stmt, local_vars, allow_recursion)
324 if should_return:
325 return ret, should_return
326
327 m = re.match(r'(?P<var>(?:var|const|let)\s)|return(?:\s+|(?=["\'])|$)|(?P<throw>throw\s+)', stmt)
328 if m:
329 expr = stmt[len(m.group(0)):].strip()
330 if m.group('throw'):
331 raise JS_Throw(self.interpret_expression(expr, local_vars, allow_recursion))
332 should_return = not m.group('var')
333 if not expr:
334 return None, should_return
335
336 if expr[0] in _QUOTES:
337 inner, outer = self._separate(expr, expr[0], 1)
338 if expr[0] == '/':
339 flags, outer = self._regex_flags(outer)
340 inner = re.compile(inner[1:], flags=flags)
341 else:
342 inner = json.loads(js_to_json(f'{inner}{expr[0]}', strict=True))
343 if not outer:
344 return inner, should_return
345 expr = self._named_object(local_vars, inner) + outer
346
347 if expr.startswith('new '):
348 obj = expr[4:]
349 if obj.startswith('Date('):
350 left, right = self._separate_at_paren(obj[4:], ')')
351 expr = unified_timestamp(
352 self.interpret_expression(left, local_vars, allow_recursion), False)
353 if not expr:
354 raise self.Exception(f'Failed to parse date {left!r}', expr)
355 expr = self._dump(int(expr * 1000), local_vars) + right
356 else:
357 raise self.Exception(f'Unsupported object {obj}', expr)
358
359 if expr.startswith('void '):
360 left = self.interpret_expression(expr[5:], local_vars, allow_recursion)
361 return None, should_return
362
363 if expr.startswith('{'):
364 inner, outer = self._separate_at_paren(expr, '}')
365 # Look for Map first
366 sub_expressions = [list(self._separate(sub_expr.strip(), ':', 1)) for sub_expr in self._separate(inner)]
367 if all(len(sub_expr) == 2 for sub_expr in sub_expressions):
368 def dict_item(key, val):
369 val = self.interpret_expression(val, local_vars, allow_recursion)
370 if re.match(_NAME_RE, key):
371 return key, val
372 return self.interpret_expression(key, local_vars, allow_recursion), val
373
374 return dict(dict_item(k, v) for k, v in sub_expressions), should_return
375
376 inner, should_abort = self.interpret_statement(inner, local_vars, allow_recursion)
377 if not outer or should_abort:
378 return inner, should_abort or should_return
379 else:
380 expr = self._dump(inner, local_vars) + outer
381
382 if expr.startswith('('):
383 inner, outer = self._separate_at_paren(expr, ')')
384 inner, should_abort = self.interpret_statement(inner, local_vars, allow_recursion)
385 if not outer or should_abort:
386 return inner, should_abort or should_return
387 else:
388 expr = self._dump(inner, local_vars) + outer
389
390 if expr.startswith('['):
391 inner, outer = self._separate_at_paren(expr, ']')
392 name = self._named_object(local_vars, [
393 self.interpret_expression(item, local_vars, allow_recursion)
394 for item in self._separate(inner)])
395 expr = name + outer
396
397 m = re.match(rf'''(?x)
398 (?P<try>try|finally)\s*|
399 (?P<catch>catch\s*(?P<err>\(\s*{_NAME_RE}\s*\)))|
400 (?P<switch>switch)\s*\(|
401 (?P<for>for)\s*\(|''', expr)
402 if m and m.group('try'):
403 if expr[m.end()] == '{':
404 try_expr, expr = self._separate_at_paren(expr[m.end():], '}')
405 else:
406 try_expr, expr = expr[m.end() - 1:], ''
407 try:
408 ret, should_abort = self.interpret_statement(try_expr, local_vars, allow_recursion)
409 if should_abort:
410 return ret, True
411 except JS_Throw as e:
412 local_vars[self._EXC_NAME] = e.error
413 except Exception as e:
414 # XXX: This works for now, but makes debugging future issues very hard
415 local_vars[self._EXC_NAME] = e
416 ret, should_abort = self.interpret_statement(expr, local_vars, allow_recursion)
417 return ret, should_abort or should_return
418
419 elif m and m.group('catch'):
420 catch_expr, expr = self._separate_at_paren(expr[m.end():], '}')
421 if self._EXC_NAME in local_vars:
422 catch_vars = local_vars.new_child({m.group('err'): local_vars.pop(self._EXC_NAME)})
423 ret, should_abort = self.interpret_statement(catch_expr, catch_vars, allow_recursion)
424 if should_abort:
425 return ret, True
426
427 ret, should_abort = self.interpret_statement(expr, local_vars, allow_recursion)
428 return ret, should_abort or should_return
429
430 elif m and m.group('for'):
431 constructor, remaining = self._separate_at_paren(expr[m.end() - 1:], ')')
432 if remaining.startswith('{'):
433 body, expr = self._separate_at_paren(remaining, '}')
434 else:
435 switch_m = re.match(r'switch\s*\(', remaining) # FIXME
436 if switch_m:
437 switch_val, remaining = self._separate_at_paren(remaining[switch_m.end() - 1:], ')')
438 body, expr = self._separate_at_paren(remaining, '}')
439 body = 'switch(%s){%s}' % (switch_val, body)
440 else:
441 body, expr = remaining, ''
442 start, cndn, increment = self._separate(constructor, ';')
443 self.interpret_expression(start, local_vars, allow_recursion)
444 while True:
445 if not _js_ternary(self.interpret_expression(cndn, local_vars, allow_recursion)):
446 break
447 try:
448 ret, should_abort = self.interpret_statement(body, local_vars, allow_recursion)
449 if should_abort:
450 return ret, True
451 except JS_Break:
452 break
453 except JS_Continue:
454 pass
455 self.interpret_expression(increment, local_vars, allow_recursion)
456 ret, should_abort = self.interpret_statement(expr, local_vars, allow_recursion)
457 return ret, should_abort or should_return
458
459 elif m and m.group('switch'):
460 switch_val, remaining = self._separate_at_paren(expr[m.end() - 1:], ')')
461 switch_val = self.interpret_expression(switch_val, local_vars, allow_recursion)
462 body, expr = self._separate_at_paren(remaining, '}')
463 items = body.replace('default:', 'case default:').split('case ')[1:]
464 for default in (False, True):
465 matched = False
466 for item in items:
467 case, stmt = (i.strip() for i in self._separate(item, ':', 1))
468 if default:
469 matched = matched or case == 'default'
470 elif not matched:
471 matched = (case != 'default'
472 and switch_val == self.interpret_expression(case, local_vars, allow_recursion))
473 if not matched:
474 continue
475 try:
476 ret, should_abort = self.interpret_statement(stmt, local_vars, allow_recursion)
477 if should_abort:
478 return ret
479 except JS_Break:
480 break
481 if matched:
482 break
483 ret, should_abort = self.interpret_statement(expr, local_vars, allow_recursion)
484 return ret, should_abort or should_return
485
486 # Comma separated statements
487 sub_expressions = list(self._separate(expr))
488 if len(sub_expressions) > 1:
489 for sub_expr in sub_expressions:
490 ret, should_abort = self.interpret_statement(sub_expr, local_vars, allow_recursion)
491 if should_abort:
492 return ret, True
493 return ret, False
494
495 for m in re.finditer(rf'''(?x)
496 (?P<pre_sign>\+\+|--)(?P<var1>{_NAME_RE})|
497 (?P<var2>{_NAME_RE})(?P<post_sign>\+\+|--)''', expr):
498 var = m.group('var1') or m.group('var2')
499 start, end = m.span()
500 sign = m.group('pre_sign') or m.group('post_sign')
501 ret = local_vars[var]
502 local_vars[var] += 1 if sign[0] == '+' else -1
503 if m.group('pre_sign'):
504 ret = local_vars[var]
505 expr = expr[:start] + self._dump(ret, local_vars) + expr[end:]
506
507 if not expr:
508 return None, should_return
509
510 m = re.match(fr'''(?x)
511 (?P<assign>
512 (?P<out>{_NAME_RE})(?:\[(?P<index>[^\]]+?)\])?\s*
513 (?P<op>{"|".join(map(re.escape, set(_OPERATORS) - _COMP_OPERATORS))})?
514 =(?!=)(?P<expr>.*)$
515 )|(?P<return>
516 (?!if|return|true|false|null|undefined|NaN)(?P<name>{_NAME_RE})$
517 )|(?P<indexing>
518 (?P<in>{_NAME_RE})\[(?P<idx>.+)\]$
519 )|(?P<attribute>
520 (?P<var>{_NAME_RE})(?:(?P<nullish>\?)?\.(?P<member>[^(]+)|\[(?P<member2>[^\]]+)\])\s*
521 )|(?P<function>
522 (?P<fname>{_NAME_RE})\((?P<args>.*)\)$
523 )''', expr)
524 if m and m.group('assign'):
525 left_val = local_vars.get(m.group('out'))
526
527 if not m.group('index'):
528 local_vars[m.group('out')] = self._operator(
529 m.group('op'), left_val, m.group('expr'), expr, local_vars, allow_recursion)
530 return local_vars[m.group('out')], should_return
531 elif left_val in (None, JS_Undefined):
532 raise self.Exception(f'Cannot index undefined variable {m.group("out")}', expr)
533
534 idx = self.interpret_expression(m.group('index'), local_vars, allow_recursion)
535 if not isinstance(idx, (int, float)):
536 raise self.Exception(f'List index {idx} must be integer', expr)
537 idx = int(idx)
538 left_val[idx] = self._operator(
539 m.group('op'), self._index(left_val, idx), m.group('expr'), expr, local_vars, allow_recursion)
540 return left_val[idx], should_return
541
542 elif expr.isdigit():
543 return int(expr), should_return
544
545 elif expr == 'break':
546 raise JS_Break()
547 elif expr == 'continue':
548 raise JS_Continue()
549 elif expr == 'undefined':
550 return JS_Undefined, should_return
551 elif expr == 'NaN':
552 return float('NaN'), should_return
553
554 elif m and m.group('return'):
555 return local_vars.get(m.group('name'), JS_Undefined), should_return
556
557 with contextlib.suppress(ValueError):
558 return json.loads(js_to_json(expr, strict=True)), should_return
559
560 if m and m.group('indexing'):
561 val = local_vars[m.group('in')]
562 idx = self.interpret_expression(m.group('idx'), local_vars, allow_recursion)
563 return self._index(val, idx), should_return
564
565 for op in _OPERATORS:
566 separated = list(self._separate(expr, op))
567 right_expr = separated.pop()
568 while True:
569 if op in '?<>*-' and len(separated) > 1 and not separated[-1].strip():
570 separated.pop()
571 elif not (separated and op == '?' and right_expr.startswith('.')):
572 break
573 right_expr = f'{op}{right_expr}'
574 if op != '-':
575 right_expr = f'{separated.pop()}{op}{right_expr}'
576 if not separated:
577 continue
578 left_val = self.interpret_expression(op.join(separated), local_vars, allow_recursion)
579 return self._operator(op, left_val, right_expr, expr, local_vars, allow_recursion), should_return
580
581 if m and m.group('attribute'):
582 variable, member, nullish = m.group('var', 'member', 'nullish')
583 if not member:
584 member = self.interpret_expression(m.group('member2'), local_vars, allow_recursion)
585 arg_str = expr[m.end():]
586 if arg_str.startswith('('):
587 arg_str, remaining = self._separate_at_paren(arg_str, ')')
588 else:
589 arg_str, remaining = None, arg_str
590
591 def assertion(cndn, msg):
592 """ assert, but without risk of getting optimized out """
593 if not cndn:
594 raise self.Exception(f'{member} {msg}', expr)
595
596 def eval_method():
597 if (variable, member) == ('console', 'debug'):
598 if Debugger.ENABLED:
599 Debugger.write(self.interpret_expression(f'[{arg_str}]', local_vars, allow_recursion))
600 return
601
602 types = {
603 'String': str,
604 'Math': float,
605 }
606 obj = local_vars.get(variable, types.get(variable, NO_DEFAULT))
607 if obj is NO_DEFAULT:
608 if variable not in self._objects:
609 try:
610 self._objects[variable] = self.extract_object(variable)
611 except self.Exception:
612 if not nullish:
613 raise
614 obj = self._objects.get(variable, JS_Undefined)
615
616 if nullish and obj is JS_Undefined:
617 return JS_Undefined
618
619 # Member access
620 if arg_str is None:
621 return self._index(obj, member, nullish)
622
623 # Function call
624 argvals = [
625 self.interpret_expression(v, local_vars, allow_recursion)
626 for v in self._separate(arg_str)]
627
628 if obj == str:
629 if member == 'fromCharCode':
630 assertion(argvals, 'takes one or more arguments')
631 return ''.join(map(chr, argvals))
632 raise self.Exception(f'Unsupported String method {member}', expr)
633 elif obj == float:
634 if member == 'pow':
635 assertion(len(argvals) == 2, 'takes two arguments')
636 return argvals[0] ** argvals[1]
637 raise self.Exception(f'Unsupported Math method {member}', expr)
638
639 if member == 'split':
640 assertion(argvals, 'takes one or more arguments')
641 assertion(len(argvals) == 1, 'with limit argument is not implemented')
642 return obj.split(argvals[0]) if argvals[0] else list(obj)
643 elif member == 'join':
644 assertion(isinstance(obj, list), 'must be applied on a list')
645 assertion(len(argvals) == 1, 'takes exactly one argument')
646 return argvals[0].join(obj)
647 elif member == 'reverse':
648 assertion(not argvals, 'does not take any arguments')
649 obj.reverse()
650 return obj
651 elif member == 'slice':
652 assertion(isinstance(obj, list), 'must be applied on a list')
653 assertion(len(argvals) == 1, 'takes exactly one argument')
654 return obj[argvals[0]:]
655 elif member == 'splice':
656 assertion(isinstance(obj, list), 'must be applied on a list')
657 assertion(argvals, 'takes one or more arguments')
658 index, howMany = map(int, (argvals + [len(obj)])[:2])
659 if index < 0:
660 index += len(obj)
661 add_items = argvals[2:]
662 res = []
663 for i in range(index, min(index + howMany, len(obj))):
664 res.append(obj.pop(index))
665 for i, item in enumerate(add_items):
666 obj.insert(index + i, item)
667 return res
668 elif member == 'unshift':
669 assertion(isinstance(obj, list), 'must be applied on a list')
670 assertion(argvals, 'takes one or more arguments')
671 for item in reversed(argvals):
672 obj.insert(0, item)
673 return obj
674 elif member == 'pop':
675 assertion(isinstance(obj, list), 'must be applied on a list')
676 assertion(not argvals, 'does not take any arguments')
677 if not obj:
678 return
679 return obj.pop()
680 elif member == 'push':
681 assertion(argvals, 'takes one or more arguments')
682 obj.extend(argvals)
683 return obj
684 elif member == 'forEach':
685 assertion(argvals, 'takes one or more arguments')
686 assertion(len(argvals) <= 2, 'takes at-most 2 arguments')
687 f, this = (argvals + [''])[:2]
688 return [f((item, idx, obj), {'this': this}, allow_recursion) for idx, item in enumerate(obj)]
689 elif member == 'indexOf':
690 assertion(argvals, 'takes one or more arguments')
691 assertion(len(argvals) <= 2, 'takes at-most 2 arguments')
692 idx, start = (argvals + [0])[:2]
693 try:
694 return obj.index(idx, start)
695 except ValueError:
696 return -1
697 elif member == 'charCodeAt':
698 assertion(isinstance(obj, str), 'must be applied on a string')
699 assertion(len(argvals) == 1, 'takes exactly one argument')
700 idx = argvals[0] if isinstance(argvals[0], int) else 0
701 if idx >= len(obj):
702 return None
703 return ord(obj[idx])
704
705 idx = int(member) if isinstance(obj, list) else member
706 return obj[idx](argvals, allow_recursion=allow_recursion)
707
708 if remaining:
709 ret, should_abort = self.interpret_statement(
710 self._named_object(local_vars, eval_method()) + remaining,
711 local_vars, allow_recursion)
712 return ret, should_return or should_abort
713 else:
714 return eval_method(), should_return
715
716 elif m and m.group('function'):
717 fname = m.group('fname')
718 argvals = [self.interpret_expression(v, local_vars, allow_recursion)
719 for v in self._separate(m.group('args'))]
720 if fname in local_vars:
721 return local_vars[fname](argvals, allow_recursion=allow_recursion), should_return
722 elif fname not in self._functions:
723 self._functions[fname] = self.extract_function(fname)
724 return self._functions[fname](argvals, allow_recursion=allow_recursion), should_return
725
726 raise self.Exception(
727 f'Unsupported JS expression {truncate_string(expr, 20, 20) if expr != stmt else ""}', stmt)
728
729 def interpret_expression(self, expr, local_vars, allow_recursion):
730 ret, should_return = self.interpret_statement(expr, local_vars, allow_recursion)
731 if should_return:
732 raise self.Exception('Cannot return from an expression', expr)
733 return ret
734
735 def extract_object(self, objname):
736 _FUNC_NAME_RE = r'''(?:[a-zA-Z$0-9]+|"[a-zA-Z$0-9]+"|'[a-zA-Z$0-9]+')'''
737 obj = {}
738 obj_m = re.search(
739 r'''(?x)
740 (?<!this\.)%s\s*=\s*{\s*
741 (?P<fields>(%s\s*:\s*function\s*\(.*?\)\s*{.*?}(?:,\s*)?)*)
742 }\s*;
743 ''' % (re.escape(objname), _FUNC_NAME_RE),
744 self.code)
745 if not obj_m:
746 raise self.Exception(f'Could not find object {objname}')
747 fields = obj_m.group('fields')
748 # Currently, it only supports function definitions
749 fields_m = re.finditer(
750 r'''(?x)
751 (?P<key>%s)\s*:\s*function\s*\((?P<args>(?:%s|,)*)\){(?P<code>[^}]+)}
752 ''' % (_FUNC_NAME_RE, _NAME_RE),
753 fields)
754 for f in fields_m:
755 argnames = f.group('args').split(',')
756 obj[remove_quotes(f.group('key'))] = self.build_function(argnames, f.group('code'))
757
758 return obj
759
760 def extract_function_code(self, funcname):
761 """ @returns argnames, code """
762 func_m = re.search(
763 r'''(?xs)
764 (?:
765 function\s+%(name)s|
766 [{;,]\s*%(name)s\s*=\s*function|
767 (?:var|const|let)\s+%(name)s\s*=\s*function
768 )\s*
769 \((?P<args>[^)]*)\)\s*
770 (?P<code>{.+})''' % {'name': re.escape(funcname)},
771 self.code)
772 code, _ = self._separate_at_paren(func_m.group('code'), '}')
773 if func_m is None:
774 raise self.Exception(f'Could not find JS function "{funcname}"')
775 return [x.strip() for x in func_m.group('args').split(',')], code
776
777 def extract_function(self, funcname):
778 return self.extract_function_from_code(*self.extract_function_code(funcname))
779
780 def extract_function_from_code(self, argnames, code, *global_stack):
781 local_vars = {}
782 while True:
783 mobj = re.search(r'function\((?P<args>[^)]*)\)\s*{', code)
784 if mobj is None:
785 break
786 start, body_start = mobj.span()
787 body, remaining = self._separate_at_paren(code[body_start - 1:], '}')
788 name = self._named_object(local_vars, self.extract_function_from_code(
789 [x.strip() for x in mobj.group('args').split(',')],
790 body, local_vars, *global_stack))
791 code = code[:start] + name + remaining
792 return self.build_function(argnames, code, local_vars, *global_stack)
793
794 def call_function(self, funcname, *args):
795 return self.extract_function(funcname)(args)
796
797 def build_function(self, argnames, code, *global_stack):
798 global_stack = list(global_stack) or [{}]
799 argnames = tuple(argnames)
800
801 def resf(args, kwargs={}, allow_recursion=100):
802 global_stack[0].update(itertools.zip_longest(argnames, args, fillvalue=None))
803 global_stack[0].update(kwargs)
804 var_stack = LocalNameSpace(*global_stack)
805 ret, should_abort = self.interpret_statement(code.replace('\n', ' '), var_stack, allow_recursion - 1)
806 if should_abort:
807 return ret
808 return resf