jsinterp.py 53 KB

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