logo

youtube-dl

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

jsinterp.py (61069B)


  1. # coding: utf-8
  2. from __future__ import unicode_literals
  3. import calendar
  4. import itertools
  5. import json
  6. import operator
  7. import re
  8. import time
  9. from functools import update_wrapper, wraps
  10. from .utils import (
  11. error_to_compat_str,
  12. ExtractorError,
  13. float_or_none,
  14. int_or_none,
  15. js_to_json,
  16. remove_quotes,
  17. str_or_none,
  18. unified_timestamp,
  19. variadic,
  20. write_string,
  21. )
  22. from .compat import (
  23. compat_basestring,
  24. compat_chr,
  25. compat_collections_chain_map as ChainMap,
  26. compat_contextlib_suppress,
  27. compat_filter as filter,
  28. compat_int,
  29. compat_integer_types,
  30. compat_itertools_zip_longest as zip_longest,
  31. compat_map as map,
  32. compat_numeric_types,
  33. compat_str,
  34. )
  35. # name JS functions
  36. class function_with_repr(object):
  37. # from yt_dlp/utils.py, but in this module
  38. # repr_ is always set
  39. def __init__(self, func, repr_):
  40. update_wrapper(self, func)
  41. self.func, self.__repr = func, repr_
  42. def __call__(self, *args, **kwargs):
  43. return self.func(*args, **kwargs)
  44. def __repr__(self):
  45. return self.__repr
  46. # name JS operators
  47. def wraps_op(op):
  48. def update_and_rename_wrapper(w):
  49. f = update_wrapper(w, op)
  50. # fn names are str in both Py 2/3
  51. f.__name__ = str('JS_') + f.__name__
  52. return f
  53. return update_and_rename_wrapper
  54. # NB In principle NaN cannot be checked by membership.
  55. # Here all NaN values are actually this one, so _NaN is _NaN,
  56. # although _NaN != _NaN. Ditto Infinity.
  57. _NaN = float('nan')
  58. _Infinity = float('inf')
  59. class JS_Undefined(object):
  60. pass
  61. def _js_bit_op(op, is_shift=False):
  62. def zeroise(x, is_shift_arg=False):
  63. if isinstance(x, compat_integer_types):
  64. return (x % 32) if is_shift_arg else (x & 0xffffffff)
  65. try:
  66. x = float(x)
  67. if is_shift_arg:
  68. x = int(x % 32)
  69. elif x < 0:
  70. x = -compat_int(-x % 0xffffffff)
  71. else:
  72. x = compat_int(x % 0xffffffff)
  73. except (ValueError, TypeError):
  74. # also here for int(NaN), including float('inf') % 32
  75. x = 0
  76. return x
  77. @wraps_op(op)
  78. def wrapped(a, b):
  79. return op(zeroise(a), zeroise(b, is_shift)) & 0xffffffff
  80. return wrapped
  81. def _js_arith_op(op, div=False):
  82. @wraps_op(op)
  83. def wrapped(a, b):
  84. if JS_Undefined in (a, b):
  85. return _NaN
  86. # null, "" --> 0
  87. a, b = (float_or_none(
  88. (x.strip() if isinstance(x, compat_basestring) else x) or 0,
  89. default=_NaN) for x in (a, b))
  90. if _NaN in (a, b):
  91. return _NaN
  92. try:
  93. return op(a, b)
  94. except ZeroDivisionError:
  95. return _NaN if not (div and (a or b)) else _Infinity
  96. return wrapped
  97. _js_arith_add = _js_arith_op(operator.add)
  98. def _js_add(a, b):
  99. if not (isinstance(a, compat_basestring) or isinstance(b, compat_basestring)):
  100. return _js_arith_add(a, b)
  101. if not isinstance(a, compat_basestring):
  102. a = _js_toString(a)
  103. elif not isinstance(b, compat_basestring):
  104. b = _js_toString(b)
  105. return operator.concat(a, b)
  106. _js_mod = _js_arith_op(operator.mod)
  107. __js_exp = _js_arith_op(operator.pow)
  108. def _js_exp(a, b):
  109. if not b:
  110. return 1 # even 0 ** 0 !!
  111. return __js_exp(a, b)
  112. def _js_to_primitive(v):
  113. return (
  114. ','.join(map(_js_toString, v)) if isinstance(v, list)
  115. else '[object Object]' if isinstance(v, dict)
  116. else compat_str(v) if not isinstance(v, (
  117. compat_numeric_types, compat_basestring))
  118. else v
  119. )
  120. # more exact: yt-dlp/yt-dlp#12110
  121. def _js_toString(v):
  122. return (
  123. 'undefined' if v is JS_Undefined
  124. else 'Infinity' if v == _Infinity
  125. else 'NaN' if v is _NaN
  126. else 'null' if v is None
  127. # bool <= int: do this first
  128. else ('false', 'true')[v] if isinstance(v, bool)
  129. else re.sub(r'(?<=\d)\.?0*$', '', '{0:.7f}'.format(v)) if isinstance(v, compat_numeric_types)
  130. else _js_to_primitive(v))
  131. _nullish = frozenset((None, JS_Undefined))
  132. def _js_eq(a, b):
  133. # NaN != any
  134. if _NaN in (a, b):
  135. return False
  136. # Object is Object
  137. if isinstance(a, type(b)) and isinstance(b, (dict, list)):
  138. return operator.is_(a, b)
  139. # general case
  140. if a == b:
  141. return True
  142. # null == undefined
  143. a_b = set((a, b))
  144. if a_b & _nullish:
  145. return a_b <= _nullish
  146. a, b = _js_to_primitive(a), _js_to_primitive(b)
  147. if not isinstance(a, compat_basestring):
  148. a, b = b, a
  149. # Number to String: convert the string to a number
  150. # Conversion failure results in ... false
  151. if isinstance(a, compat_basestring):
  152. return float_or_none(a) == b
  153. return a == b
  154. def _js_neq(a, b):
  155. return not _js_eq(a, b)
  156. def _js_id_op(op):
  157. @wraps_op(op)
  158. def wrapped(a, b):
  159. if _NaN in (a, b):
  160. return op(_NaN, None)
  161. if not isinstance(a, (compat_basestring, compat_numeric_types)):
  162. a, b = b, a
  163. # strings are === if ==
  164. # why 'a' is not 'a': https://stackoverflow.com/a/1504848
  165. if isinstance(a, (compat_basestring, compat_numeric_types)):
  166. return a == b if op(0, 0) else a != b
  167. return op(a, b)
  168. return wrapped
  169. def _js_comp_op(op):
  170. @wraps_op(op)
  171. def wrapped(a, b):
  172. if JS_Undefined in (a, b):
  173. return False
  174. if isinstance(a, compat_basestring):
  175. b = compat_str(b or 0)
  176. elif isinstance(b, compat_basestring):
  177. a = compat_str(a or 0)
  178. return op(a or 0, b or 0)
  179. return wrapped
  180. def _js_ternary(cndn, if_true=True, if_false=False):
  181. """Simulate JS's ternary operator (cndn?if_true:if_false)"""
  182. if cndn in (False, None, 0, '', JS_Undefined, _NaN):
  183. return if_false
  184. return if_true
  185. def _js_unary_op(op):
  186. @wraps_op(op)
  187. def wrapped(a, _):
  188. return op(a)
  189. return wrapped
  190. # https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof
  191. def _js_typeof(expr):
  192. with compat_contextlib_suppress(TypeError, KeyError):
  193. return {
  194. JS_Undefined: 'undefined',
  195. _NaN: 'number',
  196. _Infinity: 'number',
  197. True: 'boolean',
  198. False: 'boolean',
  199. None: 'object',
  200. }[expr]
  201. for t, n in (
  202. (compat_basestring, 'string'),
  203. (compat_numeric_types, 'number'),
  204. ):
  205. if isinstance(expr, t):
  206. return n
  207. if callable(expr):
  208. return 'function'
  209. # TODO: Symbol, BigInt
  210. return 'object'
  211. # (op, definition) in order of binding priority, tightest first
  212. # avoid dict to maintain order
  213. # definition None => Defined in JSInterpreter._operator
  214. _OPERATORS = (
  215. ('>>', _js_bit_op(operator.rshift, True)),
  216. ('<<', _js_bit_op(operator.lshift, True)),
  217. ('+', _js_add),
  218. ('-', _js_arith_op(operator.sub)),
  219. ('*', _js_arith_op(operator.mul)),
  220. ('%', _js_mod),
  221. ('/', _js_arith_op(operator.truediv, div=True)),
  222. ('**', _js_exp),
  223. )
  224. _LOG_OPERATORS = (
  225. ('|', _js_bit_op(operator.or_)),
  226. ('^', _js_bit_op(operator.xor)),
  227. ('&', _js_bit_op(operator.and_)),
  228. )
  229. _SC_OPERATORS = (
  230. ('?', None),
  231. ('??', None),
  232. ('||', None),
  233. ('&&', None),
  234. )
  235. _UNARY_OPERATORS_X = (
  236. ('void', _js_unary_op(lambda _: JS_Undefined)),
  237. ('typeof', _js_unary_op(_js_typeof)),
  238. # avoid functools.partial here since Py2 update_wrapper(partial) -> no __module__
  239. ('!', _js_unary_op(lambda x: _js_ternary(x, if_true=False, if_false=True))),
  240. )
  241. _COMP_OPERATORS = (
  242. ('===', _js_id_op(operator.is_)),
  243. ('!==', _js_id_op(operator.is_not)),
  244. ('==', _js_eq),
  245. ('!=', _js_neq),
  246. ('<=', _js_comp_op(operator.le)),
  247. ('>=', _js_comp_op(operator.ge)),
  248. ('<', _js_comp_op(operator.lt)),
  249. ('>', _js_comp_op(operator.gt)),
  250. )
  251. _OPERATOR_RE = '|'.join(map(lambda x: re.escape(x[0]), _OPERATORS + _LOG_OPERATORS + _SC_OPERATORS))
  252. _NAME_RE = r'[a-zA-Z_$][\w$]*'
  253. _MATCHING_PARENS = dict(zip(*zip('()', '{}', '[]')))
  254. _QUOTES = '\'"/'
  255. _NESTED_BRACKETS = r'[^[\]]+(?:\[[^[\]]+(?:\[[^\]]+\])?\])?'
  256. class JS_Break(ExtractorError):
  257. def __init__(self):
  258. ExtractorError.__init__(self, 'Invalid break')
  259. class JS_Continue(ExtractorError):
  260. def __init__(self):
  261. ExtractorError.__init__(self, 'Invalid continue')
  262. class JS_Throw(ExtractorError):
  263. def __init__(self, e):
  264. self.error = e
  265. ExtractorError.__init__(self, 'Uncaught exception ' + error_to_compat_str(e))
  266. class LocalNameSpace(ChainMap):
  267. def __getitem__(self, key):
  268. try:
  269. return super(LocalNameSpace, self).__getitem__(key)
  270. except KeyError:
  271. return JS_Undefined
  272. def __setitem__(self, key, value):
  273. for scope in self.maps:
  274. if key in scope:
  275. scope[key] = value
  276. return
  277. self.maps[0][key] = value
  278. def __delitem__(self, key):
  279. raise NotImplementedError('Deleting is not supported')
  280. def __repr__(self):
  281. return 'LocalNameSpace({0!r})'.format(self.maps)
  282. class Debugger(object):
  283. ENABLED = False
  284. @staticmethod
  285. def write(*args, **kwargs):
  286. level = kwargs.get('level', 100)
  287. def truncate_string(s, left, right=0):
  288. if s is None or len(s) <= left + right:
  289. return s
  290. return '...'.join((s[:left - 3], s[-right:] if right else ''))
  291. write_string('[debug] JS: {0}{1}\n'.format(
  292. ' ' * (100 - level),
  293. ' '.join(truncate_string(compat_str(x), 50, 50) for x in args)))
  294. @classmethod
  295. def wrap_interpreter(cls, f):
  296. if not cls.ENABLED:
  297. return f
  298. @wraps(f)
  299. def interpret_statement(self, stmt, local_vars, allow_recursion, *args, **kwargs):
  300. if cls.ENABLED and stmt.strip():
  301. cls.write(stmt, level=allow_recursion)
  302. try:
  303. ret, should_ret = f(self, stmt, local_vars, allow_recursion, *args, **kwargs)
  304. except Exception as e:
  305. if cls.ENABLED:
  306. if isinstance(e, ExtractorError):
  307. e = e.orig_msg
  308. cls.write('=> Raises:', e, '<-|', stmt, level=allow_recursion)
  309. raise
  310. if cls.ENABLED and stmt.strip():
  311. if should_ret or repr(ret) != stmt:
  312. cls.write(['->', '=>'][bool(should_ret)], repr(ret), '<-|', stmt, level=allow_recursion)
  313. return ret, should_ret
  314. return interpret_statement
  315. class JSInterpreter(object):
  316. __named_object_counter = 0
  317. _OBJ_NAME = '__youtube_dl_jsinterp_obj'
  318. OP_CHARS = None
  319. def __init__(self, code, objects=None):
  320. self.code, self._functions = code, {}
  321. self._objects = {} if objects is None else objects
  322. if type(self).OP_CHARS is None:
  323. type(self).OP_CHARS = self.OP_CHARS = self.__op_chars()
  324. class Exception(ExtractorError):
  325. def __init__(self, msg, *args, **kwargs):
  326. expr = kwargs.pop('expr', None)
  327. msg = str_or_none(msg, default='"None"')
  328. if expr is not None:
  329. msg = '{0} in: {1!r:.100}'.format(msg.rstrip(), expr)
  330. super(JSInterpreter.Exception, self).__init__(msg, *args, **kwargs)
  331. class JS_Object(object):
  332. def __getitem__(self, key):
  333. if hasattr(self, key):
  334. return getattr(self, key)
  335. raise KeyError(key)
  336. def dump(self):
  337. """Serialise the instance"""
  338. raise NotImplementedError
  339. class JS_RegExp(JS_Object):
  340. RE_FLAGS = {
  341. # special knowledge: Python's re flags are bitmask values, current max 128
  342. # invent new bitmask values well above that for literal parsing
  343. # JS 'u' flag is effectively always set (surrogate pairs aren't seen),
  344. # but \u{...} and \p{...} escapes aren't handled); no additional JS 'v'
  345. # features are supported
  346. # TODO: execute matches with these flags (remaining: d, y)
  347. 'd': 1024, # Generate indices for substring matches
  348. 'g': 2048, # Global search
  349. 'i': re.I, # Case-insensitive search
  350. 'm': re.M, # Multi-line search
  351. 's': re.S, # Allows . to match newline characters
  352. 'u': re.U, # Treat a pattern as a sequence of unicode code points
  353. 'v': re.U, # Like 'u' with extended character class and \p{} syntax
  354. 'y': 4096, # Perform a "sticky" search that matches starting at the current position in the target string
  355. }
  356. def __init__(self, pattern_txt, flags=0):
  357. if isinstance(flags, compat_str):
  358. flags, _ = self.regex_flags(flags)
  359. self.__self = None
  360. pattern_txt = str_or_none(pattern_txt) or '(?:)'
  361. # escape unintended embedded flags
  362. pattern_txt = re.sub(
  363. r'(\(\?)([aiLmsux]*)(-[imsx]+:|(?<!\?)\))',
  364. lambda m: ''.join(
  365. (re.escape(m.group(1)), m.group(2), re.escape(m.group(3)))
  366. if m.group(3) == ')'
  367. else ('(?:', m.group(2), m.group(3))),
  368. pattern_txt)
  369. # Avoid https://github.com/python/cpython/issues/74534
  370. self.source = pattern_txt.replace('[[', r'[\[')
  371. self.__flags = flags
  372. def __instantiate(self):
  373. if self.__self:
  374. return
  375. self.__self = re.compile(self.source, self.__flags)
  376. # Thx: https://stackoverflow.com/questions/44773522/setattr-on-python2-sre-sre-pattern
  377. for name in dir(self.__self):
  378. # Only these? Obviously __class__, __init__.
  379. # PyPy creates a __weakref__ attribute with value None
  380. # that can't be setattr'd but also can't need to be copied.
  381. if name in ('__class__', '__init__', '__weakref__'):
  382. continue
  383. if name == 'flags':
  384. setattr(self, name, getattr(self.__self, name, self.__flags))
  385. else:
  386. setattr(self, name, getattr(self.__self, name))
  387. def __getattr__(self, name):
  388. self.__instantiate()
  389. if name == 'pattern':
  390. self.pattern = self.source
  391. return self.pattern
  392. elif hasattr(self.__self, name):
  393. v = getattr(self.__self, name)
  394. setattr(self, name, v)
  395. return v
  396. elif name in ('groupindex', 'groups'):
  397. return 0 if name == 'groupindex' else {}
  398. else:
  399. flag_attrs = ( # order by 2nd elt
  400. ('hasIndices', 'd'),
  401. ('global', 'g'),
  402. ('ignoreCase', 'i'),
  403. ('multiline', 'm'),
  404. ('dotAll', 's'),
  405. ('unicode', 'u'),
  406. ('unicodeSets', 'v'),
  407. ('sticky', 'y'),
  408. )
  409. for k, c in flag_attrs:
  410. if name == k:
  411. return bool(self.RE_FLAGS[c] & self.__flags)
  412. else:
  413. if name == 'flags':
  414. return ''.join(
  415. (c if self.RE_FLAGS[c] & self.__flags else '')
  416. for _, c in flag_attrs)
  417. raise AttributeError('{0} has no attribute named {1}'.format(self, name))
  418. @classmethod
  419. def regex_flags(cls, expr):
  420. flags = 0
  421. if not expr:
  422. return flags, expr
  423. for idx, ch in enumerate(expr):
  424. if ch not in cls.RE_FLAGS:
  425. break
  426. flags |= cls.RE_FLAGS[ch]
  427. return flags, expr[idx + 1:]
  428. def dump(self):
  429. return '(/{0}/{1})'.format(
  430. re.sub(r'(?<!\\)/', r'\/', self.source),
  431. self.flags)
  432. @staticmethod
  433. def escape(string_):
  434. return re.escape(string_)
  435. class JS_Date(JS_Object):
  436. _t = None
  437. @staticmethod
  438. def __ymd_etc(*args, **kw_is_utc):
  439. # args: year, monthIndex, day, hours, minutes, seconds, milliseconds
  440. is_utc = kw_is_utc.get('is_utc', False)
  441. args = list(args[:7])
  442. args += [0] * (9 - len(args))
  443. args[1] += 1 # month 0..11 -> 1..12
  444. ms = args[6]
  445. for i in range(6, 9):
  446. args[i] = -1 # don't know
  447. if is_utc:
  448. args[-1] = 1
  449. # TODO: [MDN] When a segment overflows or underflows its expected
  450. # range, it usually "carries over to" or "borrows from" the higher segment.
  451. try:
  452. mktime = calendar.timegm if is_utc else time.mktime
  453. return mktime(time.struct_time(args)) * 1000 + ms
  454. except (OverflowError, ValueError):
  455. return None
  456. @classmethod
  457. def UTC(cls, *args):
  458. t = cls.__ymd_etc(*args, is_utc=True)
  459. return _NaN if t is None else t
  460. @staticmethod
  461. def parse(date_str, **kw_is_raw):
  462. is_raw = kw_is_raw.get('is_raw', False)
  463. t = unified_timestamp(str_or_none(date_str), False)
  464. return int(t * 1000) if t is not None else t if is_raw else _NaN
  465. @staticmethod
  466. def now(**kw_is_raw):
  467. is_raw = kw_is_raw.get('is_raw', False)
  468. t = time.time()
  469. return int(t * 1000) if t is not None else t if is_raw else _NaN
  470. def __init__(self, *args):
  471. if not args:
  472. args = [self.now(is_raw=True)]
  473. if len(args) == 1:
  474. if isinstance(args[0], JSInterpreter.JS_Date):
  475. self._t = int_or_none(args[0].valueOf(), default=None)
  476. else:
  477. arg_type = _js_typeof(args[0])
  478. if arg_type == 'string':
  479. self._t = self.parse(args[0], is_raw=True)
  480. elif arg_type == 'number':
  481. self._t = int(args[0])
  482. else:
  483. self._t = self.__ymd_etc(*args)
  484. def toString(self):
  485. try:
  486. return time.strftime('%a %b %0d %Y %H:%M:%S %Z%z', self._t).rstrip()
  487. except TypeError:
  488. return "Invalid Date"
  489. def valueOf(self):
  490. return _NaN if self._t is None else self._t
  491. def dump(self):
  492. return '(new Date({0}))'.format(self.toString())
  493. @classmethod
  494. def __op_chars(cls):
  495. op_chars = set(';,[')
  496. for op in cls._all_operators():
  497. if op[0].isalpha():
  498. continue
  499. op_chars.update(op[0])
  500. return op_chars
  501. def _named_object(self, namespace, obj):
  502. self.__named_object_counter += 1
  503. name = '%s%d' % (self._OBJ_NAME, self.__named_object_counter)
  504. if callable(obj) and not isinstance(obj, function_with_repr):
  505. obj = function_with_repr(obj, 'F<%s>' % (self.__named_object_counter, ))
  506. namespace[name] = obj
  507. return name
  508. @classmethod
  509. def _separate(cls, expr, delim=',', max_split=None, skip_delims=None):
  510. if not expr:
  511. return
  512. # collections.Counter() is ~10% slower in both 2.7 and 3.9
  513. counters = dict((k, 0) for k in _MATCHING_PARENS.values())
  514. start, splits, pos, delim_len = 0, 0, 0, len(delim) - 1
  515. in_quote, escaping, after_op, in_regex_char_group = None, False, True, False
  516. skipping = 0
  517. if skip_delims:
  518. skip_delims = variadic(skip_delims)
  519. skip_txt = None
  520. for idx, char in enumerate(expr):
  521. if skip_txt and idx <= skip_txt[1]:
  522. continue
  523. paren_delta = 0
  524. if not in_quote:
  525. if char == '/' and expr[idx:idx + 2] == '/*':
  526. # skip a comment
  527. skip_txt = expr[idx:].find('*/', 2)
  528. skip_txt = [idx, idx + skip_txt + 1] if skip_txt >= 2 else None
  529. if skip_txt:
  530. continue
  531. if char in _MATCHING_PARENS:
  532. counters[_MATCHING_PARENS[char]] += 1
  533. paren_delta = 1
  534. elif char in counters:
  535. counters[char] -= 1
  536. paren_delta = -1
  537. if not escaping:
  538. if char in _QUOTES and in_quote in (char, None):
  539. if in_quote or after_op or char != '/':
  540. in_quote = None if in_quote and not in_regex_char_group else char
  541. elif in_quote == '/' and char in '[]':
  542. in_regex_char_group = char == '['
  543. escaping = not escaping and in_quote and char == '\\'
  544. after_op = not in_quote and (char in cls.OP_CHARS or paren_delta > 0 or (after_op and char.isspace()))
  545. if char != delim[pos] or any(counters.values()) or in_quote:
  546. pos = skipping = 0
  547. continue
  548. elif skipping > 0:
  549. skipping -= 1
  550. continue
  551. elif pos == 0 and skip_delims:
  552. here = expr[idx:]
  553. for s in skip_delims:
  554. if here.startswith(s) and s:
  555. skipping = len(s) - 1
  556. break
  557. if skipping > 0:
  558. continue
  559. if pos < delim_len:
  560. pos += 1
  561. continue
  562. if skip_txt and skip_txt[0] >= start and skip_txt[1] <= idx - delim_len:
  563. yield expr[start:skip_txt[0]] + expr[skip_txt[1] + 1: idx - delim_len]
  564. else:
  565. yield expr[start: idx - delim_len]
  566. skip_txt = None
  567. start, pos = idx + 1, 0
  568. splits += 1
  569. if max_split and splits >= max_split:
  570. break
  571. if skip_txt and skip_txt[0] >= start:
  572. yield expr[start:skip_txt[0]] + expr[skip_txt[1] + 1:]
  573. else:
  574. yield expr[start:]
  575. @classmethod
  576. def _separate_at_paren(cls, expr, delim=None):
  577. if delim is None:
  578. delim = expr and _MATCHING_PARENS[expr[0]]
  579. separated = list(cls._separate(expr, delim, 1))
  580. if len(separated) < 2:
  581. raise cls.Exception('No terminating paren {delim} in {expr!r:.5500}'.format(**locals()))
  582. return separated[0][1:].strip(), separated[1].strip()
  583. @staticmethod
  584. def _all_operators(_cached=[]):
  585. if not _cached:
  586. _cached.extend(itertools.chain(
  587. # Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
  588. _SC_OPERATORS, _LOG_OPERATORS, _COMP_OPERATORS, _OPERATORS, _UNARY_OPERATORS_X))
  589. return _cached
  590. def _separate_at_op(self, expr, max_split=None):
  591. for op, _ in self._all_operators():
  592. # hackety: </> have higher priority than <</>>, but don't confuse them
  593. skip_delim = (op + op) if op in '<>*?' else None
  594. if op == '?':
  595. skip_delim = (skip_delim, '?.')
  596. separated = list(self._separate(expr, op, skip_delims=skip_delim))
  597. if len(separated) < 2:
  598. continue
  599. right_expr = separated.pop()
  600. # handle operators that are both unary and binary, minimal BODMAS
  601. if op in ('+', '-'):
  602. # simplify/adjust consecutive instances of these operators
  603. undone = 0
  604. separated = [s.strip() for s in separated]
  605. while len(separated) > 1 and not separated[-1]:
  606. undone += 1
  607. separated.pop()
  608. if op == '-' and undone % 2 != 0:
  609. right_expr = op + right_expr
  610. elif op == '+':
  611. while len(separated) > 1 and set(separated[-1]) <= self.OP_CHARS:
  612. right_expr = separated.pop() + right_expr
  613. if separated[-1][-1:] in self.OP_CHARS:
  614. right_expr = separated.pop() + right_expr
  615. # hanging op at end of left => unary + (strip) or - (push right)
  616. separated.append(right_expr)
  617. dm_ops = ('*', '%', '/', '**')
  618. dm_chars = set(''.join(dm_ops))
  619. def yield_terms(s):
  620. skip = False
  621. for i, term in enumerate(s[:-1]):
  622. if skip:
  623. skip = False
  624. continue
  625. if not (dm_chars & set(term)):
  626. yield term
  627. continue
  628. for dm_op in dm_ops:
  629. bodmas = list(self._separate(term, dm_op, skip_delims=skip_delim))
  630. if len(bodmas) > 1 and not bodmas[-1].strip():
  631. bodmas[-1] = (op if op == '-' else '') + s[i + 1]
  632. yield dm_op.join(bodmas)
  633. skip = True
  634. break
  635. else:
  636. if term:
  637. yield term
  638. if not skip and s[-1]:
  639. yield s[-1]
  640. separated = list(yield_terms(separated))
  641. right_expr = separated.pop() if len(separated) > 1 else None
  642. expr = op.join(separated)
  643. if right_expr is None:
  644. continue
  645. return op, separated, right_expr
  646. def _operator(self, op, left_val, right_expr, expr, local_vars, allow_recursion):
  647. if op in ('||', '&&'):
  648. if (op == '&&') ^ _js_ternary(left_val):
  649. return left_val # short circuiting
  650. elif op == '??':
  651. if left_val not in (None, JS_Undefined):
  652. return left_val
  653. elif op == '?':
  654. right_expr = _js_ternary(left_val, *self._separate(right_expr, ':', 1))
  655. right_val = self.interpret_expression(right_expr, local_vars, allow_recursion) if right_expr else left_val
  656. opfunc = op and next((v for k, v in self._all_operators() if k == op), None)
  657. if not opfunc:
  658. return right_val
  659. try:
  660. # print('Eval:', opfunc.__name__, left_val, right_val)
  661. return opfunc(left_val, right_val)
  662. except Exception as e:
  663. raise self.Exception('Failed to evaluate {left_val!r:.50} {op} {right_val!r:.50}'.format(**locals()), expr, cause=e)
  664. def _index(self, obj, idx, allow_undefined=None):
  665. if idx == 'length' and isinstance(obj, list):
  666. return len(obj)
  667. try:
  668. return obj[int(idx)] if isinstance(obj, list) else obj[compat_str(idx)]
  669. except (TypeError, KeyError, IndexError, ValueError) as e:
  670. # allow_undefined is None gives correct behaviour
  671. if allow_undefined or (
  672. allow_undefined is None and not isinstance(e, TypeError)):
  673. return JS_Undefined
  674. raise self.Exception('Cannot get index {idx!r:.100}'.format(**locals()), expr=repr(obj), cause=e)
  675. def _dump(self, obj, namespace):
  676. if obj is JS_Undefined:
  677. return 'undefined'
  678. try:
  679. return json.dumps(obj)
  680. except TypeError:
  681. return self._named_object(namespace, obj)
  682. # used below
  683. _VAR_RET_THROW_RE = re.compile(r'''(?x)
  684. (?:(?P<var>var|const|let)\s+|(?P<ret>return)(?:\s+|(?=["'])|$)|(?P<throw>throw)\s+)
  685. ''')
  686. _COMPOUND_RE = re.compile(r'''(?x)
  687. (?P<try>try)\s*\{|
  688. (?P<if>if)\s*\(|
  689. (?P<switch>switch)\s*\(|
  690. (?P<for>for)\s*\(|
  691. (?P<while>while)\s*\(
  692. ''')
  693. _FINALLY_RE = re.compile(r'finally\s*\{')
  694. _SWITCH_RE = re.compile(r'switch\s*\(')
  695. def _eval_operator(self, op, left_expr, right_expr, expr, local_vars, allow_recursion):
  696. left_val = self.interpret_expression(left_expr, local_vars, allow_recursion)
  697. return self._operator(op, left_val, right_expr, expr, local_vars, allow_recursion)
  698. @Debugger.wrap_interpreter
  699. def interpret_statement(self, stmt, local_vars, allow_recursion=100):
  700. if allow_recursion < 0:
  701. raise self.Exception('Recursion limit reached')
  702. allow_recursion -= 1
  703. # print('At: ' + stmt[:60])
  704. should_return = False
  705. # fails on (eg) if (...) stmt1; else stmt2;
  706. sub_statements = list(self._separate(stmt, ';')) or ['']
  707. expr = stmt = sub_statements.pop().strip()
  708. for sub_stmt in sub_statements:
  709. ret, should_return = self.interpret_statement(sub_stmt, local_vars, allow_recursion)
  710. if should_return:
  711. return ret, should_return
  712. m = self._VAR_RET_THROW_RE.match(stmt)
  713. if m:
  714. expr = stmt[len(m.group(0)):].strip()
  715. if m.group('throw'):
  716. raise JS_Throw(self.interpret_expression(expr, local_vars, allow_recursion))
  717. should_return = 'return' if m.group('ret') else False
  718. if not expr:
  719. return None, should_return
  720. if expr[0] in _QUOTES:
  721. inner, outer = self._separate(expr, expr[0], 1)
  722. if expr[0] == '/':
  723. flags, outer = self.JS_RegExp.regex_flags(outer)
  724. inner = self.JS_RegExp(inner[1:], flags=flags)
  725. else:
  726. inner = json.loads(js_to_json(inner + expr[0])) # , strict=True))
  727. if not outer:
  728. return inner, should_return
  729. expr = self._named_object(local_vars, inner) + outer
  730. new_kw, _, obj = expr.partition('new ')
  731. if not new_kw:
  732. for klass, konstr in (('Date', lambda *x: self.JS_Date(*x).valueOf()),
  733. ('RegExp', self.JS_RegExp),
  734. ('Error', self.Exception)):
  735. if not obj.startswith(klass + '('):
  736. continue
  737. left, right = self._separate_at_paren(obj[len(klass):])
  738. argvals = self.interpret_iter(left, local_vars, allow_recursion)
  739. expr = konstr(*argvals)
  740. if expr is None:
  741. raise self.Exception('Failed to parse {klass} {left!r:.100}'.format(**locals()), expr=expr)
  742. expr = self._dump(expr, local_vars) + right
  743. break
  744. else:
  745. raise self.Exception('Unsupported object {obj:.100}'.format(**locals()), expr=expr)
  746. # apply unary operators (see new above)
  747. for op, _ in _UNARY_OPERATORS_X:
  748. if not expr.startswith(op):
  749. continue
  750. operand = expr[len(op):]
  751. if not operand or (op.isalpha() and operand[0] != ' '):
  752. continue
  753. separated = self._separate_at_op(operand, max_split=1)
  754. if separated:
  755. next_op, separated, right_expr = separated
  756. separated.append(right_expr)
  757. operand = next_op.join(separated)
  758. return self._eval_operator(op, operand, '', expr, local_vars, allow_recursion), should_return
  759. if expr.startswith('{'):
  760. inner, outer = self._separate_at_paren(expr)
  761. # try for object expression (Map)
  762. sub_expressions = [list(self._separate(sub_expr.strip(), ':', 1)) for sub_expr in self._separate(inner)]
  763. if all(len(sub_expr) == 2 for sub_expr in sub_expressions):
  764. return dict(
  765. (key_expr if re.match(_NAME_RE, key_expr) else key_expr,
  766. self.interpret_expression(val_expr, local_vars, allow_recursion))
  767. for key_expr, val_expr in sub_expressions), should_return
  768. # or statement list
  769. inner, should_abort = self.interpret_statement(inner, local_vars, allow_recursion)
  770. if not outer or should_abort:
  771. return inner, should_abort or should_return
  772. else:
  773. expr = self._dump(inner, local_vars) + outer
  774. if expr.startswith('('):
  775. m = re.match(r'\((?P<d>[a-z])%(?P<e>[a-z])\.length\+(?P=e)\.length\)%(?P=e)\.length', expr)
  776. if m:
  777. # short-cut eval of frequently used `(d%e.length+e.length)%e.length`, worth ~6% on `pytest -k test_nsig`
  778. outer = None
  779. inner, should_abort = self._offset_e_by_d(m.group('d'), m.group('e'), local_vars)
  780. else:
  781. inner, outer = self._separate_at_paren(expr)
  782. inner, should_abort = self.interpret_statement(inner, local_vars, allow_recursion)
  783. if not outer or should_abort:
  784. return inner, should_abort or should_return
  785. else:
  786. expr = self._dump(inner, local_vars) + outer
  787. if expr.startswith('['):
  788. inner, outer = self._separate_at_paren(expr)
  789. name = self._named_object(local_vars, [
  790. self.interpret_expression(item, local_vars, allow_recursion)
  791. for item in self._separate(inner)])
  792. expr = name + outer
  793. m = self._COMPOUND_RE.match(expr)
  794. md = m.groupdict() if m else {}
  795. if md.get('if'):
  796. cndn, expr = self._separate_at_paren(expr[m.end() - 1:])
  797. if expr.startswith('{'):
  798. if_expr, expr = self._separate_at_paren(expr)
  799. else:
  800. # may lose ... else ... because of ll.368-374
  801. if_expr, expr = self._separate_at_paren(' %s;' % (expr,), delim=';')
  802. else_expr = None
  803. m = re.match(r'else\s*(?P<block>\{)?', expr)
  804. if m:
  805. if m.group('block'):
  806. else_expr, expr = self._separate_at_paren(expr[m.end() - 1:])
  807. else:
  808. # handle subset ... else if (...) {...} else ...
  809. # TODO: make interpret_statement do this properly, if possible
  810. exprs = list(self._separate(expr[m.end():], delim='}', max_split=2))
  811. if len(exprs) > 1:
  812. if re.match(r'\s*if\s*\(', exprs[0]) and re.match(r'\s*else\b', exprs[1]):
  813. else_expr = exprs[0] + '}' + exprs[1]
  814. expr = (exprs[2] + '}') if len(exprs) == 3 else None
  815. else:
  816. else_expr = exprs[0]
  817. exprs.append('')
  818. expr = '}'.join(exprs[1:])
  819. else:
  820. else_expr = exprs[0]
  821. expr = None
  822. else_expr = else_expr.lstrip() + '}'
  823. cndn = _js_ternary(self.interpret_expression(cndn, local_vars, allow_recursion))
  824. ret, should_abort = self.interpret_statement(
  825. if_expr if cndn else else_expr, local_vars, allow_recursion)
  826. if should_abort:
  827. return ret, True
  828. elif md.get('try'):
  829. try_expr, expr = self._separate_at_paren(expr[m.end() - 1:])
  830. err = None
  831. try:
  832. ret, should_abort = self.interpret_statement(try_expr, local_vars, allow_recursion)
  833. if should_abort:
  834. return ret, True
  835. except Exception as e:
  836. # XXX: This works for now, but makes debugging future issues very hard
  837. err = e
  838. pending = (None, False)
  839. m = re.match(r'catch\s*(?P<err>\(\s*{_NAME_RE}\s*\))?\{{'.format(**globals()), expr)
  840. if m:
  841. sub_expr, expr = self._separate_at_paren(expr[m.end() - 1:])
  842. if err:
  843. catch_vars = {}
  844. if m.group('err'):
  845. catch_vars[m.group('err')] = err.error if isinstance(err, JS_Throw) else err
  846. catch_vars = local_vars.new_child(m=catch_vars)
  847. err, pending = None, self.interpret_statement(sub_expr, catch_vars, allow_recursion)
  848. m = self._FINALLY_RE.match(expr)
  849. if m:
  850. sub_expr, expr = self._separate_at_paren(expr[m.end() - 1:])
  851. ret, should_abort = self.interpret_statement(sub_expr, local_vars, allow_recursion)
  852. if should_abort:
  853. return ret, True
  854. ret, should_abort = pending
  855. if should_abort:
  856. return ret, True
  857. if err:
  858. raise err
  859. elif md.get('for') or md.get('while'):
  860. init_or_cond, remaining = self._separate_at_paren(expr[m.end() - 1:])
  861. if remaining.startswith('{'):
  862. body, expr = self._separate_at_paren(remaining)
  863. else:
  864. switch_m = self._SWITCH_RE.match(remaining) # FIXME
  865. if switch_m:
  866. switch_val, remaining = self._separate_at_paren(remaining[switch_m.end() - 1:])
  867. body, expr = self._separate_at_paren(remaining, '}')
  868. body = 'switch(%s){%s}' % (switch_val, body)
  869. else:
  870. body, expr = remaining, ''
  871. if md.get('for'):
  872. start, cndn, increment = self._separate(init_or_cond, ';')
  873. self.interpret_expression(start, local_vars, allow_recursion)
  874. else:
  875. cndn, increment = init_or_cond, None
  876. while _js_ternary(self.interpret_expression(cndn, local_vars, allow_recursion)):
  877. try:
  878. ret, should_abort = self.interpret_statement(body, local_vars, allow_recursion)
  879. if should_abort:
  880. return ret, True
  881. except JS_Break:
  882. break
  883. except JS_Continue:
  884. pass
  885. if increment:
  886. self.interpret_expression(increment, local_vars, allow_recursion)
  887. elif md.get('switch'):
  888. switch_val, remaining = self._separate_at_paren(expr[m.end() - 1:])
  889. switch_val = self.interpret_expression(switch_val, local_vars, allow_recursion)
  890. body, expr = self._separate_at_paren(remaining, '}')
  891. items = body.replace('default:', 'case default:').split('case ')[1:]
  892. for default in (False, True):
  893. matched = False
  894. for item in items:
  895. case, stmt = (i.strip() for i in self._separate(item, ':', 1))
  896. if default:
  897. matched = matched or case == 'default'
  898. elif not matched:
  899. matched = (case != 'default'
  900. and switch_val == self.interpret_expression(case, local_vars, allow_recursion))
  901. if not matched:
  902. continue
  903. try:
  904. ret, should_abort = self.interpret_statement(stmt, local_vars, allow_recursion)
  905. if should_abort:
  906. return ret
  907. except JS_Break:
  908. break
  909. if matched:
  910. break
  911. if md:
  912. ret, should_abort = self.interpret_statement(expr, local_vars, allow_recursion)
  913. return ret, should_abort or should_return
  914. # Comma separated statements
  915. sub_expressions = list(self._separate(expr))
  916. if len(sub_expressions) > 1:
  917. for sub_expr in sub_expressions:
  918. ret, should_abort = self.interpret_statement(sub_expr, local_vars, allow_recursion)
  919. if should_abort:
  920. return ret, True
  921. return ret, False
  922. for m in re.finditer(r'''(?x)
  923. (?P<pre_sign>\+\+|--)(?P<var1>{_NAME_RE})|
  924. (?P<var2>{_NAME_RE})(?P<post_sign>\+\+|--)'''.format(**globals()), expr):
  925. var = m.group('var1') or m.group('var2')
  926. start, end = m.span()
  927. sign = m.group('pre_sign') or m.group('post_sign')
  928. ret = local_vars[var]
  929. local_vars[var] = _js_add(ret, 1 if sign[0] == '+' else -1)
  930. if m.group('pre_sign'):
  931. ret = local_vars[var]
  932. expr = expr[:start] + self._dump(ret, local_vars) + expr[end:]
  933. if not expr:
  934. return None, should_return
  935. m = re.match(r'''(?x)
  936. (?P<assign>
  937. (?P<out>{_NAME_RE})(?P<out_idx>(?:\[{_NESTED_BRACKETS}\])+)?\s*
  938. (?P<op>{_OPERATOR_RE})?
  939. =(?!=)(?P<expr>.*)$
  940. )|(?P<return>
  941. (?!if|return|true|false|null|undefined|NaN|Infinity)(?P<name>{_NAME_RE})$
  942. )|(?P<attribute>
  943. (?P<var>{_NAME_RE})(?:
  944. (?P<nullish>\?)?\.(?P<member>[^(]+)|
  945. \[(?P<member2>{_NESTED_BRACKETS})\]
  946. )\s*
  947. )|(?P<indexing>
  948. (?P<in>{_NAME_RE})(?P<in_idx>\[.+\])$
  949. )|(?P<function>
  950. (?P<fname>{_NAME_RE})\((?P<args>.*)\)$
  951. )'''.format(**globals()), expr)
  952. md = m.groupdict() if m else {}
  953. if md.get('assign'):
  954. left_val = local_vars.get(m.group('out'))
  955. if not m.group('out_idx'):
  956. local_vars[m.group('out')] = self._operator(
  957. m.group('op'), left_val, m.group('expr'), expr, local_vars, allow_recursion)
  958. return local_vars[m.group('out')], should_return
  959. elif left_val in (None, JS_Undefined):
  960. raise self.Exception('Cannot index undefined variable ' + m.group('out'), expr=expr)
  961. indexes = md['out_idx']
  962. while indexes:
  963. idx, indexes = self._separate_at_paren(indexes)
  964. idx = self.interpret_expression(idx, local_vars, allow_recursion)
  965. if indexes:
  966. left_val = self._index(left_val, idx)
  967. if isinstance(idx, float):
  968. idx = int(idx)
  969. if isinstance(left_val, list) and len(left_val) <= int_or_none(idx, default=-1):
  970. # JS Array is a sparsely assignable list
  971. # TODO: handle extreme sparsity without memory bloat, eg using auxiliary dict
  972. left_val.extend((idx - len(left_val) + 1) * [JS_Undefined])
  973. left_val[idx] = self._operator(
  974. m.group('op'), self._index(left_val, idx) if m.group('op') else None,
  975. m.group('expr'), expr, local_vars, allow_recursion)
  976. return left_val[idx], should_return
  977. elif expr.isdigit():
  978. return int(expr), should_return
  979. elif expr == 'break':
  980. raise JS_Break()
  981. elif expr == 'continue':
  982. raise JS_Continue()
  983. elif expr == 'undefined':
  984. return JS_Undefined, should_return
  985. elif expr == 'NaN':
  986. return _NaN, should_return
  987. elif expr == 'Infinity':
  988. return _Infinity, should_return
  989. elif md.get('return'):
  990. ret = local_vars[m.group('name')]
  991. # challenge may try to force returning the original value
  992. # use an optional internal var to block this
  993. if should_return == 'return':
  994. if '_ytdl_do_not_return' not in local_vars:
  995. return ret, True
  996. return (ret, True) if ret != local_vars['_ytdl_do_not_return'] else (ret, False)
  997. else:
  998. return ret, should_return
  999. with compat_contextlib_suppress(ValueError):
  1000. ret = json.loads(js_to_json(expr)) # strict=True)
  1001. if not md.get('attribute'):
  1002. return ret, should_return
  1003. if md.get('indexing'):
  1004. val = local_vars[m.group('in')]
  1005. indexes = m.group('in_idx')
  1006. while indexes:
  1007. idx, indexes = self._separate_at_paren(indexes)
  1008. idx = self.interpret_expression(idx, local_vars, allow_recursion)
  1009. val = self._index(val, idx)
  1010. return val, should_return
  1011. separated = self._separate_at_op(expr)
  1012. if separated:
  1013. op, separated, right_expr = separated
  1014. return self._eval_operator(op, op.join(separated), right_expr, expr, local_vars, allow_recursion), should_return
  1015. if md.get('attribute'):
  1016. variable, member, nullish = m.group('var', 'member', 'nullish')
  1017. if not member:
  1018. member = self.interpret_expression(m.group('member2'), local_vars, allow_recursion)
  1019. arg_str = expr[m.end():]
  1020. if arg_str.startswith('('):
  1021. arg_str, remaining = self._separate_at_paren(arg_str)
  1022. else:
  1023. arg_str, remaining = None, arg_str
  1024. def assertion(cndn, msg):
  1025. """ assert, but without risk of getting optimized out """
  1026. if not cndn:
  1027. memb = member
  1028. raise self.Exception('{memb} {msg}'.format(**locals()), expr=expr)
  1029. def eval_method(variable, member):
  1030. if (variable, member) == ('console', 'debug'):
  1031. if Debugger.ENABLED:
  1032. Debugger.write(self.interpret_expression('[{0}]'.format(arg_str), local_vars, allow_recursion))
  1033. return
  1034. types = {
  1035. 'String': compat_str,
  1036. 'Math': float,
  1037. 'Array': list,
  1038. 'Date': self.JS_Date,
  1039. 'RegExp': self.JS_RegExp,
  1040. # 'Error': self.Exception, # has no std static methods
  1041. }
  1042. obj = local_vars.get(variable)
  1043. if obj in (JS_Undefined, None):
  1044. obj = types.get(variable, JS_Undefined)
  1045. if obj is JS_Undefined:
  1046. try:
  1047. if variable not in self._objects:
  1048. self._objects[variable] = self.extract_object(variable, local_vars)
  1049. obj = self._objects[variable]
  1050. except self.Exception:
  1051. if not nullish:
  1052. raise
  1053. if nullish and obj is JS_Undefined:
  1054. return JS_Undefined
  1055. # Member access
  1056. if arg_str is None:
  1057. return self._index(obj, member, nullish)
  1058. # Function call
  1059. argvals = [
  1060. self.interpret_expression(v, local_vars, allow_recursion)
  1061. for v in self._separate(arg_str)]
  1062. # Fixup prototype call
  1063. if isinstance(obj, type):
  1064. new_member, rest = member.partition('.')[0::2]
  1065. if new_member == 'prototype':
  1066. new_member, func_prototype = rest.partition('.')[0::2]
  1067. assertion(argvals, 'takes one or more arguments')
  1068. assertion(isinstance(argvals[0], obj), 'must bind to type {0}'.format(obj))
  1069. if func_prototype == 'call':
  1070. obj = argvals.pop(0)
  1071. elif func_prototype == 'apply':
  1072. assertion(len(argvals) == 2, 'takes two arguments')
  1073. obj, argvals = argvals
  1074. assertion(isinstance(argvals, list), 'second argument must be a list')
  1075. else:
  1076. raise self.Exception('Unsupported Function method ' + func_prototype, expr)
  1077. member = new_member
  1078. if obj is compat_str:
  1079. if member == 'fromCharCode':
  1080. assertion(argvals, 'takes one or more arguments')
  1081. return ''.join(compat_chr(int(n)) for n in argvals)
  1082. raise self.Exception('Unsupported string method ' + member, expr=expr)
  1083. elif obj is float:
  1084. if member == 'pow':
  1085. assertion(len(argvals) == 2, 'takes two arguments')
  1086. return argvals[0] ** argvals[1]
  1087. raise self.Exception('Unsupported Math method ' + member, expr=expr)
  1088. elif obj is self.JS_Date:
  1089. return getattr(obj, member)(*argvals)
  1090. if member == 'split':
  1091. assertion(len(argvals) <= 2, 'takes at most two arguments')
  1092. if len(argvals) > 1:
  1093. limit = argvals[1]
  1094. assertion(isinstance(limit, int) and limit >= 0, 'integer limit >= 0')
  1095. if limit == 0:
  1096. return []
  1097. else:
  1098. limit = 0
  1099. if len(argvals) == 0:
  1100. argvals = [JS_Undefined]
  1101. elif isinstance(argvals[0], self.JS_RegExp):
  1102. # avoid re.split(), similar but not enough
  1103. def where():
  1104. for m in argvals[0].finditer(obj):
  1105. yield m.span(0)
  1106. yield (None, None)
  1107. def splits(limit=limit):
  1108. i = 0
  1109. for j, jj in where():
  1110. if j == jj == 0:
  1111. continue
  1112. if j is None and i >= len(obj):
  1113. break
  1114. yield obj[i:j]
  1115. if jj is None or limit == 1:
  1116. break
  1117. limit -= 1
  1118. i = jj
  1119. return list(splits())
  1120. return (
  1121. obj.split(argvals[0], limit - 1) if argvals[0] and argvals[0] != JS_Undefined
  1122. else list(obj)[:limit or None])
  1123. elif member == 'join':
  1124. assertion(isinstance(obj, list), 'must be applied on a list')
  1125. assertion(len(argvals) <= 1, 'takes at most one argument')
  1126. return (',' if len(argvals) == 0 or argvals[0] in (None, JS_Undefined)
  1127. else argvals[0]).join(
  1128. ('' if x in (None, JS_Undefined) else _js_toString(x))
  1129. for x in obj)
  1130. elif member == 'reverse':
  1131. assertion(not argvals, 'does not take any arguments')
  1132. obj.reverse()
  1133. return obj
  1134. elif member == 'slice':
  1135. assertion(isinstance(obj, (list, compat_str)), 'must be applied on a list or string')
  1136. # From [1]:
  1137. # .slice() - like [:]
  1138. # .slice(n) - like [n:] (not [slice(n)]
  1139. # .slice(m, n) - like [m:n] or [slice(m, n)]
  1140. # [1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
  1141. assertion(len(argvals) <= 2, 'takes between 0 and 2 arguments')
  1142. if len(argvals) < 2:
  1143. argvals += (None,)
  1144. return obj[slice(*argvals)]
  1145. elif member == 'splice':
  1146. assertion(isinstance(obj, list), 'must be applied on a list')
  1147. assertion(argvals, 'takes one or more arguments')
  1148. index, how_many = map(int, (argvals + [len(obj)])[:2])
  1149. if index < 0:
  1150. index += len(obj)
  1151. res = [obj.pop(index)
  1152. for _ in range(index, min(index + how_many, len(obj)))]
  1153. obj[index:index] = argvals[2:]
  1154. return res
  1155. elif member in ('shift', 'pop'):
  1156. assertion(isinstance(obj, list), 'must be applied on a list')
  1157. assertion(not argvals, 'does not take any arguments')
  1158. return obj.pop(0 if member == 'shift' else -1) if len(obj) > 0 else JS_Undefined
  1159. elif member == 'unshift':
  1160. assertion(isinstance(obj, list), 'must be applied on a list')
  1161. # not enforced: assertion(argvals, 'takes one or more arguments')
  1162. obj[0:0] = argvals
  1163. return len(obj)
  1164. elif member == 'push':
  1165. # not enforced: assertion(argvals, 'takes one or more arguments')
  1166. obj.extend(argvals)
  1167. return len(obj)
  1168. elif member == 'forEach':
  1169. assertion(argvals, 'takes one or more arguments')
  1170. assertion(len(argvals) <= 2, 'takes at most 2 arguments')
  1171. f, this = (argvals + [''])[:2]
  1172. return [f((item, idx, obj), {'this': this}, allow_recursion) for idx, item in enumerate(obj)]
  1173. elif member == 'indexOf':
  1174. assertion(argvals, 'takes one or more arguments')
  1175. assertion(len(argvals) <= 2, 'takes at most 2 arguments')
  1176. idx, start = (argvals + [0])[:2]
  1177. try:
  1178. return obj.index(idx, start)
  1179. except ValueError:
  1180. return -1
  1181. elif member == 'charCodeAt':
  1182. assertion(isinstance(obj, compat_str), 'must be applied on a string')
  1183. # assertion(len(argvals) == 1, 'takes exactly one argument') # but not enforced
  1184. idx = argvals[0] if len(argvals) > 0 and isinstance(argvals[0], int) else 0
  1185. if idx >= len(obj):
  1186. return None
  1187. return ord(obj[idx])
  1188. elif member in ('replace', 'replaceAll'):
  1189. assertion(isinstance(obj, compat_str), 'must be applied on a string')
  1190. assertion(len(argvals) == 2, 'takes exactly two arguments')
  1191. # TODO: argvals[1] callable, other Py vs JS edge cases
  1192. if isinstance(argvals[0], self.JS_RegExp):
  1193. # access JS member with Py reserved name
  1194. count = 0 if self._index(argvals[0], 'global') else 1
  1195. assertion(member != 'replaceAll' or count == 0,
  1196. 'replaceAll must be called with a global RegExp')
  1197. return argvals[0].sub(argvals[1], obj, count=count)
  1198. count = ('replaceAll', 'replace').index(member)
  1199. return re.sub(re.escape(argvals[0]), argvals[1], obj, count=count)
  1200. idx = int(member) if isinstance(obj, list) else member
  1201. return obj[idx](argvals, allow_recursion=allow_recursion)
  1202. if remaining:
  1203. ret, should_abort = self.interpret_statement(
  1204. self._named_object(local_vars, eval_method(variable, member)) + remaining,
  1205. local_vars, allow_recursion)
  1206. return ret, should_return or should_abort
  1207. else:
  1208. return eval_method(variable, member), should_return
  1209. elif md.get('function'):
  1210. fname = m.group('fname')
  1211. argvals = [self.interpret_expression(v, local_vars, allow_recursion)
  1212. for v in self._separate(m.group('args'))]
  1213. if fname in local_vars:
  1214. return local_vars[fname](argvals, allow_recursion=allow_recursion), should_return
  1215. elif fname not in self._functions:
  1216. self._functions[fname] = self.extract_function(fname)
  1217. return self._functions[fname](argvals, allow_recursion=allow_recursion), should_return
  1218. raise self.Exception(
  1219. 'Unsupported JS expression ' + (expr[:40] if expr != stmt else ''), expr=stmt)
  1220. def interpret_expression(self, expr, local_vars, allow_recursion):
  1221. ret, should_return = self.interpret_statement(expr, local_vars, allow_recursion)
  1222. if should_return:
  1223. raise self.Exception('Cannot return from an expression', expr)
  1224. return ret
  1225. def interpret_iter(self, list_txt, local_vars, allow_recursion):
  1226. for v in self._separate(list_txt):
  1227. yield self.interpret_expression(v, local_vars, allow_recursion)
  1228. def extract_object(self, objname, *global_stack):
  1229. _FUNC_NAME_RE = r'''(?:{n}|"{n}"|'{n}')'''.format(n=_NAME_RE)
  1230. obj = {}
  1231. fields = next(filter(None, (
  1232. obj_m.group('fields') for obj_m in re.finditer(
  1233. r'''(?xs)
  1234. {0}\s*\.\s*{1}|{1}\s*=\s*\{{\s*
  1235. (?P<fields>({2}\s*:\s*function\s*\(.*?\)\s*\{{.*?}}(?:,\s*)?)*)
  1236. }}\s*;
  1237. '''.format(_NAME_RE, re.escape(objname), _FUNC_NAME_RE),
  1238. self.code))), None)
  1239. if not fields:
  1240. raise self.Exception('Could not find object ' + objname)
  1241. # Currently, it only supports function definitions
  1242. for f in re.finditer(
  1243. r'''(?x)
  1244. (?P<key>%s)\s*:\s*function\s*\((?P<args>(?:%s|,)*)\){(?P<code>[^}]+)}
  1245. ''' % (_FUNC_NAME_RE, _NAME_RE),
  1246. fields):
  1247. argnames = self.build_arglist(f.group('args'))
  1248. name = remove_quotes(f.group('key'))
  1249. obj[name] = function_with_repr(
  1250. self.build_function(argnames, f.group('code'), *global_stack), 'F<{0}>'.format(name))
  1251. return obj
  1252. @staticmethod
  1253. def _offset_e_by_d(d, e, local_vars):
  1254. """ Short-cut eval: (d%e.length+e.length)%e.length """
  1255. try:
  1256. d = local_vars[d]
  1257. e = local_vars[e]
  1258. e = len(e)
  1259. return _js_mod(_js_mod(d, e) + e, e), False
  1260. except Exception:
  1261. return None, True
  1262. def extract_function_code(self, funcname):
  1263. """ @returns argnames, code """
  1264. func_m = re.search(
  1265. r'''(?xs)
  1266. (?:
  1267. function\s+%(name)s|
  1268. [{;,]\s*%(name)s\s*=\s*function|
  1269. (?:var|const|let)\s+%(name)s\s*=\s*function
  1270. )\s*
  1271. \((?P<args>[^)]*)\)\s*
  1272. (?P<code>{.+})''' % {'name': re.escape(funcname)},
  1273. self.code)
  1274. if func_m is None:
  1275. raise self.Exception('Could not find JS function "{funcname}"'.format(**locals()))
  1276. code, _ = self._separate_at_paren(func_m.group('code')) # refine the match
  1277. return self.build_arglist(func_m.group('args')), code
  1278. def extract_function(self, funcname, *global_stack):
  1279. return function_with_repr(
  1280. self.extract_function_from_code(*itertools.chain(
  1281. self.extract_function_code(funcname), global_stack)),
  1282. 'F<%s>' % (funcname,))
  1283. def extract_function_from_code(self, argnames, code, *global_stack):
  1284. local_vars = {}
  1285. start = None
  1286. while True:
  1287. mobj = re.search(r'function\((?P<args>[^)]*)\)\s*{', code[start:])
  1288. if mobj is None:
  1289. break
  1290. start, body_start = ((start or 0) + x for x in mobj.span())
  1291. body, remaining = self._separate_at_paren(code[body_start - 1:])
  1292. name = self._named_object(local_vars, self.extract_function_from_code(
  1293. [x.strip() for x in mobj.group('args').split(',')],
  1294. body, local_vars, *global_stack))
  1295. code = code[:start] + name + remaining
  1296. return self.build_function(argnames, code, local_vars, *global_stack)
  1297. def call_function(self, funcname, *args, **kw_global_vars):
  1298. return self.extract_function(funcname)(args, kw_global_vars)
  1299. @classmethod
  1300. def build_arglist(cls, arg_text):
  1301. if not arg_text:
  1302. return []
  1303. def valid_arg(y):
  1304. y = y.strip()
  1305. if not y:
  1306. raise cls.Exception('Missing arg in "%s"' % (arg_text, ))
  1307. return y
  1308. return [valid_arg(x) for x in cls._separate(arg_text)]
  1309. def build_function(self, argnames, code, *global_stack):
  1310. global_stack = list(global_stack) or [{}]
  1311. argnames = tuple(argnames)
  1312. def resf(args, kwargs=None, allow_recursion=100):
  1313. kwargs = kwargs or {}
  1314. global_stack[0].update(zip_longest(argnames, args, fillvalue=JS_Undefined))
  1315. global_stack[0].update(kwargs)
  1316. var_stack = LocalNameSpace(*global_stack)
  1317. ret, should_abort = self.interpret_statement(code.replace('\n', ' '), var_stack, allow_recursion - 1)
  1318. if should_abort:
  1319. return ret
  1320. return resf