jsinterp.py 55 KB

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