23 if x
in (None, JS_Undefined
):
25 with contextlib
.suppress(TypeError):
26 if math
.isnan(x
): # NB: NaN cannot be checked by membership
31 return op(zeroise(a
), zeroise(b
)) & 0xffffffff
39 if JS_Undefined
in (a
, b
):
41 return op(a
or 0, b
or 0)
47 if JS_Undefined
in (a
, b
) or not (a
or b
):
49 return (a
or 0) / b
if b
else float('inf')
53 if JS_Undefined
in (a
, b
) or not b
:
60 return 1 # even 0 ** 0 !!
61 elif JS_Undefined
in (a
, b
):
69 if {a
, b
} <= {None, JS_Undefined
}:
79 if JS_Undefined
in (a
, b
):
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)
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
):
92 with contextlib
.suppress(TypeError):
93 if math
.isnan(cndn
): # NB: NaN cannot be checked by membership
98 # Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
99 _OPERATORS
= { # None => Defined in JSInterpreter._operator
105 '|': _js_bit_op(operator
.or_
),
106 '^': _js_bit_op(operator
.xor
),
107 '&': _js_bit_op(operator
.and_
),
110 '!==': operator
.is_not
,
111 '==': _js_eq_op(operator
.eq
),
112 '!=': _js_eq_op(operator
.ne
),
114 '<=': _js_comp_op(operator
.le
),
115 '>=': _js_comp_op(operator
.ge
),
116 '<': _js_comp_op(operator
.lt
),
117 '>': _js_comp_op(operator
.gt
),
119 '>>': _js_bit_op(operator
.rshift
),
120 '<<': _js_bit_op(operator
.lshift
),
122 '+': _js_arith_op(operator
.add
),
123 '-': _js_arith_op(operator
.sub
),
125 '*': _js_arith_op(operator
.mul
),
131 _COMP_OPERATORS
= {'===', '!==', '==', '!=', '<=', '>=', '<', '>'}
133 _NAME_RE
= r
'[a-zA-Z_$][\w$]*'
134 _MATCHING_PARENS
= dict(zip(*zip('()', '{}', '[]')))
142 class JS_Break(ExtractorError
):
144 ExtractorError
.__init
__(self
, 'Invalid break')
147 class JS_Continue(ExtractorError
):
149 ExtractorError
.__init
__(self
, 'Invalid continue')
152 class JS_Throw(ExtractorError
):
153 def __init__(self
, e
):
155 ExtractorError
.__init
__(self
, f
'Uncaught exception {e}')
158 class LocalNameSpace(collections
.ChainMap
):
159 def __setitem__(self
, key
, value
):
160 for scope
in self
.maps
:
164 self
.maps
[0][key
] = value
166 def __delitem__(self
, key
):
167 raise NotImplementedError('Deleting is not supported')
172 ENABLED
= False and 'pytest' in sys
.modules
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')
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
)
185 ret
, should_ret
= f(self
, stmt
, local_vars
, allow_recursion
, *args
, **kwargs
)
186 except Exception as e
:
188 if isinstance(e
, ExtractorError
):
190 cls
.write('=> Raises:', e
, '<-|', stmt
, level
=allow_recursion
)
192 if cls
.ENABLED
and stmt
.strip():
193 if should_ret
or repr(ret
) != stmt
:
194 cls
.write(['->', '=>'][should_ret
], repr(ret
), '<-|', stmt
, level
=allow_recursion
)
195 return ret
, should_ret
196 return interpret_statement
200 __named_object_counter
= 0
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
215 def __init__(self
, code
, objects
=None):
216 self
.code
, self
._functions
= code
, {}
217 self
._objects
= {} if objects
is None else objects
219 class Exception(ExtractorError
): # noqa: A001
220 def __init__(self
, msg
, expr
=None, *args
, **kwargs
):
222 msg
= f
'{msg.rstrip()} in: {truncate_string(expr, 50, 50)}'
223 super().__init
__(msg
, *args
, **kwargs
)
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
234 def _regex_flags(cls
, expr
):
238 for idx
, ch
in enumerate(expr
): # noqa: B007
239 if ch
not in cls
._RE
_FLAGS
:
241 flags |
= cls
._RE
_FLAGS
[ch
]
242 return flags
, expr
[idx
+ 1:]
245 def _separate(expr
, delim
=',', max_split
=None):
246 OP_CHARS
= '+-*/%&|^=<>!,;{}:['
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
= None, False, True, 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
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
)
270 if char
!= delim
[pos
] or any(counters
.values()) or in_quote
or in_unary_op
:
273 elif pos
!= delim_len
:
276 yield expr
[start
: idx
- delim_len
]
277 start
, pos
= idx
+ 1, 0
279 if max_split
and splits
>= max_split
:
284 def _separate_at_paren(cls
, expr
, delim
=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()
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
297 if left_val
not in (None, JS_Undefined
):
300 right_expr
= _js_ternary(left_val
, *self
._separate
(right_expr
, ':', 1))
302 right_val
= self
.interpret_expression(right_expr
, local_vars
, allow_recursion
)
303 if not _OPERATORS
.get(op
):
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
)
311 def _index(self
, obj
, idx
, allow_undefined
=False):
315 return obj
[int(idx
)] if isinstance(obj
, list) else obj
[idx
]
316 except Exception as e
:
319 raise self
.Exception(f
'Cannot get index {idx}', repr(obj
), cause
=e
)
321 def _dump(self
, obj
, namespace
):
323 return json
.dumps(obj
)
325 return self
._named
_object
(namespace
, obj
)
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')
333 should_return
= False
334 sub_statements
= list(self
._separate
(stmt
, ';')) or ['']
335 expr
= stmt
= sub_statements
.pop().strip()
337 for sub_stmt
in sub_statements
:
338 ret
, should_return
= self
.interpret_statement(sub_stmt
, local_vars
, allow_recursion
)
340 return ret
, should_return
342 m
= re
.match(r
'(?P<var>(?:var|const|let)\s)|return(?:\s+|(?=["\'])|$
)|
(?P
<throw
>throw\s
+)', stmt)
344 expr = stmt[len(m.group(0)):].strip()
346 raise JS_Throw(self.interpret_expression(expr, local_vars, allow_recursion))
347 should_return = not m.group('var
')
349 return None, should_return
351 if expr[0] in _QUOTES:
352 inner, outer = self._separate(expr, expr[0], 1)
354 flags, outer = self._regex_flags(outer)
355 # We don't support regex methods yet
, so no point compiling it
356 inner
= f
'{inner}/{flags}'
357 # Avoid https://github.com/python/cpython/issues/74534
358 # inner = re.compile(inner[1:].replace('[[', r'[\['), flags=flags)
360 inner
= json
.loads(js_to_json(f
'{inner}{expr[0]}', strict
=True))
362 return inner
, should_return
363 expr
= self
._named
_object
(local_vars
, inner
) + outer
365 if expr
.startswith('new '):
367 if obj
.startswith('Date('):
368 left
, right
= self
._separate
_at
_paren
(obj
[4:])
369 date
= unified_timestamp(
370 self
.interpret_expression(left
, local_vars
, allow_recursion
), False)
372 raise self
.Exception(f
'Failed to parse date {left!r}', expr
)
373 expr
= self
._dump
(int(date
* 1000), local_vars
) + right
375 raise self
.Exception(f
'Unsupported object {obj}', expr
)
377 if expr
.startswith('void '):
378 left
= self
.interpret_expression(expr
[5:], local_vars
, allow_recursion
)
379 return None, should_return
381 if expr
.startswith('{'):
382 inner
, outer
= self
._separate
_at
_paren
(expr
)
383 # try for object expression (Map)
384 sub_expressions
= [list(self
._separate
(sub_expr
.strip(), ':', 1)) for sub_expr
in self
._separate
(inner
)]
385 if all(len(sub_expr
) == 2 for sub_expr
in sub_expressions
):
386 def dict_item(key
, val
):
387 val
= self
.interpret_expression(val
, local_vars
, allow_recursion
)
388 if re
.match(_NAME_RE
, key
):
390 return self
.interpret_expression(key
, local_vars
, allow_recursion
), val
392 return dict(dict_item(k
, v
) for k
, v
in sub_expressions
), should_return
394 inner
, should_abort
= self
.interpret_statement(inner
, local_vars
, allow_recursion
)
395 if not outer
or should_abort
:
396 return inner
, should_abort
or should_return
398 expr
= self
._dump
(inner
, local_vars
) + outer
400 if expr
.startswith('('):
401 inner
, outer
= self
._separate
_at
_paren
(expr
)
402 inner
, should_abort
= self
.interpret_statement(inner
, local_vars
, allow_recursion
)
403 if not outer
or should_abort
:
404 return inner
, should_abort
or should_return
406 expr
= self
._dump
(inner
, local_vars
) + outer
408 if expr
.startswith('['):
409 inner
, outer
= self
._separate
_at
_paren
(expr
)
410 name
= self
._named
_object
(local_vars
, [
411 self
.interpret_expression(item
, local_vars
, allow_recursion
)
412 for item
in self
._separate
(inner
)])
415 m
= re
.match(r
'''(?x)
418 (?P<switch>switch)\s*\(|
421 md
= m
.groupdict() if m
else {}
423 cndn
, expr
= self
._separate
_at
_paren
(expr
[m
.end() - 1:])
424 if_expr
, expr
= self
._separate
_at
_paren
(expr
.lstrip())
425 # TODO: "else if" is not handled
427 m
= re
.match(r
'else\s*{', expr
)
429 else_expr
, expr
= self
._separate
_at
_paren
(expr
[m
.end() - 1:])
430 cndn
= _js_ternary(self
.interpret_expression(cndn
, local_vars
, allow_recursion
))
431 ret
, should_abort
= self
.interpret_statement(
432 if_expr
if cndn
else else_expr
, local_vars
, allow_recursion
)
437 try_expr
, expr
= self
._separate
_at
_paren
(expr
[m
.end() - 1:])
440 ret
, should_abort
= self
.interpret_statement(try_expr
, local_vars
, allow_recursion
)
443 except Exception as e
:
444 # XXX: This works for now, but makes debugging future issues very hard
447 pending
= (None, False)
448 m
= re
.match(fr
'catch\s*(?P<err>\(\s*{_NAME_RE}\s*\))?\{{', expr
)
450 sub_expr
, expr
= self
._separate
_at
_paren
(expr
[m
.end() - 1:])
454 catch_vars
[m
.group('err')] = err
.error
if isinstance(err
, JS_Throw
) else err
455 catch_vars
= local_vars
.new_child(catch_vars
)
456 err
, pending
= None, self
.interpret_statement(sub_expr
, catch_vars
, allow_recursion
)
458 m
= re
.match(r
'finally\s*\{', expr
)
460 sub_expr
, expr
= self
._separate
_at
_paren
(expr
[m
.end() - 1:])
461 ret
, should_abort
= self
.interpret_statement(sub_expr
, local_vars
, allow_recursion
)
465 ret
, should_abort
= pending
473 constructor
, remaining
= self
._separate
_at
_paren
(expr
[m
.end() - 1:])
474 if remaining
.startswith('{'):
475 body
, expr
= self
._separate
_at
_paren
(remaining
)
477 switch_m
= re
.match(r
'switch\s*\(', remaining
) # FIXME: ?
479 switch_val
, remaining
= self
._separate
_at
_paren
(remaining
[switch_m
.end() - 1:])
480 body
, expr
= self
._separate
_at
_paren
(remaining
, '}')
481 body
= 'switch(%s){%s}' % (switch_val
, body
)
483 body
, expr
= remaining
, ''
484 start
, cndn
, increment
= self
._separate
(constructor
, ';')
485 self
.interpret_expression(start
, local_vars
, allow_recursion
)
487 if not _js_ternary(self
.interpret_expression(cndn
, local_vars
, allow_recursion
)):
490 ret
, should_abort
= self
.interpret_statement(body
, local_vars
, allow_recursion
)
497 self
.interpret_expression(increment
, local_vars
, allow_recursion
)
499 elif md
.get('switch'):
500 switch_val
, remaining
= self
._separate
_at
_paren
(expr
[m
.end() - 1:])
501 switch_val
= self
.interpret_expression(switch_val
, local_vars
, allow_recursion
)
502 body
, expr
= self
._separate
_at
_paren
(remaining
, '}')
503 items
= body
.replace('default:', 'case default:').split('case ')[1:]
504 for default
in (False, True):
507 case
, stmt
= (i
.strip() for i
in self
._separate
(item
, ':', 1))
509 matched
= matched
or case
== 'default'
511 matched
= (case
!= 'default'
512 and switch_val
== self
.interpret_expression(case
, local_vars
, allow_recursion
))
516 ret
, should_abort
= self
.interpret_statement(stmt
, local_vars
, allow_recursion
)
525 ret
, should_abort
= self
.interpret_statement(expr
, local_vars
, allow_recursion
)
526 return ret
, should_abort
or should_return
528 # Comma separated statements
529 sub_expressions
= list(self
._separate
(expr
))
530 if len(sub_expressions
) > 1:
531 for sub_expr
in sub_expressions
:
532 ret
, should_abort
= self
.interpret_statement(sub_expr
, local_vars
, allow_recursion
)
537 for m
in re
.finditer(rf
'''(?x)
538 (?P<pre_sign>\+\+|--)(?P<var1>{_NAME_RE})|
539 (?P<var2>{_NAME_RE})(?P<post_sign>\+\+|--)''', expr
):
540 var
= m
.group('var1') or m
.group('var2')
541 start
, end
= m
.span()
542 sign
= m
.group('pre_sign') or m
.group('post_sign')
543 ret
= local_vars
[var
]
544 local_vars
[var
] += 1 if sign
[0] == '+' else -1
545 if m
.group('pre_sign'):
546 ret
= local_vars
[var
]
547 expr
= expr
[:start
] + self
._dump
(ret
, local_vars
) + expr
[end
:]
550 return None, should_return
552 m
= re
.match(fr
'''(?x)
554 (?P<out>{_NAME_RE})(?:\[(?P<index>[^\]]+?)\])?\s*
555 (?P<op>{"|".join(map(re.escape, set(_OPERATORS) - _COMP_OPERATORS))})?
558 (?!if|return|true|false|null|undefined|NaN)(?P<name>{_NAME_RE})$
560 (?P<in>{_NAME_RE})\[(?P<idx>.+)\]$
562 (?P<var>{_NAME_RE})(?:(?P<nullish>\?)?\.(?P<member>[^(]+)|\[(?P<member2>[^\]]+)\])\s*
564 (?P<fname>{_NAME_RE})\((?P<args>.*)\)$
566 if m
and m
.group('assign'):
567 left_val
= local_vars
.get(m
.group('out'))
569 if not m
.group('index'):
570 local_vars
[m
.group('out')] = self
._operator
(
571 m
.group('op'), left_val
, m
.group('expr'), expr
, local_vars
, allow_recursion
)
572 return local_vars
[m
.group('out')], should_return
573 elif left_val
in (None, JS_Undefined
):
574 raise self
.Exception(f
'Cannot index undefined variable {m.group("out")}', expr
)
576 idx
= self
.interpret_expression(m
.group('index'), local_vars
, allow_recursion
)
577 if not isinstance(idx
, (int, float)):
578 raise self
.Exception(f
'List index {idx} must be integer', expr
)
580 left_val
[idx
] = self
._operator
(
581 m
.group('op'), self
._index
(left_val
, idx
), m
.group('expr'), expr
, local_vars
, allow_recursion
)
582 return left_val
[idx
], should_return
585 return int(expr
), should_return
587 elif expr
== 'break':
589 elif expr
== 'continue':
591 elif expr
== 'undefined':
592 return JS_Undefined
, should_return
594 return float('NaN'), should_return
596 elif m
and m
.group('return'):
597 return local_vars
.get(m
.group('name'), JS_Undefined
), should_return
599 with contextlib
.suppress(ValueError):
600 return json
.loads(js_to_json(expr
, strict
=True)), should_return
602 if m
and m
.group('indexing'):
603 val
= local_vars
[m
.group('in')]
604 idx
= self
.interpret_expression(m
.group('idx'), local_vars
, allow_recursion
)
605 return self
._index
(val
, idx
), should_return
607 for op
in _OPERATORS
:
608 separated
= list(self
._separate
(expr
, op
))
609 right_expr
= separated
.pop()
611 if op
in '?<>*-' and len(separated
) > 1 and not separated
[-1].strip():
613 elif not (separated
and op
== '?' and right_expr
.startswith('.')):
615 right_expr
= f
'{op}{right_expr}'
617 right_expr
= f
'{separated.pop()}{op}{right_expr}'
620 left_val
= self
.interpret_expression(op
.join(separated
), local_vars
, allow_recursion
)
621 return self
._operator
(op
, left_val
, right_expr
, expr
, local_vars
, allow_recursion
), should_return
623 if m
and m
.group('attribute'):
624 variable
, member
, nullish
= m
.group('var', 'member', 'nullish')
626 member
= self
.interpret_expression(m
.group('member2'), local_vars
, allow_recursion
)
627 arg_str
= expr
[m
.end():]
628 if arg_str
.startswith('('):
629 arg_str
, remaining
= self
._separate
_at
_paren
(arg_str
)
631 arg_str
, remaining
= None, arg_str
633 def assertion(cndn
, msg
):
634 """ assert, but without risk of getting optimized out """
636 raise self
.Exception(f
'{member} {msg}', expr
)
641 if (variable
, member
) == ('console', 'debug'):
643 Debugger
.write(self
.interpret_expression(f
'[{arg_str}]', local_vars
, allow_recursion
))
651 obj
= local_vars
.get(variable
, types
.get(variable
, NO_DEFAULT
))
652 if obj
is NO_DEFAULT
:
653 if variable
not in self
._objects
:
655 self
._objects
[variable
] = self
.extract_object(variable
)
656 except self
.Exception:
659 obj
= self
._objects
.get(variable
, JS_Undefined
)
661 if nullish
and obj
is JS_Undefined
:
666 return self
._index
(obj
, member
, nullish
)
670 self
.interpret_expression(v
, local_vars
, allow_recursion
)
671 for v
in self
._separate
(arg_str
)]
673 # Fixup prototype call
674 if isinstance(obj
, type) and member
.startswith('prototype.'):
675 new_member
, _
, func_prototype
= member
.partition('.')[2].partition('.')
676 assertion(argvals
, 'takes one or more arguments')
677 assertion(isinstance(argvals
[0], obj
), f
'needs binding to type {obj}')
678 if func_prototype
== 'call':
679 obj
, *argvals
= argvals
680 elif func_prototype
== 'apply':
681 assertion(len(argvals
) == 2, 'takes two arguments')
682 obj
, argvals
= argvals
683 assertion(isinstance(argvals
, list), 'second argument needs to be a list')
685 raise self
.Exception(f
'Unsupported Function method {func_prototype}', expr
)
689 if member
== 'fromCharCode':
690 assertion(argvals
, 'takes one or more arguments')
691 return ''.join(map(chr, argvals
))
692 raise self
.Exception(f
'Unsupported String method {member}', expr
)
695 assertion(len(argvals
) == 2, 'takes two arguments')
696 return argvals
[0] ** argvals
[1]
697 raise self
.Exception(f
'Unsupported Math method {member}', expr
)
699 if member
== 'split':
700 assertion(argvals
, 'takes one or more arguments')
701 assertion(len(argvals
) == 1, 'with limit argument is not implemented')
702 return obj
.split(argvals
[0]) if argvals
[0] else list(obj
)
703 elif member
== 'join':
704 assertion(isinstance(obj
, list), 'must be applied on a list')
705 assertion(len(argvals
) == 1, 'takes exactly one argument')
706 return argvals
[0].join(obj
)
707 elif member
== 'reverse':
708 assertion(not argvals
, 'does not take any arguments')
711 elif member
== 'slice':
712 assertion(isinstance(obj
, (list, str)), 'must be applied on a list or string')
713 assertion(len(argvals
) <= 2, 'takes between 0 and 2 arguments')
714 return obj
[slice(*argvals
, None)]
715 elif member
== 'splice':
716 assertion(isinstance(obj
, list), 'must be applied on a list')
717 assertion(argvals
, 'takes one or more arguments')
718 index
, how_many
= map(int, ([*argvals
, len(obj
)])[:2])
721 add_items
= argvals
[2:]
723 for _
in range(index
, min(index
+ how_many
, len(obj
))):
724 res
.append(obj
.pop(index
))
725 for i
, item
in enumerate(add_items
):
726 obj
.insert(index
+ i
, item
)
728 elif member
== 'unshift':
729 assertion(isinstance(obj
, list), 'must be applied on a list')
730 assertion(argvals
, 'takes one or more arguments')
731 for item
in reversed(argvals
):
734 elif member
== 'pop':
735 assertion(isinstance(obj
, list), 'must be applied on a list')
736 assertion(not argvals
, 'does not take any arguments')
740 elif member
== 'push':
741 assertion(argvals
, 'takes one or more arguments')
744 elif member
== 'forEach':
745 assertion(argvals
, 'takes one or more arguments')
746 assertion(len(argvals
) <= 2, 'takes at-most 2 arguments')
747 f
, this
= ([*argvals
, ''])[:2]
748 return [f((item
, idx
, obj
), {'this': this
}, allow_recursion
) for idx
, item
in enumerate(obj
)]
749 elif member
== 'indexOf':
750 assertion(argvals
, 'takes one or more arguments')
751 assertion(len(argvals
) <= 2, 'takes at-most 2 arguments')
752 idx
, start
= ([*argvals
, 0])[:2]
754 return obj
.index(idx
, start
)
757 elif member
== 'charCodeAt':
758 assertion(isinstance(obj
, str), 'must be applied on a string')
759 assertion(len(argvals
) == 1, 'takes exactly one argument')
760 idx
= argvals
[0] if isinstance(argvals
[0], int) else 0
765 idx
= int(member
) if isinstance(obj
, list) else member
766 return obj
[idx
](argvals
, allow_recursion
=allow_recursion
)
769 ret
, should_abort
= self
.interpret_statement(
770 self
._named
_object
(local_vars
, eval_method()) + remaining
,
771 local_vars
, allow_recursion
)
772 return ret
, should_return
or should_abort
774 return eval_method(), should_return
776 elif m
and m
.group('function'):
777 fname
= m
.group('fname')
778 argvals
= [self
.interpret_expression(v
, local_vars
, allow_recursion
)
779 for v
in self
._separate
(m
.group('args'))]
780 if fname
in local_vars
:
781 return local_vars
[fname
](argvals
, allow_recursion
=allow_recursion
), should_return
782 elif fname
not in self
._functions
:
783 self
._functions
[fname
] = self
.extract_function(fname
)
784 return self
._functions
[fname
](argvals
, allow_recursion
=allow_recursion
), should_return
786 raise self
.Exception(
787 f
'Unsupported JS expression {truncate_string(expr, 20, 20) if expr != stmt else ""}', stmt
)
789 def interpret_expression(self
, expr
, local_vars
, allow_recursion
):
790 ret
, should_return
= self
.interpret_statement(expr
, local_vars
, allow_recursion
)
792 raise self
.Exception('Cannot return from an expression', expr
)
795 def extract_object(self
, objname
):
796 _FUNC_NAME_RE
= r
'''(?:[a-zA-Z$0-9]+|"[a-zA-Z$0-9]+"|'[a-zA-Z$0-9]+')'''
801 (?P<fields>(%s\s*:\s*function\s*\(.*?\)\s*{.*?}(?:,\s*)?)*)
803 ''' % (re
.escape(objname
), _FUNC_NAME_RE
),
806 raise self
.Exception(f
'Could not find object {objname}')
807 fields
= obj_m
.group('fields')
808 # Currently, it only supports function definitions
809 fields_m
= re
.finditer(
811 (?P<key>%s)\s*:\s*function\s*\((?P<args>(?:%s|,)*)\){(?P<code>[^}]+)}
812 ''' % (_FUNC_NAME_RE
, _NAME_RE
),
815 argnames
= f
.group('args').split(',')
816 name
= remove_quotes(f
.group('key'))
817 obj
[name
] = function_with_repr(self
.build_function(argnames
, f
.group('code')), f
'F<{name}>')
821 def extract_function_code(self
, funcname
):
822 """ @returns argnames, code """
827 [{;,]\s*%(name)s\s*=\s*function|
828 (?:var|const|let)\s+%(name)s\s*=\s*function
830 \((?P<args>[^)]*)\)\s*
831 (?P<code>{.+})''' % {'name': re
.escape(funcname
)},
834 raise self
.Exception(f
'Could not find JS function "{funcname}"')
835 code
, _
= self
._separate
_at
_paren
(func_m
.group('code'))
836 return [x
.strip() for x
in func_m
.group('args').split(',')], code
838 def extract_function(self
, funcname
):
839 return function_with_repr(
840 self
.extract_function_from_code(*self
.extract_function_code(funcname
)),
843 def extract_function_from_code(self
, argnames
, code
, *global_stack
):
846 mobj
= re
.search(r
'function\((?P<args>[^)]*)\)\s*{', code
)
849 start
, body_start
= mobj
.span()
850 body
, remaining
= self
._separate
_at
_paren
(code
[body_start
- 1:])
851 name
= self
._named
_object
(local_vars
, self
.extract_function_from_code(
852 [x
.strip() for x
in mobj
.group('args').split(',')],
853 body
, local_vars
, *global_stack
))
854 code
= code
[:start
] + name
+ remaining
855 return self
.build_function(argnames
, code
, local_vars
, *global_stack
)
857 def call_function(self
, funcname
, *args
):
858 return self
.extract_function(funcname
)(args
)
860 def build_function(self
, argnames
, code
, *global_stack
):
861 global_stack
= list(global_stack
) or [{}]
862 argnames
= tuple(argnames
)
864 def resf(args
, kwargs
={}, allow_recursion
=100):
865 global_stack
[0].update(itertools
.zip_longest(argnames
, args
, fillvalue
=None))
866 global_stack
[0].update(kwargs
)
867 var_stack
= LocalNameSpace(*global_stack
)
868 ret
, should_abort
= self
.interpret_statement(code
.replace('\n', ' '), var_stack
, allow_recursion
- 1)