jsinterp.py 38 KB

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