jsinterp.py 56 KB

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