jsinterp.py 37 KB

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