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