jsinterp.py 41 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042
  1. from __future__ import unicode_literals
  2. import itertools
  3. import json
  4. import math
  5. import operator
  6. import re
  7. from functools import update_wrapper
  8. from .utils import (
  9. error_to_compat_str,
  10. ExtractorError,
  11. js_to_json,
  12. remove_quotes,
  13. unified_timestamp,
  14. variadic,
  15. )
  16. from .compat import (
  17. compat_basestring,
  18. compat_chr,
  19. compat_collections_chain_map as ChainMap,
  20. compat_itertools_zip_longest as zip_longest,
  21. compat_str,
  22. )
  23. # name JS functions
  24. class function_with_repr(object):
  25. # from yt_dlp/utils.py, but in this module
  26. # repr_ is always set
  27. def __init__(self, func, repr_):
  28. update_wrapper(self, func)
  29. self.func, self.__repr = func, repr_
  30. def __call__(self, *args, **kwargs):
  31. return self.func(*args, **kwargs)
  32. def __repr__(self):
  33. return self.__repr
  34. # name JS operators
  35. def wraps_op(op):
  36. def update_and_rename_wrapper(w):
  37. f = update_wrapper(w, op)
  38. # fn names are str in both Py 2/3
  39. f.__name__ = str('JS_') + f.__name__
  40. return f
  41. return update_and_rename_wrapper
  42. _NaN = float('nan')
  43. def _js_bit_op(op):
  44. def zeroise(x):
  45. return 0 if x in (None, JS_Undefined, _NaN) else x
  46. @wraps_op(op)
  47. def wrapped(a, b):
  48. return op(zeroise(a), zeroise(b)) & 0xffffffff
  49. return wrapped
  50. def _js_arith_op(op):
  51. @wraps_op(op)
  52. def wrapped(a, b):
  53. if JS_Undefined in (a, b):
  54. return _NaN
  55. return op(a or 0, b or 0)
  56. return wrapped
  57. def _js_div(a, b):
  58. if JS_Undefined in (a, b) or not (a and b):
  59. return _NaN
  60. return operator.truediv(a or 0, b) if b else float('inf')
  61. def _js_mod(a, b):
  62. if JS_Undefined in (a, b) or not b:
  63. return _NaN
  64. return (a or 0) % b
  65. def _js_exp(a, b):
  66. if not b:
  67. return 1 # even 0 ** 0 !!
  68. elif JS_Undefined in (a, b):
  69. return _NaN
  70. return (a or 0) ** b
  71. def _js_eq_op(op):
  72. @wraps_op(op)
  73. def wrapped(a, b):
  74. if set((a, b)) <= set((None, JS_Undefined)):
  75. return op(a, a)
  76. return op(a, b)
  77. return wrapped
  78. def _js_comp_op(op):
  79. @wraps_op(op)
  80. def wrapped(a, b):
  81. if JS_Undefined in (a, b):
  82. return False
  83. if isinstance(a, compat_basestring):
  84. b = compat_str(b or 0)
  85. elif isinstance(b, compat_basestring):
  86. a = compat_str(a or 0)
  87. return op(a or 0, b or 0)
  88. return wrapped
  89. def _js_ternary(cndn, if_true=True, if_false=False):
  90. """Simulate JS's ternary operator (cndn?if_true:if_false)"""
  91. if cndn in (False, None, 0, '', JS_Undefined):
  92. return if_false
  93. try:
  94. if math.isnan(cndn): # NB: NaN cannot be checked by membership
  95. return if_false
  96. except TypeError:
  97. pass
  98. return if_true
  99. # (op, definition) in order of binding priority, tightest first
  100. # avoid dict to maintain order
  101. # definition None => Defined in JSInterpreter._operator
  102. _OPERATORS = (
  103. ('>>', _js_bit_op(operator.rshift)),
  104. ('<<', _js_bit_op(operator.lshift)),
  105. ('+', _js_arith_op(operator.add)),
  106. ('-', _js_arith_op(operator.sub)),
  107. ('*', _js_arith_op(operator.mul)),
  108. ('%', _js_mod),
  109. ('/', _js_div),
  110. ('**', _js_exp),
  111. )
  112. _COMP_OPERATORS = (
  113. ('===', operator.is_),
  114. ('!==', operator.is_not),
  115. ('==', _js_eq_op(operator.eq)),
  116. ('!=', _js_eq_op(operator.ne)),
  117. ('<=', _js_comp_op(operator.le)),
  118. ('>=', _js_comp_op(operator.ge)),
  119. ('<', _js_comp_op(operator.lt)),
  120. ('>', _js_comp_op(operator.gt)),
  121. )
  122. _LOG_OPERATORS = (
  123. ('|', _js_bit_op(operator.or_)),
  124. ('^', _js_bit_op(operator.xor)),
  125. ('&', _js_bit_op(operator.and_)),
  126. )
  127. _SC_OPERATORS = (
  128. ('?', None),
  129. ('??', None),
  130. ('||', None),
  131. ('&&', None),
  132. )
  133. _OPERATOR_RE = '|'.join(map(lambda x: re.escape(x[0]), _OPERATORS + _LOG_OPERATORS))
  134. _NAME_RE = r'[a-zA-Z_$][\w$]*'
  135. _MATCHING_PARENS = dict(zip(*zip('()', '{}', '[]')))
  136. _QUOTES = '\'"/'
  137. class JS_Undefined(object):
  138. pass
  139. class JS_Break(ExtractorError):
  140. def __init__(self):
  141. ExtractorError.__init__(self, 'Invalid break')
  142. class JS_Continue(ExtractorError):
  143. def __init__(self):
  144. ExtractorError.__init__(self, 'Invalid continue')
  145. class JS_Throw(ExtractorError):
  146. def __init__(self, e):
  147. self.error = e
  148. ExtractorError.__init__(self, 'Uncaught exception ' + error_to_compat_str(e))
  149. class LocalNameSpace(ChainMap):
  150. def __getitem__(self, key):
  151. try:
  152. return super(LocalNameSpace, self).__getitem__(key)
  153. except KeyError:
  154. return JS_Undefined
  155. def __setitem__(self, key, value):
  156. for scope in self.maps:
  157. if key in scope:
  158. scope[key] = value
  159. return
  160. self.maps[0][key] = value
  161. def __delitem__(self, key):
  162. raise NotImplementedError('Deleting is not supported')
  163. def __repr__(self):
  164. return 'LocalNameSpace%s' % (self.maps, )
  165. class JSInterpreter(object):
  166. __named_object_counter = 0
  167. _OBJ_NAME = '__youtube_dl_jsinterp_obj'
  168. OP_CHARS = None
  169. def __init__(self, code, objects=None):
  170. self.code, self._functions = code, {}
  171. self._objects = {} if objects is None else objects
  172. if type(self).OP_CHARS is None:
  173. type(self).OP_CHARS = self.OP_CHARS = self.__op_chars()
  174. class Exception(ExtractorError):
  175. def __init__(self, msg, *args, **kwargs):
  176. expr = kwargs.pop('expr', None)
  177. if expr is not None:
  178. msg = '{0} in: {1!r:.100}'.format(msg.rstrip(), expr)
  179. super(JSInterpreter.Exception, self).__init__(msg, *args, **kwargs)
  180. class JS_RegExp(object):
  181. RE_FLAGS = {
  182. # special knowledge: Python's re flags are bitmask values, current max 128
  183. # invent new bitmask values well above that for literal parsing
  184. # TODO: execute matches with these flags (remaining: d, y)
  185. 'd': 1024, # Generate indices for substring matches
  186. 'g': 2048, # Global search
  187. 'i': re.I, # Case-insensitive search
  188. 'm': re.M, # Multi-line search
  189. 's': re.S, # Allows . to match newline characters
  190. 'u': re.U, # Treat a pattern as a sequence of unicode code points
  191. 'y': 4096, # Perform a "sticky" search that matches starting at the current position in the target string
  192. }
  193. def __init__(self, pattern_txt, flags=0):
  194. if isinstance(flags, compat_str):
  195. flags, _ = self.regex_flags(flags)
  196. # First, avoid https://github.com/python/cpython/issues/74534
  197. self.__self = None
  198. self.__pattern_txt = pattern_txt.replace('[[', r'[\[')
  199. self.__flags = flags
  200. def __instantiate(self):
  201. if self.__self:
  202. return
  203. self.__self = re.compile(self.__pattern_txt, self.__flags)
  204. # Thx: https://stackoverflow.com/questions/44773522/setattr-on-python2-sre-sre-pattern
  205. for name in dir(self.__self):
  206. # Only these? Obviously __class__, __init__.
  207. # PyPy creates a __weakref__ attribute with value None
  208. # that can't be setattr'd but also can't need to be copied.
  209. if name in ('__class__', '__init__', '__weakref__'):
  210. continue
  211. setattr(self, name, getattr(self.__self, name))
  212. def __getattr__(self, name):
  213. self.__instantiate()
  214. if hasattr(self, name):
  215. return getattr(self, name)
  216. return super(JSInterpreter.JS_RegExp, self).__getattr__(name)
  217. @classmethod
  218. def regex_flags(cls, expr):
  219. flags = 0
  220. if not expr:
  221. return flags, expr
  222. for idx, ch in enumerate(expr):
  223. if ch not in cls.RE_FLAGS:
  224. break
  225. flags |= cls.RE_FLAGS[ch]
  226. return flags, expr[idx + 1:]
  227. @classmethod
  228. def __op_chars(cls):
  229. op_chars = set(';,[')
  230. for op in cls._all_operators():
  231. for c in op[0]:
  232. op_chars.add(c)
  233. return op_chars
  234. def _named_object(self, namespace, obj):
  235. self.__named_object_counter += 1
  236. name = '%s%d' % (self._OBJ_NAME, self.__named_object_counter)
  237. if callable(obj) and not isinstance(obj, function_with_repr):
  238. obj = function_with_repr(obj, 'F<%s>' % (self.__named_object_counter, ))
  239. namespace[name] = obj
  240. return name
  241. @classmethod
  242. def _separate(cls, expr, delim=',', max_split=None, skip_delims=None):
  243. if not expr:
  244. return
  245. # collections.Counter() is ~10% slower in both 2.7 and 3.9
  246. counters = dict((k, 0) for k in _MATCHING_PARENS.values())
  247. start, splits, pos, delim_len = 0, 0, 0, len(delim) - 1
  248. in_quote, escaping, skipping = None, False, 0
  249. after_op, in_regex_char_group = True, False
  250. for idx, char in enumerate(expr):
  251. paren_delta = 0
  252. if not in_quote:
  253. if char in _MATCHING_PARENS:
  254. counters[_MATCHING_PARENS[char]] += 1
  255. paren_delta = 1
  256. elif char in counters:
  257. counters[char] -= 1
  258. paren_delta = -1
  259. if not escaping:
  260. if char in _QUOTES and in_quote in (char, None):
  261. if in_quote or after_op or char != '/':
  262. in_quote = None if in_quote and not in_regex_char_group else char
  263. elif in_quote == '/' and char in '[]':
  264. in_regex_char_group = char == '['
  265. escaping = not escaping and in_quote and char == '\\'
  266. after_op = not in_quote and (char in cls.OP_CHARS or paren_delta > 0 or (after_op and char.isspace()))
  267. if char != delim[pos] or any(counters.values()) or in_quote:
  268. pos = skipping = 0
  269. continue
  270. elif skipping > 0:
  271. skipping -= 1
  272. continue
  273. elif pos == 0 and skip_delims:
  274. here = expr[idx:]
  275. for s in variadic(skip_delims):
  276. if here.startswith(s) and s:
  277. skipping = len(s) - 1
  278. break
  279. if skipping > 0:
  280. continue
  281. if pos < delim_len:
  282. pos += 1
  283. continue
  284. yield expr[start: idx - delim_len]
  285. start, pos = idx + 1, 0
  286. splits += 1
  287. if max_split and splits >= max_split:
  288. break
  289. yield expr[start:]
  290. @classmethod
  291. def _separate_at_paren(cls, expr, delim=None):
  292. if delim is None:
  293. delim = expr and _MATCHING_PARENS[expr[0]]
  294. separated = list(cls._separate(expr, delim, 1))
  295. if len(separated) < 2:
  296. raise cls.Exception('No terminating paren {delim} in {expr!r:.5500}'.format(**locals()))
  297. return separated[0][1:].strip(), separated[1].strip()
  298. @staticmethod
  299. def _all_operators():
  300. return itertools.chain(
  301. # Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
  302. _SC_OPERATORS, _LOG_OPERATORS, _COMP_OPERATORS, _OPERATORS)
  303. def _operator(self, op, left_val, right_expr, expr, local_vars, allow_recursion):
  304. if op in ('||', '&&'):
  305. if (op == '&&') ^ _js_ternary(left_val):
  306. return left_val # short circuiting
  307. elif op == '??':
  308. if left_val not in (None, JS_Undefined):
  309. return left_val
  310. elif op == '?':
  311. right_expr = _js_ternary(left_val, *self._separate(right_expr, ':', 1))
  312. right_val = self.interpret_expression(right_expr, local_vars, allow_recursion)
  313. opfunc = op and next((v for k, v in self._all_operators() if k == op), None)
  314. if not opfunc:
  315. return right_val
  316. try:
  317. # print('Eval:', opfunc.__name__, left_val, right_val)
  318. return opfunc(left_val, right_val)
  319. except Exception as e:
  320. raise self.Exception('Failed to evaluate {left_val!r:.50} {op} {right_val!r:.50}'.format(**locals()), expr, cause=e)
  321. def _index(self, obj, idx, allow_undefined=False):
  322. if idx == 'length':
  323. return len(obj)
  324. try:
  325. return obj[int(idx)] if isinstance(obj, list) else obj[idx]
  326. except Exception as e:
  327. if allow_undefined:
  328. return JS_Undefined
  329. raise self.Exception('Cannot get index {idx:.100}'.format(**locals()), expr=repr(obj), cause=e)
  330. def _dump(self, obj, namespace):
  331. try:
  332. return json.dumps(obj)
  333. except TypeError:
  334. return self._named_object(namespace, obj)
  335. # used below
  336. _VAR_RET_THROW_RE = re.compile(r'''(?x)
  337. (?P<var>(?:var|const|let)\s)|return(?:\s+|(?=["'])|$)|(?P<throw>throw\s+)
  338. ''')
  339. _COMPOUND_RE = re.compile(r'''(?x)
  340. (?P<try>try)\s*\{|
  341. (?P<if>if)\s*\(|
  342. (?P<switch>switch)\s*\(|
  343. (?P<for>for)\s*\(|
  344. (?P<while>while)\s*\(
  345. ''')
  346. _FINALLY_RE = re.compile(r'finally\s*\{')
  347. _SWITCH_RE = re.compile(r'switch\s*\(')
  348. def interpret_statement(self, stmt, local_vars, allow_recursion=100):
  349. if allow_recursion < 0:
  350. raise self.Exception('Recursion limit reached')
  351. allow_recursion -= 1
  352. # print('At: ' + stmt[:60])
  353. should_return = False
  354. # fails on (eg) if (...) stmt1; else stmt2;
  355. sub_statements = list(self._separate(stmt, ';')) or ['']
  356. expr = stmt = sub_statements.pop().strip()
  357. for sub_stmt in sub_statements:
  358. ret, should_return = self.interpret_statement(sub_stmt, local_vars, allow_recursion)
  359. if should_return:
  360. return ret, should_return
  361. m = self._VAR_RET_THROW_RE.match(stmt)
  362. if m:
  363. expr = stmt[len(m.group(0)):].strip()
  364. if m.group('throw'):
  365. raise JS_Throw(self.interpret_expression(expr, local_vars, allow_recursion))
  366. should_return = not m.group('var')
  367. if not expr:
  368. return None, should_return
  369. if expr[0] in _QUOTES:
  370. inner, outer = self._separate(expr, expr[0], 1)
  371. if expr[0] == '/':
  372. flags, outer = self.JS_RegExp.regex_flags(outer)
  373. inner = self.JS_RegExp(inner[1:], flags=flags)
  374. else:
  375. inner = json.loads(js_to_json(inner + expr[0])) # , strict=True))
  376. if not outer:
  377. return inner, should_return
  378. expr = self._named_object(local_vars, inner) + outer
  379. new_kw, _, obj = expr.partition('new ')
  380. if not new_kw:
  381. for klass, konstr in (('Date', lambda x: int(unified_timestamp(x, False) * 1000)),
  382. ('RegExp', self.JS_RegExp),
  383. ('Error', self.Exception)):
  384. if not obj.startswith(klass + '('):
  385. continue
  386. left, right = self._separate_at_paren(obj[len(klass):])
  387. argvals = self.interpret_iter(left, local_vars, allow_recursion)
  388. expr = konstr(*argvals)
  389. if expr is None:
  390. raise self.Exception('Failed to parse {klass} {left!r:.100}'.format(**locals()), expr=expr)
  391. expr = self._dump(expr, local_vars) + right
  392. break
  393. else:
  394. raise self.Exception('Unsupported object {obj:.100}'.format(**locals()), expr=expr)
  395. if expr.startswith('void '):
  396. left = self.interpret_expression(expr[5:], local_vars, allow_recursion)
  397. return None, should_return
  398. if expr.startswith('{'):
  399. inner, outer = self._separate_at_paren(expr)
  400. # try for object expression (Map)
  401. sub_expressions = [list(self._separate(sub_expr.strip(), ':', 1)) for sub_expr in self._separate(inner)]
  402. if all(len(sub_expr) == 2 for sub_expr in sub_expressions):
  403. return dict(
  404. (key_expr if re.match(_NAME_RE, key_expr) else key_expr,
  405. self.interpret_expression(val_expr, local_vars, allow_recursion))
  406. for key_expr, val_expr in sub_expressions), should_return
  407. # or statement list
  408. inner, should_abort = self.interpret_statement(inner, local_vars, allow_recursion)
  409. if not outer or should_abort:
  410. return inner, should_abort or should_return
  411. else:
  412. expr = self._dump(inner, local_vars) + outer
  413. if expr.startswith('('):
  414. m = re.match(r'\((?P<d>[a-z])%(?P<e>[a-z])\.length\+(?P=e)\.length\)%(?P=e)\.length', expr)
  415. if m:
  416. # short-cut eval of frequently used `(d%e.length+e.length)%e.length`, worth ~6% on `pytest -k test_nsig`
  417. outer = None
  418. inner, should_abort = self._offset_e_by_d(m.group('d'), m.group('e'), local_vars)
  419. else:
  420. inner, outer = self._separate_at_paren(expr)
  421. inner, should_abort = self.interpret_statement(inner, local_vars, allow_recursion)
  422. if not outer or should_abort:
  423. return inner, should_abort or should_return
  424. else:
  425. expr = self._dump(inner, local_vars) + outer
  426. if expr.startswith('['):
  427. inner, outer = self._separate_at_paren(expr)
  428. name = self._named_object(local_vars, [
  429. self.interpret_expression(item, local_vars, allow_recursion)
  430. for item in self._separate(inner)])
  431. expr = name + outer
  432. m = self._COMPOUND_RE.match(expr)
  433. md = m.groupdict() if m else {}
  434. if md.get('if'):
  435. cndn, expr = self._separate_at_paren(expr[m.end() - 1:])
  436. if expr.startswith('{'):
  437. if_expr, expr = self._separate_at_paren(expr)
  438. else:
  439. # may lose ... else ... because of ll.368-374
  440. if_expr, expr = self._separate_at_paren(expr, delim=';')
  441. else_expr = None
  442. m = re.match(r'else\s*(?P<block>\{)?', expr)
  443. if m:
  444. if m.group('block'):
  445. else_expr, expr = self._separate_at_paren(expr[m.end() - 1:])
  446. else:
  447. # handle subset ... else if (...) {...} else ...
  448. # TODO: make interpret_statement do this properly, if possible
  449. exprs = list(self._separate(expr[m.end():], delim='}', max_split=2))
  450. if len(exprs) > 1:
  451. if re.match(r'\s*if\s*\(', exprs[0]) and re.match(r'\s*else\b', exprs[1]):
  452. else_expr = exprs[0] + '}' + exprs[1]
  453. expr = (exprs[2] + '}') if len(exprs) == 3 else None
  454. else:
  455. else_expr = exprs[0]
  456. exprs.append('')
  457. expr = '}'.join(exprs[1:])
  458. else:
  459. else_expr = exprs[0]
  460. expr = None
  461. else_expr = else_expr.lstrip() + '}'
  462. cndn = _js_ternary(self.interpret_expression(cndn, local_vars, allow_recursion))
  463. ret, should_abort = self.interpret_statement(
  464. if_expr if cndn else else_expr, local_vars, allow_recursion)
  465. if should_abort:
  466. return ret, True
  467. elif md.get('try'):
  468. try_expr, expr = self._separate_at_paren(expr[m.end() - 1:])
  469. err = None
  470. try:
  471. ret, should_abort = self.interpret_statement(try_expr, local_vars, allow_recursion)
  472. if should_abort:
  473. return ret, True
  474. except Exception as e:
  475. # XXX: This works for now, but makes debugging future issues very hard
  476. err = e
  477. pending = (None, False)
  478. m = re.match(r'catch\s*(?P<err>\(\s*{_NAME_RE}\s*\))?\{{'.format(**globals()), expr)
  479. if m:
  480. sub_expr, expr = self._separate_at_paren(expr[m.end() - 1:])
  481. if err:
  482. catch_vars = {}
  483. if m.group('err'):
  484. catch_vars[m.group('err')] = err.error if isinstance(err, JS_Throw) else err
  485. catch_vars = local_vars.new_child(m=catch_vars)
  486. err = None
  487. pending = self.interpret_statement(sub_expr, catch_vars, allow_recursion)
  488. m = self._FINALLY_RE.match(expr)
  489. if m:
  490. sub_expr, expr = self._separate_at_paren(expr[m.end() - 1:])
  491. ret, should_abort = self.interpret_statement(sub_expr, local_vars, allow_recursion)
  492. if should_abort:
  493. return ret, True
  494. ret, should_abort = pending
  495. if should_abort:
  496. return ret, True
  497. if err:
  498. raise err
  499. elif md.get('for') or md.get('while'):
  500. init_or_cond, remaining = self._separate_at_paren(expr[m.end() - 1:])
  501. if remaining.startswith('{'):
  502. body, expr = self._separate_at_paren(remaining)
  503. else:
  504. switch_m = self._SWITCH_RE.match(remaining) # FIXME
  505. if switch_m:
  506. switch_val, remaining = self._separate_at_paren(remaining[switch_m.end() - 1:])
  507. body, expr = self._separate_at_paren(remaining, '}')
  508. body = 'switch(%s){%s}' % (switch_val, body)
  509. else:
  510. body, expr = remaining, ''
  511. if md.get('for'):
  512. start, cndn, increment = self._separate(init_or_cond, ';')
  513. self.interpret_expression(start, local_vars, allow_recursion)
  514. else:
  515. cndn, increment = init_or_cond, None
  516. while _js_ternary(self.interpret_expression(cndn, local_vars, allow_recursion)):
  517. try:
  518. ret, should_abort = self.interpret_statement(body, local_vars, allow_recursion)
  519. if should_abort:
  520. return ret, True
  521. except JS_Break:
  522. break
  523. except JS_Continue:
  524. pass
  525. if increment:
  526. self.interpret_expression(increment, local_vars, allow_recursion)
  527. elif md.get('switch'):
  528. switch_val, remaining = self._separate_at_paren(expr[m.end() - 1:])
  529. switch_val = self.interpret_expression(switch_val, local_vars, allow_recursion)
  530. body, expr = self._separate_at_paren(remaining, '}')
  531. items = body.replace('default:', 'case default:').split('case ')[1:]
  532. for default in (False, True):
  533. matched = False
  534. for item in items:
  535. case, stmt = (i.strip() for i in self._separate(item, ':', 1))
  536. if default:
  537. matched = matched or case == 'default'
  538. elif not matched:
  539. matched = (case != 'default'
  540. and switch_val == self.interpret_expression(case, local_vars, allow_recursion))
  541. if not matched:
  542. continue
  543. try:
  544. ret, should_abort = self.interpret_statement(stmt, local_vars, allow_recursion)
  545. if should_abort:
  546. return ret
  547. except JS_Break:
  548. break
  549. if matched:
  550. break
  551. if md:
  552. ret, should_abort = self.interpret_statement(expr, local_vars, allow_recursion)
  553. return ret, should_abort or should_return
  554. # Comma separated statements
  555. sub_expressions = list(self._separate(expr))
  556. if len(sub_expressions) > 1:
  557. for sub_expr in sub_expressions:
  558. ret, should_abort = self.interpret_statement(sub_expr, local_vars, allow_recursion)
  559. if should_abort:
  560. return ret, True
  561. return ret, False
  562. for m in re.finditer(r'''(?x)
  563. (?P<pre_sign>\+\+|--)(?P<var1>{_NAME_RE})|
  564. (?P<var2>{_NAME_RE})(?P<post_sign>\+\+|--)'''.format(**globals()), expr):
  565. var = m.group('var1') or m.group('var2')
  566. start, end = m.span()
  567. sign = m.group('pre_sign') or m.group('post_sign')
  568. ret = local_vars[var]
  569. local_vars[var] += 1 if sign[0] == '+' else -1
  570. if m.group('pre_sign'):
  571. ret = local_vars[var]
  572. expr = expr[:start] + self._dump(ret, local_vars) + expr[end:]
  573. if not expr:
  574. return None, should_return
  575. m = re.match(r'''(?x)
  576. (?P<assign>
  577. (?P<out>{_NAME_RE})(?:\[(?P<index>[^\]]+?)\])?\s*
  578. (?P<op>{_OPERATOR_RE})?
  579. =(?!=)(?P<expr>.*)$
  580. )|(?P<return>
  581. (?!if|return|true|false|null|undefined)(?P<name>{_NAME_RE})$
  582. )|(?P<indexing>
  583. (?P<in>{_NAME_RE})\[(?P<idx>.+)\]$
  584. )|(?P<attribute>
  585. (?P<var>{_NAME_RE})(?:(?P<nullish>\?)?\.(?P<member>[^(]+)|\[(?P<member2>[^\]]+)\])\s*
  586. )|(?P<function>
  587. (?P<fname>{_NAME_RE})\((?P<args>.*)\)$
  588. )'''.format(**globals()), expr)
  589. md = m.groupdict() if m else {}
  590. if md.get('assign'):
  591. left_val = local_vars.get(m.group('out'))
  592. if not m.group('index'):
  593. local_vars[m.group('out')] = self._operator(
  594. m.group('op'), left_val, m.group('expr'), expr, local_vars, allow_recursion)
  595. return local_vars[m.group('out')], should_return
  596. elif left_val in (None, JS_Undefined):
  597. raise self.Exception('Cannot index undefined variable ' + m.group('out'), expr=expr)
  598. idx = self.interpret_expression(m.group('index'), local_vars, allow_recursion)
  599. if not isinstance(idx, (int, float)):
  600. raise self.Exception('List index %s must be integer' % (idx, ), expr=expr)
  601. idx = int(idx)
  602. left_val[idx] = self._operator(
  603. m.group('op'), self._index(left_val, idx), m.group('expr'), expr, local_vars, allow_recursion)
  604. return left_val[idx], should_return
  605. elif expr.isdigit():
  606. return int(expr), should_return
  607. elif expr == 'break':
  608. raise JS_Break()
  609. elif expr == 'continue':
  610. raise JS_Continue()
  611. elif expr == 'undefined':
  612. return JS_Undefined, should_return
  613. elif expr == 'NaN':
  614. return _NaN, should_return
  615. elif md.get('return'):
  616. return local_vars[m.group('name')], should_return
  617. try:
  618. ret = json.loads(js_to_json(expr)) # strict=True)
  619. if not md.get('attribute'):
  620. return ret, should_return
  621. except ValueError:
  622. pass
  623. if md.get('indexing'):
  624. val = local_vars[m.group('in')]
  625. idx = self.interpret_expression(m.group('idx'), local_vars, allow_recursion)
  626. return self._index(val, idx), should_return
  627. for op, _ in self._all_operators():
  628. # hackety: </> have higher priority than <</>>, but don't confuse them
  629. skip_delim = (op + op) if op in '<>*?' else None
  630. if op == '?':
  631. skip_delim = (skip_delim, '?.')
  632. separated = list(self._separate(expr, op, skip_delims=skip_delim))
  633. if len(separated) < 2:
  634. continue
  635. right_expr = separated.pop()
  636. # handle operators that are both unary and binary, minimal BODMAS
  637. if op in ('+', '-'):
  638. undone = 0
  639. while len(separated) > 1 and not separated[-1].strip():
  640. undone += 1
  641. separated.pop()
  642. if op == '-' and undone % 2 != 0:
  643. right_expr = op + right_expr
  644. left_val = separated[-1]
  645. for dm_op in ('*', '%', '/', '**'):
  646. bodmas = tuple(self._separate(left_val, dm_op, skip_delims=skip_delim))
  647. if len(bodmas) > 1 and not bodmas[-1].strip():
  648. expr = op.join(separated) + op + right_expr
  649. right_expr = None
  650. break
  651. if right_expr is None:
  652. continue
  653. left_val = self.interpret_expression(op.join(separated), local_vars, allow_recursion)
  654. return self._operator(op, left_val, right_expr, expr, local_vars, allow_recursion), should_return
  655. if md.get('attribute'):
  656. variable, member, nullish = m.group('var', 'member', 'nullish')
  657. if not member:
  658. member = self.interpret_expression(m.group('member2'), local_vars, allow_recursion)
  659. arg_str = expr[m.end():]
  660. if arg_str.startswith('('):
  661. arg_str, remaining = self._separate_at_paren(arg_str)
  662. else:
  663. arg_str, remaining = None, arg_str
  664. def assertion(cndn, msg):
  665. """ assert, but without risk of getting optimized out """
  666. if not cndn:
  667. memb = member
  668. raise self.Exception('{memb} {msg}'.format(**locals()), expr=expr)
  669. def eval_method():
  670. if (variable, member) == ('console', 'debug'):
  671. return
  672. types = {
  673. 'String': compat_str,
  674. 'Math': float,
  675. }
  676. obj = local_vars.get(variable)
  677. if obj in (JS_Undefined, None):
  678. obj = types.get(variable, JS_Undefined)
  679. if obj is JS_Undefined:
  680. try:
  681. if variable not in self._objects:
  682. self._objects[variable] = self.extract_object(variable)
  683. obj = self._objects[variable]
  684. except self.Exception:
  685. if not nullish:
  686. raise
  687. if nullish and obj is JS_Undefined:
  688. return JS_Undefined
  689. # Member access
  690. if arg_str is None:
  691. return self._index(obj, member, nullish)
  692. # Function call
  693. argvals = [
  694. self.interpret_expression(v, local_vars, allow_recursion)
  695. for v in self._separate(arg_str)]
  696. if obj == compat_str:
  697. if member == 'fromCharCode':
  698. assertion(argvals, 'takes one or more arguments')
  699. return ''.join(map(compat_chr, argvals))
  700. raise self.Exception('Unsupported string method ' + member, expr=expr)
  701. elif obj == float:
  702. if member == 'pow':
  703. assertion(len(argvals) == 2, 'takes two arguments')
  704. return argvals[0] ** argvals[1]
  705. raise self.Exception('Unsupported Math method ' + member, expr=expr)
  706. if member == 'split':
  707. assertion(argvals, 'takes one or more arguments')
  708. assertion(len(argvals) == 1, 'with limit argument is not implemented')
  709. return obj.split(argvals[0]) if argvals[0] else list(obj)
  710. elif member == 'join':
  711. assertion(isinstance(obj, list), 'must be applied on a list')
  712. assertion(len(argvals) == 1, 'takes exactly one argument')
  713. return argvals[0].join(obj)
  714. elif member == 'reverse':
  715. assertion(not argvals, 'does not take any arguments')
  716. obj.reverse()
  717. return obj
  718. elif member == 'slice':
  719. assertion(isinstance(obj, list), 'must be applied on a list')
  720. assertion(len(argvals) == 1, 'takes exactly one argument')
  721. return obj[argvals[0]:]
  722. elif member == 'splice':
  723. assertion(isinstance(obj, list), 'must be applied on a list')
  724. assertion(argvals, 'takes one or more arguments')
  725. index, howMany = map(int, (argvals + [len(obj)])[:2])
  726. if index < 0:
  727. index += len(obj)
  728. add_items = argvals[2:]
  729. res = []
  730. for i in range(index, min(index + howMany, len(obj))):
  731. res.append(obj.pop(index))
  732. for i, item in enumerate(add_items):
  733. obj.insert(index + i, item)
  734. return res
  735. elif member == 'unshift':
  736. assertion(isinstance(obj, list), 'must be applied on a list')
  737. assertion(argvals, 'takes one or more arguments')
  738. for item in reversed(argvals):
  739. obj.insert(0, item)
  740. return obj
  741. elif member == 'pop':
  742. assertion(isinstance(obj, list), 'must be applied on a list')
  743. assertion(not argvals, 'does not take any arguments')
  744. if not obj:
  745. return
  746. return obj.pop()
  747. elif member == 'push':
  748. assertion(argvals, 'takes one or more arguments')
  749. obj.extend(argvals)
  750. return obj
  751. elif member == 'forEach':
  752. assertion(argvals, 'takes one or more arguments')
  753. assertion(len(argvals) <= 2, 'takes at-most 2 arguments')
  754. f, this = (argvals + [''])[:2]
  755. return [f((item, idx, obj), {'this': this}, allow_recursion) for idx, item in enumerate(obj)]
  756. elif member == 'indexOf':
  757. assertion(argvals, 'takes one or more arguments')
  758. assertion(len(argvals) <= 2, 'takes at-most 2 arguments')
  759. idx, start = (argvals + [0])[:2]
  760. try:
  761. return obj.index(idx, start)
  762. except ValueError:
  763. return -1
  764. elif member == 'charCodeAt':
  765. assertion(isinstance(obj, compat_str), 'must be applied on a string')
  766. # assertion(len(argvals) == 1, 'takes exactly one argument') # but not enforced
  767. idx = argvals[0] if isinstance(argvals[0], int) else 0
  768. if idx >= len(obj):
  769. return None
  770. return ord(obj[idx])
  771. elif member in ('replace', 'replaceAll'):
  772. assertion(isinstance(obj, compat_str), 'must be applied on a string')
  773. assertion(len(argvals) == 2, 'takes exactly two arguments')
  774. # TODO: argvals[1] callable, other Py vs JS edge cases
  775. if isinstance(argvals[0], self.JS_RegExp):
  776. count = 0 if argvals[0].flags & self.JS_RegExp.RE_FLAGS['g'] else 1
  777. assertion(member != 'replaceAll' or count == 0,
  778. 'replaceAll must be called with a global RegExp')
  779. return argvals[0].sub(argvals[1], obj, count=count)
  780. count = ('replaceAll', 'replace').index(member)
  781. return re.sub(re.escape(argvals[0]), argvals[1], obj, count=count)
  782. idx = int(member) if isinstance(obj, list) else member
  783. return obj[idx](argvals, allow_recursion=allow_recursion)
  784. if remaining:
  785. ret, should_abort = self.interpret_statement(
  786. self._named_object(local_vars, eval_method()) + remaining,
  787. local_vars, allow_recursion)
  788. return ret, should_return or should_abort
  789. else:
  790. return eval_method(), should_return
  791. elif md.get('function'):
  792. fname = m.group('fname')
  793. argvals = [self.interpret_expression(v, local_vars, allow_recursion)
  794. for v in self._separate(m.group('args'))]
  795. if fname in local_vars:
  796. return local_vars[fname](argvals, allow_recursion=allow_recursion), should_return
  797. elif fname not in self._functions:
  798. self._functions[fname] = self.extract_function(fname)
  799. return self._functions[fname](argvals, allow_recursion=allow_recursion), should_return
  800. raise self.Exception(
  801. 'Unsupported JS expression ' + (expr[:40] if expr != stmt else ''), expr=stmt)
  802. def interpret_expression(self, expr, local_vars, allow_recursion):
  803. ret, should_return = self.interpret_statement(expr, local_vars, allow_recursion)
  804. if should_return:
  805. raise self.Exception('Cannot return from an expression', expr)
  806. return ret
  807. def interpret_iter(self, list_txt, local_vars, allow_recursion):
  808. for v in self._separate(list_txt):
  809. yield self.interpret_expression(v, local_vars, allow_recursion)
  810. def extract_object(self, objname):
  811. _FUNC_NAME_RE = r'''(?:[a-zA-Z$0-9]+|"[a-zA-Z$0-9]+"|'[a-zA-Z$0-9]+')'''
  812. obj = {}
  813. obj_m = re.search(
  814. r'''(?x)
  815. (?<!this\.)%s\s*=\s*{\s*
  816. (?P<fields>(%s\s*:\s*function\s*\(.*?\)\s*{.*?}(?:,\s*)?)*)
  817. }\s*;
  818. ''' % (re.escape(objname), _FUNC_NAME_RE),
  819. self.code)
  820. if not obj_m:
  821. raise self.Exception('Could not find object ' + objname)
  822. fields = obj_m.group('fields')
  823. # Currently, it only supports function definitions
  824. fields_m = re.finditer(
  825. r'''(?x)
  826. (?P<key>%s)\s*:\s*function\s*\((?P<args>(?:%s|,)*)\){(?P<code>[^}]+)}
  827. ''' % (_FUNC_NAME_RE, _NAME_RE),
  828. fields)
  829. for f in fields_m:
  830. argnames = self.build_arglist(f.group('args'))
  831. obj[remove_quotes(f.group('key'))] = self.build_function(argnames, f.group('code'))
  832. return obj
  833. @staticmethod
  834. def _offset_e_by_d(d, e, local_vars):
  835. """ Short-cut eval: (d%e.length+e.length)%e.length """
  836. try:
  837. d = local_vars[d]
  838. e = local_vars[e]
  839. e = len(e)
  840. return _js_mod(_js_mod(d, e) + e, e), False
  841. except Exception:
  842. return None, True
  843. def extract_function_code(self, funcname):
  844. """ @returns argnames, code """
  845. func_m = re.search(
  846. r'''(?xs)
  847. (?:
  848. function\s+%(name)s|
  849. [{;,]\s*%(name)s\s*=\s*function|
  850. (?:var|const|let)\s+%(name)s\s*=\s*function
  851. )\s*
  852. \((?P<args>[^)]*)\)\s*
  853. (?P<code>{.+})''' % {'name': re.escape(funcname)},
  854. self.code)
  855. code, _ = self._separate_at_paren(func_m.group('code')) # refine the match
  856. if func_m is None:
  857. raise self.Exception('Could not find JS function "{funcname}"'.format(**locals()))
  858. return self.build_arglist(func_m.group('args')), code
  859. def extract_function(self, funcname):
  860. return function_with_repr(
  861. self.extract_function_from_code(*self.extract_function_code(funcname)),
  862. 'F<%s>' % (funcname, ))
  863. def extract_function_from_code(self, argnames, code, *global_stack):
  864. local_vars = {}
  865. while True:
  866. mobj = re.search(r'function\((?P<args>[^)]*)\)\s*{', code)
  867. if mobj is None:
  868. break
  869. start, body_start = mobj.span()
  870. body, remaining = self._separate_at_paren(code[body_start - 1:], '}')
  871. name = self._named_object(local_vars, self.extract_function_from_code(
  872. [x.strip() for x in mobj.group('args').split(',')],
  873. body, local_vars, *global_stack))
  874. code = code[:start] + name + remaining
  875. return self.build_function(argnames, code, local_vars, *global_stack)
  876. def call_function(self, funcname, *args):
  877. return self.extract_function(funcname)(args)
  878. @classmethod
  879. def build_arglist(cls, arg_text):
  880. if not arg_text:
  881. return []
  882. def valid_arg(y):
  883. y = y.strip()
  884. if not y:
  885. raise cls.Exception('Missing arg in "%s"' % (arg_text, ))
  886. return y
  887. return [valid_arg(x) for x in cls._separate(arg_text)]
  888. def build_function(self, argnames, code, *global_stack):
  889. global_stack = list(global_stack) or [{}]
  890. argnames = tuple(argnames)
  891. def resf(args, kwargs={}, allow_recursion=100):
  892. global_stack[0].update(
  893. zip_longest(argnames, args, fillvalue=None))
  894. global_stack[0].update(kwargs)
  895. var_stack = LocalNameSpace(*global_stack)
  896. ret, should_abort = self.interpret_statement(code.replace('\n', ' '), var_stack, allow_recursion - 1)
  897. if should_abort:
  898. return ret
  899. return resf