jsinterp.py 44 KB

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