jsinterp.py 56 KB

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