jsinterp.py 56 KB

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