jsinterp.py 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024
  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. inner, outer = self._separate_at_paren(expr)
  415. inner, should_abort = self.interpret_statement(inner, local_vars, allow_recursion)
  416. if not outer or should_abort:
  417. return inner, should_abort or should_return
  418. else:
  419. expr = self._dump(inner, local_vars) + outer
  420. if expr.startswith('['):
  421. inner, outer = self._separate_at_paren(expr)
  422. name = self._named_object(local_vars, [
  423. self.interpret_expression(item, local_vars, allow_recursion)
  424. for item in self._separate(inner)])
  425. expr = name + outer
  426. m = self._COMPOUND_RE.match(expr)
  427. md = m.groupdict() if m else {}
  428. if md.get('if'):
  429. cndn, expr = self._separate_at_paren(expr[m.end() - 1:])
  430. if expr.startswith('{'):
  431. if_expr, expr = self._separate_at_paren(expr)
  432. else:
  433. # may lose ... else ... because of ll.368-374
  434. if_expr, expr = self._separate_at_paren(expr, delim=';')
  435. else_expr = None
  436. m = re.match(r'else\s*(?P<block>\{)?', expr)
  437. if m:
  438. if m.group('block'):
  439. else_expr, expr = self._separate_at_paren(expr[m.end() - 1:])
  440. else:
  441. # handle subset ... else if (...) {...} else ...
  442. # TODO: make interpret_statement do this properly, if possible
  443. exprs = list(self._separate(expr[m.end():], delim='}', max_split=2))
  444. if len(exprs) > 1:
  445. if re.match(r'\s*if\s*\(', exprs[0]) and re.match(r'\s*else\b', exprs[1]):
  446. else_expr = exprs[0] + '}' + exprs[1]
  447. expr = (exprs[2] + '}') if len(exprs) == 3 else None
  448. else:
  449. else_expr = exprs[0]
  450. exprs.append('')
  451. expr = '}'.join(exprs[1:])
  452. else:
  453. else_expr = exprs[0]
  454. expr = None
  455. else_expr = else_expr.lstrip() + '}'
  456. cndn = _js_ternary(self.interpret_expression(cndn, local_vars, allow_recursion))
  457. ret, should_abort = self.interpret_statement(
  458. if_expr if cndn else else_expr, local_vars, allow_recursion)
  459. if should_abort:
  460. return ret, True
  461. elif md.get('try'):
  462. try_expr, expr = self._separate_at_paren(expr[m.end() - 1:])
  463. err = None
  464. try:
  465. ret, should_abort = self.interpret_statement(try_expr, local_vars, allow_recursion)
  466. if should_abort:
  467. return ret, True
  468. except Exception as e:
  469. # XXX: This works for now, but makes debugging future issues very hard
  470. err = e
  471. pending = (None, False)
  472. m = re.match(r'catch\s*(?P<err>\(\s*{_NAME_RE}\s*\))?\{{'.format(**globals()), expr)
  473. if m:
  474. sub_expr, expr = self._separate_at_paren(expr[m.end() - 1:])
  475. if err:
  476. catch_vars = {}
  477. if m.group('err'):
  478. catch_vars[m.group('err')] = err.error if isinstance(err, JS_Throw) else err
  479. catch_vars = local_vars.new_child(m=catch_vars)
  480. err = None
  481. pending = self.interpret_statement(sub_expr, catch_vars, allow_recursion)
  482. m = self._FINALLY_RE.match(expr)
  483. if m:
  484. sub_expr, expr = self._separate_at_paren(expr[m.end() - 1:])
  485. ret, should_abort = self.interpret_statement(sub_expr, local_vars, allow_recursion)
  486. if should_abort:
  487. return ret, True
  488. ret, should_abort = pending
  489. if should_abort:
  490. return ret, True
  491. if err:
  492. raise err
  493. elif md.get('for') or md.get('while'):
  494. init_or_cond, remaining = self._separate_at_paren(expr[m.end() - 1:])
  495. if remaining.startswith('{'):
  496. body, expr = self._separate_at_paren(remaining)
  497. else:
  498. switch_m = self._SWITCH_RE.match(remaining) # FIXME
  499. if switch_m:
  500. switch_val, remaining = self._separate_at_paren(remaining[switch_m.end() - 1:])
  501. body, expr = self._separate_at_paren(remaining, '}')
  502. body = 'switch(%s){%s}' % (switch_val, body)
  503. else:
  504. body, expr = remaining, ''
  505. if md.get('for'):
  506. start, cndn, increment = self._separate(init_or_cond, ';')
  507. self.interpret_expression(start, local_vars, allow_recursion)
  508. else:
  509. cndn, increment = init_or_cond, None
  510. while _js_ternary(self.interpret_expression(cndn, local_vars, allow_recursion)):
  511. try:
  512. ret, should_abort = self.interpret_statement(body, local_vars, allow_recursion)
  513. if should_abort:
  514. return ret, True
  515. except JS_Break:
  516. break
  517. except JS_Continue:
  518. pass
  519. if increment:
  520. self.interpret_expression(increment, local_vars, allow_recursion)
  521. elif md.get('switch'):
  522. switch_val, remaining = self._separate_at_paren(expr[m.end() - 1:])
  523. switch_val = self.interpret_expression(switch_val, local_vars, allow_recursion)
  524. body, expr = self._separate_at_paren(remaining, '}')
  525. items = body.replace('default:', 'case default:').split('case ')[1:]
  526. for default in (False, True):
  527. matched = False
  528. for item in items:
  529. case, stmt = (i.strip() for i in self._separate(item, ':', 1))
  530. if default:
  531. matched = matched or case == 'default'
  532. elif not matched:
  533. matched = (case != 'default'
  534. and switch_val == self.interpret_expression(case, local_vars, allow_recursion))
  535. if not matched:
  536. continue
  537. try:
  538. ret, should_abort = self.interpret_statement(stmt, local_vars, allow_recursion)
  539. if should_abort:
  540. return ret
  541. except JS_Break:
  542. break
  543. if matched:
  544. break
  545. if md:
  546. ret, should_abort = self.interpret_statement(expr, local_vars, allow_recursion)
  547. return ret, should_abort or should_return
  548. # Comma separated statements
  549. sub_expressions = list(self._separate(expr))
  550. if len(sub_expressions) > 1:
  551. for sub_expr in sub_expressions:
  552. ret, should_abort = self.interpret_statement(sub_expr, local_vars, allow_recursion)
  553. if should_abort:
  554. return ret, True
  555. return ret, False
  556. for m in re.finditer(r'''(?x)
  557. (?P<pre_sign>\+\+|--)(?P<var1>{_NAME_RE})|
  558. (?P<var2>{_NAME_RE})(?P<post_sign>\+\+|--)'''.format(**globals()), expr):
  559. var = m.group('var1') or m.group('var2')
  560. start, end = m.span()
  561. sign = m.group('pre_sign') or m.group('post_sign')
  562. ret = local_vars[var]
  563. local_vars[var] += 1 if sign[0] == '+' else -1
  564. if m.group('pre_sign'):
  565. ret = local_vars[var]
  566. expr = expr[:start] + self._dump(ret, local_vars) + expr[end:]
  567. if not expr:
  568. return None, should_return
  569. m = re.match(r'''(?x)
  570. (?P<assign>
  571. (?P<out>{_NAME_RE})(?:\[(?P<index>[^\]]+?)\])?\s*
  572. (?P<op>{_OPERATOR_RE})?
  573. =(?!=)(?P<expr>.*)$
  574. )|(?P<return>
  575. (?!if|return|true|false|null|undefined)(?P<name>{_NAME_RE})$
  576. )|(?P<indexing>
  577. (?P<in>{_NAME_RE})\[(?P<idx>.+)\]$
  578. )|(?P<attribute>
  579. (?P<var>{_NAME_RE})(?:(?P<nullish>\?)?\.(?P<member>[^(]+)|\[(?P<member2>[^\]]+)\])\s*
  580. )|(?P<function>
  581. (?P<fname>{_NAME_RE})\((?P<args>.*)\)$
  582. )'''.format(**globals()), expr)
  583. md = m.groupdict() if m else {}
  584. if md.get('assign'):
  585. left_val = local_vars.get(m.group('out'))
  586. if not m.group('index'):
  587. local_vars[m.group('out')] = self._operator(
  588. m.group('op'), left_val, m.group('expr'), expr, local_vars, allow_recursion)
  589. return local_vars[m.group('out')], should_return
  590. elif left_val in (None, JS_Undefined):
  591. raise self.Exception('Cannot index undefined variable ' + m.group('out'), expr=expr)
  592. idx = self.interpret_expression(m.group('index'), local_vars, allow_recursion)
  593. if not isinstance(idx, (int, float)):
  594. raise self.Exception('List index %s must be integer' % (idx, ), expr=expr)
  595. idx = int(idx)
  596. left_val[idx] = self._operator(
  597. m.group('op'), self._index(left_val, idx), m.group('expr'), expr, local_vars, allow_recursion)
  598. return left_val[idx], should_return
  599. elif expr.isdigit():
  600. return int(expr), should_return
  601. elif expr == 'break':
  602. raise JS_Break()
  603. elif expr == 'continue':
  604. raise JS_Continue()
  605. elif expr == 'undefined':
  606. return JS_Undefined, should_return
  607. elif expr == 'NaN':
  608. return _NaN, should_return
  609. elif md.get('return'):
  610. return local_vars[m.group('name')], should_return
  611. try:
  612. ret = json.loads(js_to_json(expr)) # strict=True)
  613. if not md.get('attribute'):
  614. return ret, should_return
  615. except ValueError:
  616. pass
  617. if md.get('indexing'):
  618. val = local_vars[m.group('in')]
  619. idx = self.interpret_expression(m.group('idx'), local_vars, allow_recursion)
  620. return self._index(val, idx), should_return
  621. for op, _ in self._all_operators():
  622. # hackety: </> have higher priority than <</>>, but don't confuse them
  623. skip_delim = (op + op) if op in '<>*?' else None
  624. if op == '?':
  625. skip_delim = (skip_delim, '?.')
  626. separated = list(self._separate(expr, op, skip_delims=skip_delim))
  627. if len(separated) < 2:
  628. continue
  629. right_expr = separated.pop()
  630. # handle operators that are both unary and binary, minimal BODMAS
  631. if op in ('+', '-'):
  632. undone = 0
  633. while len(separated) > 1 and not separated[-1].strip():
  634. undone += 1
  635. separated.pop()
  636. if op == '-' and undone % 2 != 0:
  637. right_expr = op + right_expr
  638. left_val = separated[-1]
  639. for dm_op in ('*', '%', '/', '**'):
  640. bodmas = tuple(self._separate(left_val, dm_op, skip_delims=skip_delim))
  641. if len(bodmas) > 1 and not bodmas[-1].strip():
  642. expr = op.join(separated) + op + right_expr
  643. right_expr = None
  644. break
  645. if right_expr is None:
  646. continue
  647. left_val = self.interpret_expression(op.join(separated), local_vars, allow_recursion)
  648. return self._operator(op, left_val, right_expr, expr, local_vars, allow_recursion), should_return
  649. if md.get('attribute'):
  650. variable, member, nullish = m.group('var', 'member', 'nullish')
  651. if not member:
  652. member = self.interpret_expression(m.group('member2'), local_vars, allow_recursion)
  653. arg_str = expr[m.end():]
  654. if arg_str.startswith('('):
  655. arg_str, remaining = self._separate_at_paren(arg_str)
  656. else:
  657. arg_str, remaining = None, arg_str
  658. def assertion(cndn, msg):
  659. """ assert, but without risk of getting optimized out """
  660. if not cndn:
  661. memb = member
  662. raise self.Exception('{memb} {msg}'.format(**locals()), expr=expr)
  663. def eval_method():
  664. if (variable, member) == ('console', 'debug'):
  665. return
  666. types = {
  667. 'String': compat_str,
  668. 'Math': float,
  669. }
  670. obj = local_vars.get(variable)
  671. if obj in (JS_Undefined, None):
  672. obj = types.get(variable, JS_Undefined)
  673. if obj is JS_Undefined:
  674. try:
  675. if variable not in self._objects:
  676. self._objects[variable] = self.extract_object(variable)
  677. obj = self._objects[variable]
  678. except self.Exception:
  679. if not nullish:
  680. raise
  681. if nullish and obj is JS_Undefined:
  682. return JS_Undefined
  683. # Member access
  684. if arg_str is None:
  685. return self._index(obj, member, nullish)
  686. # Function call
  687. argvals = [
  688. self.interpret_expression(v, local_vars, allow_recursion)
  689. for v in self._separate(arg_str)]
  690. if obj == compat_str:
  691. if member == 'fromCharCode':
  692. assertion(argvals, 'takes one or more arguments')
  693. return ''.join(map(compat_chr, argvals))
  694. raise self.Exception('Unsupported string method ' + member, expr=expr)
  695. elif obj == float:
  696. if member == 'pow':
  697. assertion(len(argvals) == 2, 'takes two arguments')
  698. return argvals[0] ** argvals[1]
  699. raise self.Exception('Unsupported Math method ' + member, expr=expr)
  700. if member == 'split':
  701. assertion(argvals, 'takes one or more arguments')
  702. assertion(len(argvals) == 1, 'with limit argument is not implemented')
  703. return obj.split(argvals[0]) if argvals[0] else list(obj)
  704. elif member == 'join':
  705. assertion(isinstance(obj, list), 'must be applied on a list')
  706. assertion(len(argvals) == 1, 'takes exactly one argument')
  707. return argvals[0].join(obj)
  708. elif member == 'reverse':
  709. assertion(not argvals, 'does not take any arguments')
  710. obj.reverse()
  711. return obj
  712. elif member == 'slice':
  713. assertion(isinstance(obj, list), 'must be applied on a list')
  714. assertion(len(argvals) == 1, 'takes exactly one argument')
  715. return obj[argvals[0]:]
  716. elif member == 'splice':
  717. assertion(isinstance(obj, list), 'must be applied on a list')
  718. assertion(argvals, 'takes one or more arguments')
  719. index, howMany = map(int, (argvals + [len(obj)])[:2])
  720. if index < 0:
  721. index += len(obj)
  722. add_items = argvals[2:]
  723. res = []
  724. for i in range(index, min(index + howMany, len(obj))):
  725. res.append(obj.pop(index))
  726. for i, item in enumerate(add_items):
  727. obj.insert(index + i, item)
  728. return res
  729. elif member == 'unshift':
  730. assertion(isinstance(obj, list), 'must be applied on a list')
  731. assertion(argvals, 'takes one or more arguments')
  732. for item in reversed(argvals):
  733. obj.insert(0, item)
  734. return obj
  735. elif member == 'pop':
  736. assertion(isinstance(obj, list), 'must be applied on a list')
  737. assertion(not argvals, 'does not take any arguments')
  738. if not obj:
  739. return
  740. return obj.pop()
  741. elif member == 'push':
  742. assertion(argvals, 'takes one or more arguments')
  743. obj.extend(argvals)
  744. return obj
  745. elif member == 'forEach':
  746. assertion(argvals, 'takes one or more arguments')
  747. assertion(len(argvals) <= 2, 'takes at-most 2 arguments')
  748. f, this = (argvals + [''])[:2]
  749. return [f((item, idx, obj), {'this': this}, allow_recursion) for idx, item in enumerate(obj)]
  750. elif member == 'indexOf':
  751. assertion(argvals, 'takes one or more arguments')
  752. assertion(len(argvals) <= 2, 'takes at-most 2 arguments')
  753. idx, start = (argvals + [0])[:2]
  754. try:
  755. return obj.index(idx, start)
  756. except ValueError:
  757. return -1
  758. elif member == 'charCodeAt':
  759. assertion(isinstance(obj, compat_str), 'must be applied on a string')
  760. # assertion(len(argvals) == 1, 'takes exactly one argument') # but not enforced
  761. idx = argvals[0] if isinstance(argvals[0], int) else 0
  762. if idx >= len(obj):
  763. return None
  764. return ord(obj[idx])
  765. elif member in ('replace', 'replaceAll'):
  766. assertion(isinstance(obj, compat_str), 'must be applied on a string')
  767. assertion(len(argvals) == 2, 'takes exactly two arguments')
  768. # TODO: argvals[1] callable, other Py vs JS edge cases
  769. if isinstance(argvals[0], self.JS_RegExp):
  770. count = 0 if argvals[0].flags & self.JS_RegExp.RE_FLAGS['g'] else 1
  771. assertion(member != 'replaceAll' or count == 0,
  772. 'replaceAll must be called with a global RegExp')
  773. return argvals[0].sub(argvals[1], obj, count=count)
  774. count = ('replaceAll', 'replace').index(member)
  775. return re.sub(re.escape(argvals[0]), argvals[1], obj, count=count)
  776. idx = int(member) if isinstance(obj, list) else member
  777. return obj[idx](argvals, allow_recursion=allow_recursion)
  778. if remaining:
  779. ret, should_abort = self.interpret_statement(
  780. self._named_object(local_vars, eval_method()) + remaining,
  781. local_vars, allow_recursion)
  782. return ret, should_return or should_abort
  783. else:
  784. return eval_method(), should_return
  785. elif md.get('function'):
  786. fname = m.group('fname')
  787. argvals = [self.interpret_expression(v, local_vars, allow_recursion)
  788. for v in self._separate(m.group('args'))]
  789. if fname in local_vars:
  790. return local_vars[fname](argvals, allow_recursion=allow_recursion), should_return
  791. elif fname not in self._functions:
  792. self._functions[fname] = self.extract_function(fname)
  793. return self._functions[fname](argvals, allow_recursion=allow_recursion), should_return
  794. raise self.Exception(
  795. 'Unsupported JS expression ' + (expr[:40] if expr != stmt else ''), expr=stmt)
  796. def interpret_expression(self, expr, local_vars, allow_recursion):
  797. ret, should_return = self.interpret_statement(expr, local_vars, allow_recursion)
  798. if should_return:
  799. raise self.Exception('Cannot return from an expression', expr)
  800. return ret
  801. def interpret_iter(self, list_txt, local_vars, allow_recursion):
  802. for v in self._separate(list_txt):
  803. yield self.interpret_expression(v, local_vars, allow_recursion)
  804. def extract_object(self, objname):
  805. _FUNC_NAME_RE = r'''(?:[a-zA-Z$0-9]+|"[a-zA-Z$0-9]+"|'[a-zA-Z$0-9]+')'''
  806. obj = {}
  807. obj_m = re.search(
  808. r'''(?x)
  809. (?<!this\.)%s\s*=\s*{\s*
  810. (?P<fields>(%s\s*:\s*function\s*\(.*?\)\s*{.*?}(?:,\s*)?)*)
  811. }\s*;
  812. ''' % (re.escape(objname), _FUNC_NAME_RE),
  813. self.code)
  814. if not obj_m:
  815. raise self.Exception('Could not find object ' + objname)
  816. fields = obj_m.group('fields')
  817. # Currently, it only supports function definitions
  818. fields_m = re.finditer(
  819. r'''(?x)
  820. (?P<key>%s)\s*:\s*function\s*\((?P<args>(?:%s|,)*)\){(?P<code>[^}]+)}
  821. ''' % (_FUNC_NAME_RE, _NAME_RE),
  822. fields)
  823. for f in fields_m:
  824. argnames = self.build_arglist(f.group('args'))
  825. obj[remove_quotes(f.group('key'))] = self.build_function(argnames, f.group('code'))
  826. return obj
  827. def extract_function_code(self, funcname):
  828. """ @returns argnames, code """
  829. func_m = re.search(
  830. r'''(?xs)
  831. (?:
  832. function\s+%(name)s|
  833. [{;,]\s*%(name)s\s*=\s*function|
  834. (?:var|const|let)\s+%(name)s\s*=\s*function
  835. )\s*
  836. \((?P<args>[^)]*)\)\s*
  837. (?P<code>{.+})''' % {'name': re.escape(funcname)},
  838. self.code)
  839. code, _ = self._separate_at_paren(func_m.group('code')) # refine the match
  840. if func_m is None:
  841. raise self.Exception('Could not find JS function "{funcname}"'.format(**locals()))
  842. return self.build_arglist(func_m.group('args')), code
  843. def extract_function(self, funcname):
  844. return function_with_repr(
  845. self.extract_function_from_code(*self.extract_function_code(funcname)),
  846. 'F<%s>' % (funcname, ))
  847. def extract_function_from_code(self, argnames, code, *global_stack):
  848. local_vars = {}
  849. while True:
  850. mobj = re.search(r'function\((?P<args>[^)]*)\)\s*{', code)
  851. if mobj is None:
  852. break
  853. start, body_start = mobj.span()
  854. body, remaining = self._separate_at_paren(code[body_start - 1:], '}')
  855. name = self._named_object(local_vars, self.extract_function_from_code(
  856. [x.strip() for x in mobj.group('args').split(',')],
  857. body, local_vars, *global_stack))
  858. code = code[:start] + name + remaining
  859. return self.build_function(argnames, code, local_vars, *global_stack)
  860. def call_function(self, funcname, *args):
  861. return self.extract_function(funcname)(args)
  862. @classmethod
  863. def build_arglist(cls, arg_text):
  864. if not arg_text:
  865. return []
  866. def valid_arg(y):
  867. y = y.strip()
  868. if not y:
  869. raise cls.Exception('Missing arg in "%s"' % (arg_text, ))
  870. return y
  871. return [valid_arg(x) for x in cls._separate(arg_text)]
  872. def build_function(self, argnames, code, *global_stack):
  873. global_stack = list(global_stack) or [{}]
  874. argnames = tuple(argnames)
  875. def resf(args, kwargs={}, allow_recursion=100):
  876. global_stack[0].update(
  877. zip_longest(argnames, args, fillvalue=None))
  878. global_stack[0].update(kwargs)
  879. var_stack = LocalNameSpace(*global_stack)
  880. ret, should_abort = self.interpret_statement(code.replace('\n', ' '), var_stack, allow_recursion - 1)
  881. if should_abort:
  882. return ret
  883. return resf