logo

youtube-dl

[mirror] Download/Watch videos from video hostersgit clone https://hacktivis.me/git/mirror/youtube-dl.git

jsinterp.py (42281B)


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