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