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