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