jsinterp.py 55 KB

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