jsinterp.py 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786
  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. ExtractorError,
  9. js_to_json,
  10. remove_quotes,
  11. unified_timestamp,
  12. )
  13. from .compat import (
  14. compat_collections_chain_map as ChainMap,
  15. compat_itertools_zip_longest as zip_longest,
  16. compat_str,
  17. )
  18. _NAME_RE = r'[a-zA-Z_$][\w$]*'
  19. _UNDEFINED = object()
  20. def _js_bit_op(op):
  21. def wrapped(a, b):
  22. def zeroise(x):
  23. return 0 if x in (None, _UNDEFINED) else x
  24. return op(zeroise(a), zeroise(b))
  25. return wrapped
  26. def _js_arith_op(op):
  27. def wrapped(a, b):
  28. if _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 _UNDEFINED in (a, b) or not (a and b):
  34. return float('nan')
  35. return float('inf') if not b else operator.truediv(a or 0, b)
  36. def _js_mod(a, b):
  37. if _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. # even 0 ** 0 !!
  43. return 1
  44. if _UNDEFINED in (a, b):
  45. return float('nan')
  46. return (a or 0) ** b
  47. def _js_eq_op(op):
  48. def wrapped(a, b):
  49. if set((a, b)) <= set((None, _UNDEFINED)):
  50. return op(a, a)
  51. return op(a, b)
  52. return wrapped
  53. def _js_comp_op(op):
  54. def wrapped(a, b):
  55. if _UNDEFINED in (a, b):
  56. return False
  57. return op(a or 0, b or 0)
  58. return wrapped
  59. # (op, definition) in order of binding priority, tightest first
  60. # avoid dict to maintain order
  61. # definition None => Defined in JSInterpreter._operator
  62. _DOT_OPERATORS = (
  63. ('.', None),
  64. # TODO: ('?.', None),
  65. )
  66. _OPERATORS = (
  67. ('>>', _js_bit_op(operator.rshift)),
  68. ('<<', _js_bit_op(operator.lshift)),
  69. ('+', _js_arith_op(operator.add)),
  70. ('-', _js_arith_op(operator.sub)),
  71. ('*', _js_arith_op(operator.mul)),
  72. ('/', _js_div),
  73. ('%', _js_mod),
  74. ('**', _js_exp),
  75. )
  76. _COMP_OPERATORS = (
  77. ('===', operator.is_),
  78. ('==', _js_eq_op(operator.eq)),
  79. ('!==', operator.is_not),
  80. ('!=', _js_eq_op(operator.ne)),
  81. ('<=', _js_comp_op(operator.le)),
  82. ('>=', _js_comp_op(operator.ge)),
  83. ('<', _js_comp_op(operator.lt)),
  84. ('>', _js_comp_op(operator.gt)),
  85. )
  86. _LOG_OPERATORS = (
  87. ('|', _js_bit_op(operator.or_)),
  88. ('^', _js_bit_op(operator.xor)),
  89. ('&', _js_bit_op(operator.and_)),
  90. )
  91. _SC_OPERATORS = (
  92. ('?', None),
  93. ('??', None),
  94. ('||', None),
  95. ('&&', None),
  96. )
  97. _OPERATOR_RE = '|'.join(map(lambda x: re.escape(x[0]), _OPERATORS + _LOG_OPERATORS))
  98. _MATCHING_PARENS = dict(zip(*zip('()', '{}', '[]')))
  99. _QUOTES = '\'"'
  100. def _ternary(cndn, if_true=True, if_false=False):
  101. """Simulate JS's ternary operator (cndn?if_true:if_false)"""
  102. if cndn in (False, None, 0, '', _UNDEFINED):
  103. return if_false
  104. try:
  105. if math.isnan(cndn): # NB: NaN cannot be checked by membership
  106. return if_false
  107. except TypeError:
  108. pass
  109. return if_true
  110. class JS_Break(ExtractorError):
  111. def __init__(self):
  112. ExtractorError.__init__(self, 'Invalid break')
  113. class JS_Continue(ExtractorError):
  114. def __init__(self):
  115. ExtractorError.__init__(self, 'Invalid continue')
  116. class LocalNameSpace(ChainMap):
  117. def __getitem__(self, key):
  118. try:
  119. return super(LocalNameSpace, self).__getitem__(key)
  120. except KeyError:
  121. return _UNDEFINED
  122. def __setitem__(self, key, value):
  123. for scope in self.maps:
  124. if key in scope:
  125. scope[key] = value
  126. return
  127. self.maps[0][key] = value
  128. def __delitem__(self, key):
  129. raise NotImplementedError('Deleting is not supported')
  130. def __contains__(self, key):
  131. try:
  132. super(LocalNameSpace, self).__getitem__(key)
  133. return True
  134. except KeyError:
  135. return False
  136. def __repr__(self):
  137. return 'LocalNameSpace%s' % (self.maps, )
  138. class JSInterpreter(object):
  139. __named_object_counter = 0
  140. undefined = _UNDEFINED
  141. def __init__(self, code, objects=None):
  142. self.code, self._functions = code, {}
  143. self._objects = {} if objects is None else objects
  144. class Exception(ExtractorError):
  145. def __init__(self, msg, *args, **kwargs):
  146. expr = kwargs.pop('expr', None)
  147. if expr is not None:
  148. msg = '{0} in: {1!r}'.format(msg.rstrip(), expr[:100])
  149. super(JSInterpreter.Exception, self).__init__(msg, *args, **kwargs)
  150. def _named_object(self, namespace, obj):
  151. self.__named_object_counter += 1
  152. name = '__youtube_dl_jsinterp_obj%d' % (self.__named_object_counter, )
  153. namespace[name] = obj
  154. return name
  155. @staticmethod
  156. def _separate(expr, delim=',', max_split=None, skip_delims=None):
  157. if not expr:
  158. return
  159. counters = {k: 0 for k in _MATCHING_PARENS.values()}
  160. start, splits, pos, skipping, delim_len = 0, 0, 0, 0, len(delim) - 1
  161. in_quote, escaping = None, False
  162. for idx, char in enumerate(expr):
  163. if not in_quote:
  164. if char in _MATCHING_PARENS:
  165. counters[_MATCHING_PARENS[char]] += 1
  166. elif char in counters:
  167. counters[char] -= 1
  168. if not escaping:
  169. if char in _QUOTES and in_quote in (char, None):
  170. in_quote = None if in_quote else char
  171. else:
  172. escaping = in_quote and char == '\\'
  173. else:
  174. escaping = False
  175. if char != delim[pos] or any(counters.values()) or in_quote:
  176. pos = skipping = 0
  177. continue
  178. elif skipping > 0:
  179. skipping -= 1
  180. continue
  181. elif pos == 0 and skip_delims:
  182. here = expr[idx:]
  183. for s in skip_delims if isinstance(skip_delims, (list, tuple)) else [skip_delims]:
  184. if here.startswith(s) and s:
  185. skipping = len(s) - 1
  186. break
  187. if skipping > 0:
  188. continue
  189. if pos < delim_len:
  190. pos += 1
  191. continue
  192. yield expr[start: idx - delim_len]
  193. start, pos = idx + 1, 0
  194. splits += 1
  195. if max_split and splits >= max_split:
  196. break
  197. yield expr[start:]
  198. @classmethod
  199. def _separate_at_paren(cls, expr, delim):
  200. separated = list(cls._separate(expr, delim, 1))
  201. if len(separated) < 2:
  202. raise cls.Exception('No terminating paren {delim} in {expr}'.format(**locals()))
  203. return separated[0][1:].strip(), separated[1].strip()
  204. @staticmethod
  205. def _all_operators():
  206. return itertools.chain(
  207. # Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
  208. _SC_OPERATORS, _LOG_OPERATORS, _COMP_OPERATORS, _OPERATORS)
  209. def _operator(self, op, left_val, right_expr, expr, local_vars, allow_recursion):
  210. if op in ('||', '&&'):
  211. if (op == '&&') ^ _ternary(left_val):
  212. return left_val # short circuiting
  213. elif op == '??':
  214. if left_val not in (None, self.undefined):
  215. return left_val
  216. elif op == '?':
  217. right_expr = _ternary(left_val, *self._separate(right_expr, ':', 1))
  218. right_val = self.interpret_expression(right_expr, local_vars, allow_recursion)
  219. opfunc = op and next((v for k, v in self._all_operators() if k == op), None)
  220. if not opfunc:
  221. return right_val
  222. try:
  223. return opfunc(left_val, right_val)
  224. except Exception as e:
  225. raise self.Exception('Failed to evaluate {left_val!r} {op} {right_val!r}'.format(**locals()), expr, cause=e)
  226. def _index(self, obj, idx, allow_undefined=False):
  227. if idx == 'length':
  228. return len(obj)
  229. try:
  230. return obj[int(idx)] if isinstance(obj, list) else obj[idx]
  231. except Exception as e:
  232. if allow_undefined:
  233. return self.undefined
  234. raise self.Exception('Cannot get index {idx}'.format(**locals()), expr=repr(obj), cause=e)
  235. def _dump(self, obj, namespace):
  236. try:
  237. return json.dumps(obj)
  238. except TypeError:
  239. return self._named_object(namespace, obj)
  240. def interpret_statement(self, stmt, local_vars, allow_recursion=100):
  241. if allow_recursion < 0:
  242. raise self.Exception('Recursion limit reached')
  243. allow_recursion -= 1
  244. should_return = False
  245. sub_statements = list(self._separate(stmt, ';')) or ['']
  246. expr = stmt = sub_statements.pop().strip()
  247. for sub_stmt in sub_statements:
  248. ret, should_return = self.interpret_statement(sub_stmt, local_vars, allow_recursion)
  249. if should_return:
  250. return ret, should_return
  251. m = re.match(r'(?P<var>(?:var|const|let)\s)|return(?:\s+|$)', stmt)
  252. if m:
  253. expr = stmt[len(m.group(0)):].strip()
  254. should_return = not m.group('var')
  255. if not expr:
  256. return None, should_return
  257. if expr[0] in _QUOTES:
  258. inner, outer = self._separate(expr, expr[0], 1)
  259. inner = json.loads(js_to_json(inner + expr[0])) # , strict=True))
  260. if not outer:
  261. return inner, should_return
  262. expr = self._named_object(local_vars, inner) + outer
  263. if expr.startswith('new '):
  264. obj = expr[4:]
  265. if obj.startswith('Date('):
  266. left, right = self._separate_at_paren(obj[4:], ')')
  267. expr = unified_timestamp(
  268. self.interpret_expression(left, local_vars, allow_recursion), False)
  269. if not expr:
  270. raise self.Exception('Failed to parse date {left!r}'.format(**locals()), expr=expr)
  271. expr = self._dump(int(expr * 1000), local_vars) + right
  272. else:
  273. raise self.Exception('Unsupported object {obj}'.format(**locals()), expr=expr)
  274. if expr.startswith('void '):
  275. left = self.interpret_expression(expr[5:], local_vars, allow_recursion)
  276. return None, should_return
  277. if expr.startswith('{'):
  278. inner, outer = self._separate_at_paren(expr, '}')
  279. # try for object expression
  280. sub_expressions = [list(self._separate(sub_expr.strip(), ':', 1)) for sub_expr in self._separate(inner)]
  281. if all(len(sub_expr) == 2 for sub_expr in sub_expressions):
  282. return dict(
  283. (key_expr if re.match(_NAME_RE, key_expr) else key_expr,
  284. self.interpret_expression(val_expr, local_vars, allow_recursion))
  285. for key_expr, val_expr in sub_expressions), should_return
  286. # or statement list
  287. inner, should_abort = self.interpret_statement(inner, local_vars, allow_recursion)
  288. if not outer or should_abort:
  289. return inner, should_abort or should_return
  290. else:
  291. expr = self._dump(inner, local_vars) + outer
  292. if expr.startswith('('):
  293. inner, outer = self._separate_at_paren(expr, ')')
  294. inner, should_abort = self.interpret_statement(inner, local_vars, allow_recursion)
  295. if not outer or should_abort:
  296. return inner, should_abort or should_return
  297. else:
  298. expr = self._dump(inner, local_vars) + outer
  299. if expr.startswith('['):
  300. inner, outer = self._separate_at_paren(expr, ']')
  301. name = self._named_object(local_vars, [
  302. self.interpret_expression(item, local_vars, allow_recursion)
  303. for item in self._separate(inner)])
  304. expr = name + outer
  305. m = re.match(r'(?P<try>try|finally)\s*|(?:(?P<catch>catch)|(?P<for>for)|(?P<switch>switch))\s*\(', expr)
  306. md = m.groupdict() if m else {}
  307. if md.get('try'):
  308. if expr[m.end()] == '{':
  309. try_expr, expr = self._separate_at_paren(expr[m.end():], '}')
  310. else:
  311. try_expr, expr = expr[m.end() - 1:], ''
  312. ret, should_abort = self.interpret_statement(try_expr, local_vars, allow_recursion)
  313. if should_abort:
  314. return ret, True
  315. ret, should_abort = self.interpret_statement(expr, local_vars, allow_recursion)
  316. return ret, should_abort or should_return
  317. elif md.get('catch'):
  318. # We ignore the catch block
  319. _, expr = self._separate_at_paren(expr, '}')
  320. ret, should_abort = self.interpret_statement(expr, local_vars, allow_recursion)
  321. return ret, should_abort or should_return
  322. elif md.get('for'):
  323. constructor, remaining = self._separate_at_paren(expr[m.end() - 1:], ')')
  324. if remaining.startswith('{'):
  325. body, expr = self._separate_at_paren(remaining, '}')
  326. else:
  327. switch_m = re.match(r'switch\s*\(', remaining) # FIXME
  328. if switch_m:
  329. switch_val, remaining = self._separate_at_paren(remaining[switch_m.end() - 1:], ')')
  330. body, expr = self._separate_at_paren(remaining, '}')
  331. body = 'switch(%s){%s}' % (switch_val, body)
  332. else:
  333. body, expr = remaining, ''
  334. start, cndn, increment = self._separate(constructor, ';')
  335. self.interpret_expression(start, local_vars, allow_recursion)
  336. while True:
  337. if not _ternary(self.interpret_expression(cndn, local_vars, allow_recursion)):
  338. break
  339. try:
  340. ret, should_abort = self.interpret_statement(body, local_vars, allow_recursion)
  341. if should_abort:
  342. return ret, True
  343. except JS_Break:
  344. break
  345. except JS_Continue:
  346. pass
  347. self.interpret_expression(increment, local_vars, allow_recursion)
  348. ret, should_abort = self.interpret_statement(expr, local_vars, allow_recursion)
  349. return ret, should_abort or should_return
  350. elif md.get('switch'):
  351. switch_val, remaining = self._separate_at_paren(expr[m.end() - 1:], ')')
  352. switch_val = self.interpret_expression(switch_val, local_vars, allow_recursion)
  353. body, expr = self._separate_at_paren(remaining, '}')
  354. items = body.replace('default:', 'case default:').split('case ')[1:]
  355. for default in (False, True):
  356. matched = False
  357. for item in items:
  358. case, stmt = (i.strip() for i in self._separate(item, ':', 1))
  359. if default:
  360. matched = matched or case == 'default'
  361. elif not matched:
  362. matched = (case != 'default'
  363. and switch_val == self.interpret_expression(case, local_vars, allow_recursion))
  364. if not matched:
  365. continue
  366. try:
  367. ret, should_abort = self.interpret_statement(stmt, local_vars, allow_recursion)
  368. if should_abort:
  369. return ret
  370. except JS_Break:
  371. break
  372. if matched:
  373. break
  374. ret, should_abort = self.interpret_statement(expr, local_vars, allow_recursion)
  375. return ret, should_abort or should_return
  376. # Comma separated statements
  377. sub_expressions = list(self._separate(expr))
  378. if len(sub_expressions) > 1:
  379. for sub_expr in sub_expressions:
  380. ret, should_abort = self.interpret_statement(sub_expr, local_vars, allow_recursion)
  381. if should_abort:
  382. return ret, True
  383. return ret, False
  384. for m in re.finditer(r'''(?x)
  385. (?P<pre_sign>\+\+|--)(?P<var1>{_NAME_RE})|
  386. (?P<var2>{_NAME_RE})(?P<post_sign>\+\+|--)'''.format(**globals()), expr):
  387. var = m.group('var1') or m.group('var2')
  388. start, end = m.span()
  389. sign = m.group('pre_sign') or m.group('post_sign')
  390. ret = local_vars[var]
  391. local_vars[var] += 1 if sign[0] == '+' else -1
  392. if m.group('pre_sign'):
  393. ret = local_vars[var]
  394. expr = expr[:start] + self._dump(ret, local_vars) + expr[end:]
  395. if not expr:
  396. return None, should_return
  397. m = re.match(r'''(?x)
  398. (?P<assign>
  399. (?P<out>{_NAME_RE})(?:\[(?P<index>[^\]]+?)\])?\s*
  400. (?P<op>{_OPERATOR_RE})?
  401. =(?!=)(?P<expr>.*)$
  402. )|(?P<return>
  403. (?!if|return|true|false|null|undefined)(?P<name>{_NAME_RE})$
  404. )|(?P<indexing>
  405. (?P<in>{_NAME_RE})\[(?P<idx>.+)\]$
  406. )|(?P<attribute>
  407. (?P<var>{_NAME_RE})(?:(?P<nullish>\?)?\.(?P<member>[^(]+)|\[(?P<member2>[^\]]+)\])\s*
  408. )|(?P<function>
  409. (?P<fname>{_NAME_RE})\((?P<args>.*)\)$
  410. )'''.format(**globals()), expr)
  411. md = m.groupdict() if m else {}
  412. if md.get('assign'):
  413. left_val = local_vars.get(m.group('out'))
  414. if not m.group('index'):
  415. local_vars[m.group('out')] = self._operator(
  416. m.group('op'), left_val, m.group('expr'), expr, local_vars, allow_recursion)
  417. return local_vars[m.group('out')], should_return
  418. elif left_val in (None, self.undefined):
  419. raise self.Exception('Cannot index undefined variable ' + m.group('out'), expr=expr)
  420. idx = self.interpret_expression(m.group('index'), local_vars, allow_recursion)
  421. if not isinstance(idx, (int, float)):
  422. raise self.Exception('List index %s must be integer' % (idx, ), expr=expr)
  423. idx = int(idx)
  424. left_val[idx] = self._operator(
  425. m.group('op'), left_val[idx], m.group('expr'), expr, local_vars, allow_recursion)
  426. return left_val[idx], should_return
  427. elif expr.isdigit():
  428. return int(expr), should_return
  429. elif expr == 'break':
  430. raise JS_Break()
  431. elif expr == 'continue':
  432. raise JS_Continue()
  433. elif expr == 'undefined':
  434. return self.undefined, should_return
  435. elif md.get('return'):
  436. return local_vars[m.group('name')], should_return
  437. try:
  438. ret = json.loads(js_to_json(expr)) # strict=True)
  439. if not md.get('attribute'):
  440. return ret, should_return
  441. except ValueError:
  442. pass
  443. if md.get('indexing'):
  444. val = local_vars[m.group('in')]
  445. idx = self.interpret_expression(m.group('idx'), local_vars, allow_recursion)
  446. return self._index(val, idx), should_return
  447. for op, _ in self._all_operators():
  448. # hackety: </> have higher priority than <</>>, but don't confuse them
  449. skip_delim = (op + op) if op in '<>*?' else None
  450. if op == '?':
  451. skip_delim = (skip_delim, '?.')
  452. separated = list(self._separate(expr, op, skip_delims=skip_delim))
  453. if len(separated) < 2:
  454. continue
  455. right_expr = separated.pop()
  456. while op == '-' and len(separated) > 1 and not separated[-1].strip():
  457. right_expr = '-' + right_expr
  458. separated.pop()
  459. left_val = self.interpret_expression(op.join(separated), local_vars, allow_recursion)
  460. return self._operator(op, left_val, right_expr, expr, local_vars, allow_recursion), should_return
  461. if md.get('attribute'):
  462. variable, member, nullish = m.group('var', 'member', 'nullish')
  463. if not member:
  464. member = self.interpret_expression(m.group('member2'), local_vars, allow_recursion)
  465. arg_str = expr[m.end():]
  466. if arg_str.startswith('('):
  467. arg_str, remaining = self._separate_at_paren(arg_str, ')')
  468. else:
  469. arg_str, remaining = None, arg_str
  470. def assertion(cndn, msg):
  471. """ assert, but without risk of getting optimized out """
  472. if not cndn:
  473. raise ExtractorError('{member} {msg}'.format(**locals()), expr=expr)
  474. def eval_method():
  475. if (variable, member) == ('console', 'debug'):
  476. return
  477. types = {
  478. 'String': compat_str,
  479. 'Math': float,
  480. }
  481. obj = local_vars.get(variable)
  482. if obj in (self.undefined, None):
  483. obj = types.get(variable, self.undefined)
  484. if obj is self.undefined:
  485. try:
  486. if variable not in self._objects:
  487. self._objects[variable] = self.extract_object(variable)
  488. obj = self._objects[variable]
  489. except self.Exception:
  490. if not nullish:
  491. raise
  492. if nullish and obj is self.undefined:
  493. return self.undefined
  494. # Member access
  495. if arg_str is None:
  496. return self._index(obj, member, nullish)
  497. # Function call
  498. argvals = [
  499. self.interpret_expression(v, local_vars, allow_recursion)
  500. for v in self._separate(arg_str)]
  501. if obj == compat_str:
  502. if member == 'fromCharCode':
  503. assertion(argvals, 'takes one or more arguments')
  504. return ''.join(map(chr, argvals))
  505. raise self.Exception('Unsupported string method ' + member, expr=expr)
  506. elif obj == float:
  507. if member == 'pow':
  508. assertion(len(argvals) == 2, 'takes two arguments')
  509. return argvals[0] ** argvals[1]
  510. raise self.Exception('Unsupported Math method ' + member, expr=expr)
  511. if member == 'split':
  512. assertion(argvals, 'takes one or more arguments')
  513. assertion(len(argvals) == 1, 'with limit argument is not implemented')
  514. return obj.split(argvals[0]) if argvals[0] else list(obj)
  515. elif member == 'join':
  516. assertion(isinstance(obj, list), 'must be applied on a list')
  517. assertion(len(argvals) == 1, 'takes exactly one argument')
  518. return argvals[0].join(obj)
  519. elif member == 'reverse':
  520. assertion(not argvals, 'does not take any arguments')
  521. obj.reverse()
  522. return obj
  523. elif member == 'slice':
  524. assertion(isinstance(obj, list), 'must be applied on a list')
  525. assertion(len(argvals) == 1, 'takes exactly one argument')
  526. return obj[argvals[0]:]
  527. elif member == 'splice':
  528. assertion(isinstance(obj, list), 'must be applied on a list')
  529. assertion(argvals, 'takes one or more arguments')
  530. index, howMany = map(int, (argvals + [len(obj)])[:2])
  531. if index < 0:
  532. index += len(obj)
  533. add_items = argvals[2:]
  534. res = []
  535. for i in range(index, min(index + howMany, len(obj))):
  536. res.append(obj.pop(index))
  537. for i, item in enumerate(add_items):
  538. obj.insert(index + i, item)
  539. return res
  540. elif member == 'unshift':
  541. assertion(isinstance(obj, list), 'must be applied on a list')
  542. assertion(argvals, 'takes one or more arguments')
  543. for item in reversed(argvals):
  544. obj.insert(0, item)
  545. return obj
  546. elif member == 'pop':
  547. assertion(isinstance(obj, list), 'must be applied on a list')
  548. assertion(not argvals, 'does not take any arguments')
  549. if not obj:
  550. return
  551. return obj.pop()
  552. elif member == 'push':
  553. assertion(argvals, 'takes one or more arguments')
  554. obj.extend(argvals)
  555. return obj
  556. elif member == 'forEach':
  557. assertion(argvals, 'takes one or more arguments')
  558. assertion(len(argvals) <= 2, 'takes at-most 2 arguments')
  559. f, this = (argvals + [''])[:2]
  560. return [f((item, idx, obj), {'this': this}, allow_recursion) for idx, item in enumerate(obj)]
  561. elif member == 'indexOf':
  562. assertion(argvals, 'takes one or more arguments')
  563. assertion(len(argvals) <= 2, 'takes at-most 2 arguments')
  564. idx, start = (argvals + [0])[:2]
  565. try:
  566. return obj.index(idx, start)
  567. except ValueError:
  568. return -1
  569. idx = int(member) if isinstance(obj, list) else member
  570. return obj[idx](argvals, allow_recursion=allow_recursion)
  571. if remaining:
  572. ret, should_abort = self.interpret_statement(
  573. self._named_object(local_vars, eval_method()) + remaining,
  574. local_vars, allow_recursion)
  575. return ret, should_return or should_abort
  576. else:
  577. return eval_method(), should_return
  578. elif md.get('function'):
  579. fname = m.group('fname')
  580. argvals = [self.interpret_expression(v, local_vars, allow_recursion)
  581. for v in self._separate(m.group('args'))]
  582. if fname in local_vars:
  583. return local_vars[fname](argvals, allow_recursion=allow_recursion), should_return
  584. elif fname not in self._functions:
  585. self._functions[fname] = self.extract_function(fname)
  586. return self._functions[fname](argvals, allow_recursion=allow_recursion), should_return
  587. raise self.Exception(
  588. 'Unsupported JS expression ' + (expr[:40] if expr != stmt else ''), expr=stmt)
  589. def interpret_expression(self, expr, local_vars, allow_recursion):
  590. ret, should_return = self.interpret_statement(expr, local_vars, allow_recursion)
  591. if should_return:
  592. raise self.Exception('Cannot return from an expression', expr)
  593. return ret
  594. def extract_object(self, objname):
  595. _FUNC_NAME_RE = r'''(?:[a-zA-Z$0-9]+|"[a-zA-Z$0-9]+"|'[a-zA-Z$0-9]+')'''
  596. obj = {}
  597. obj_m = re.search(
  598. r'''(?x)
  599. (?<!this\.)%s\s*=\s*{\s*
  600. (?P<fields>(%s\s*:\s*function\s*\(.*?\)\s*{.*?}(?:,\s*)?)*)
  601. }\s*;
  602. ''' % (re.escape(objname), _FUNC_NAME_RE),
  603. self.code)
  604. if not obj_m:
  605. raise self.Exception('Could not find object ' + objname)
  606. fields = obj_m.group('fields')
  607. # Currently, it only supports function definitions
  608. fields_m = re.finditer(
  609. r'''(?x)
  610. (?P<key>%s)\s*:\s*function\s*\((?P<args>(?:%s|,)*)\){(?P<code>[^}]+)}
  611. ''' % (_FUNC_NAME_RE, _NAME_RE),
  612. fields)
  613. for f in fields_m:
  614. argnames = self.build_arglist(f.group('args'))
  615. obj[remove_quotes(f.group('key'))] = self.build_function(argnames, f.group('code'))
  616. return obj
  617. def extract_function_code(self, funcname):
  618. """ @returns argnames, code """
  619. func_m = re.search(
  620. r'''(?xs)
  621. (?:
  622. function\s+%(name)s|
  623. [{;,]\s*%(name)s\s*=\s*function|
  624. (?:var|const|let)\s+%(name)s\s*=\s*function
  625. )\s*
  626. \((?P<args>[^)]*)\)\s*
  627. (?P<code>{.+})''' % {'name': re.escape(funcname)},
  628. self.code)
  629. code, _ = self._separate_at_paren(func_m.group('code'), '}') # refine the match
  630. if func_m is None:
  631. raise self.Exception('Could not find JS function "{funcname}"'.format(**locals()))
  632. return self.build_arglist(func_m.group('args')), code
  633. def extract_function(self, funcname):
  634. return self.extract_function_from_code(*self.extract_function_code(funcname))
  635. def extract_function_from_code(self, argnames, code, *global_stack):
  636. local_vars = {}
  637. while True:
  638. mobj = re.search(r'function\((?P<args>[^)]*)\)\s*{', code)
  639. if mobj is None:
  640. break
  641. start, body_start = mobj.span()
  642. body, remaining = self._separate_at_paren(code[body_start - 1:], '}')
  643. name = self._named_object(
  644. local_vars,
  645. self.extract_function_from_code(
  646. self.build_arglist(mobj.group('args')),
  647. body, local_vars, *global_stack))
  648. code = code[:start] + name + remaining
  649. return self.build_function(argnames, code, local_vars, *global_stack)
  650. def call_function(self, funcname, *args):
  651. return self.extract_function(funcname)(args)
  652. @classmethod
  653. def build_arglist(cls, arg_text):
  654. if not arg_text:
  655. return []
  656. def valid_arg(y):
  657. y = y.strip()
  658. if not y:
  659. raise cls.Exception('Missing arg in "%s"' % (arg_text, ))
  660. return y
  661. return [valid_arg(x) for x in cls._separate(arg_text)]
  662. def build_function(self, argnames, code, *global_stack):
  663. global_stack = list(global_stack) or [{}]
  664. argnames = tuple(argnames)
  665. def resf(args, kwargs={}, allow_recursion=100):
  666. global_stack[0].update(
  667. zip_longest(argnames, args, fillvalue=None))
  668. global_stack[0].update(kwargs)
  669. var_stack = LocalNameSpace(*global_stack)
  670. ret, should_abort = self.interpret_statement(code.replace('\n', ''), var_stack, allow_recursion - 1)
  671. if should_abort:
  672. return ret
  673. return resf