jsinterp.py 37 KB

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