jsinterp.py 52 KB

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