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