jsinterp.py 43 KB

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