jsinterp.py 32 KB

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