jsinterp.py 44 KB

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