jsinterp.py 34 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885
  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. _RE_FLAGS = {
  141. # special knowledge: Python's re flags are bitmask values, current max 128
  142. # invent new bitmask values well above that for literal parsing
  143. # TODO: new pattern class to execute matches with these flags
  144. 'd': 1024, # Generate indices for substring matches
  145. 'g': 2048, # Global search
  146. 'i': re.I, # Case-insensitive search
  147. 'm': re.M, # Multi-line search
  148. 's': re.S, # Allows . to match newline characters
  149. 'u': re.U, # Treat a pattern as a sequence of unicode code points
  150. 'y': 4096, # Perform a "sticky" search that matches starting at the current position in the target string
  151. }
  152. _OBJ_NAME = '__youtube_dl_jsinterp_obj'
  153. OP_CHARS = None
  154. def __init__(self, code, objects=None):
  155. self.code, self._functions = code, {}
  156. self._objects = {} if objects is None else objects
  157. if type(self).OP_CHARS is None:
  158. type(self).OP_CHARS = self.OP_CHARS = self.__op_chars()
  159. class Exception(ExtractorError):
  160. def __init__(self, msg, *args, **kwargs):
  161. expr = kwargs.pop('expr', None)
  162. if expr is not None:
  163. msg = '{0} in: {1!r}'.format(msg.rstrip(), expr[:100])
  164. super(JSInterpreter.Exception, self).__init__(msg, *args, **kwargs)
  165. @classmethod
  166. def __op_chars(cls):
  167. op_chars = set(';,')
  168. for op in cls._all_operators():
  169. for c in op[0]:
  170. op_chars.add(c)
  171. return op_chars
  172. def _named_object(self, namespace, obj):
  173. self.__named_object_counter += 1
  174. name = '%s%d' % (self._OBJ_NAME, self.__named_object_counter)
  175. namespace[name] = obj
  176. return name
  177. @classmethod
  178. def _regex_flags(cls, expr):
  179. flags = 0
  180. if not expr:
  181. return flags, expr
  182. for idx, ch in enumerate(expr):
  183. if ch not in cls._RE_FLAGS:
  184. break
  185. flags |= cls._RE_FLAGS[ch]
  186. return flags, expr[idx + 1:]
  187. @classmethod
  188. def _separate(cls, expr, delim=',', max_split=None, skip_delims=None):
  189. if not expr:
  190. return
  191. # collections.Counter() is ~10% slower in both 2.7 and 3.9
  192. counters = {k: 0 for k in _MATCHING_PARENS.values()}
  193. start, splits, pos, delim_len = 0, 0, 0, len(delim) - 1
  194. in_quote, escaping, skipping = None, False, 0
  195. after_op, in_regex_char_group, skip_re = True, False, 0
  196. for idx, char in enumerate(expr):
  197. if skip_re > 0:
  198. skip_re -= 1
  199. continue
  200. if not in_quote:
  201. if char in _MATCHING_PARENS:
  202. counters[_MATCHING_PARENS[char]] += 1
  203. elif char in counters:
  204. counters[char] -= 1
  205. if not escaping:
  206. if char in _QUOTES and in_quote in (char, None):
  207. if in_quote or after_op or char != '/':
  208. in_quote = None if in_quote and not in_regex_char_group else char
  209. elif in_quote == '/' and char in '[]':
  210. in_regex_char_group = char == '['
  211. escaping = not escaping and in_quote and char == '\\'
  212. after_op = not in_quote and (char in cls.OP_CHARS or (char.isspace() and after_op))
  213. if char != delim[pos] or any(counters.values()) or in_quote:
  214. pos = skipping = 0
  215. continue
  216. elif skipping > 0:
  217. skipping -= 1
  218. continue
  219. elif pos == 0 and skip_delims:
  220. here = expr[idx:]
  221. for s in skip_delims if isinstance(skip_delims, (list, tuple)) else [skip_delims]:
  222. if here.startswith(s) and s:
  223. skipping = len(s) - 1
  224. break
  225. if skipping > 0:
  226. continue
  227. if pos < delim_len:
  228. pos += 1
  229. continue
  230. yield expr[start: idx - delim_len]
  231. start, pos = idx + 1, 0
  232. splits += 1
  233. if max_split and splits >= max_split:
  234. break
  235. yield expr[start:]
  236. @classmethod
  237. def _separate_at_paren(cls, expr, delim=None):
  238. if delim is None:
  239. delim = expr and _MATCHING_PARENS[expr[0]]
  240. separated = list(cls._separate(expr, delim, 1))
  241. if len(separated) < 2:
  242. raise cls.Exception('No terminating paren {delim} in {expr}'.format(**locals()))
  243. return separated[0][1:].strip(), separated[1].strip()
  244. @staticmethod
  245. def _all_operators():
  246. return itertools.chain(
  247. # Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
  248. _SC_OPERATORS, _LOG_OPERATORS, _COMP_OPERATORS, _OPERATORS)
  249. def _operator(self, op, left_val, right_expr, expr, local_vars, allow_recursion):
  250. if op in ('||', '&&'):
  251. if (op == '&&') ^ _js_ternary(left_val):
  252. return left_val # short circuiting
  253. elif op == '??':
  254. if left_val not in (None, JS_Undefined):
  255. return left_val
  256. elif op == '?':
  257. right_expr = _js_ternary(left_val, *self._separate(right_expr, ':', 1))
  258. right_val = self.interpret_expression(right_expr, local_vars, allow_recursion)
  259. opfunc = op and next((v for k, v in self._all_operators() if k == op), None)
  260. if not opfunc:
  261. return right_val
  262. try:
  263. return opfunc(left_val, right_val)
  264. except Exception as e:
  265. raise self.Exception('Failed to evaluate {left_val!r} {op} {right_val!r}'.format(**locals()), expr, cause=e)
  266. def _index(self, obj, idx, allow_undefined=False):
  267. if idx == 'length':
  268. return len(obj)
  269. try:
  270. return obj[int(idx)] if isinstance(obj, list) else obj[idx]
  271. except Exception as e:
  272. if allow_undefined:
  273. return JS_Undefined
  274. raise self.Exception('Cannot get index {idx}'.format(**locals()), expr=repr(obj), cause=e)
  275. def _dump(self, obj, namespace):
  276. try:
  277. return json.dumps(obj)
  278. except TypeError:
  279. return self._named_object(namespace, obj)
  280. def interpret_statement(self, stmt, local_vars, allow_recursion=100):
  281. if allow_recursion < 0:
  282. raise self.Exception('Recursion limit reached')
  283. allow_recursion -= 1
  284. should_return = False
  285. sub_statements = list(self._separate(stmt, ';')) or ['']
  286. expr = stmt = sub_statements.pop().strip()
  287. for sub_stmt in sub_statements:
  288. ret, should_return = self.interpret_statement(sub_stmt, local_vars, allow_recursion)
  289. if should_return:
  290. return ret, should_return
  291. m = re.match(r'(?P<var>(?:var|const|let)\s)|return(?:\s+|(?=["\'])|$)|(?P<throw>throw\s+)', stmt)
  292. if m:
  293. expr = stmt[len(m.group(0)):].strip()
  294. if m.group('throw'):
  295. raise JS_Throw(self.interpret_expression(expr, local_vars, allow_recursion))
  296. should_return = not m.group('var')
  297. if not expr:
  298. return None, should_return
  299. if expr[0] in _QUOTES:
  300. inner, outer = self._separate(expr, expr[0], 1)
  301. if expr[0] == '/':
  302. flags, outer = self._regex_flags(outer)
  303. inner = re.compile(inner[1:], flags=flags) # , strict=True))
  304. else:
  305. inner = json.loads(js_to_json(inner + expr[0])) # , strict=True))
  306. if not outer:
  307. return inner, should_return
  308. expr = self._named_object(local_vars, inner) + outer
  309. if expr.startswith('new '):
  310. obj = expr[4:]
  311. if obj.startswith('Date('):
  312. left, right = self._separate_at_paren(obj[4:])
  313. expr = unified_timestamp(
  314. self.interpret_expression(left, local_vars, allow_recursion), False)
  315. if not expr:
  316. raise self.Exception('Failed to parse date {left!r}'.format(**locals()), expr=expr)
  317. expr = self._dump(int(expr * 1000), local_vars) + right
  318. else:
  319. raise self.Exception('Unsupported object {obj}'.format(**locals()), expr=expr)
  320. if expr.startswith('void '):
  321. left = self.interpret_expression(expr[5:], local_vars, allow_recursion)
  322. return None, should_return
  323. if expr.startswith('{'):
  324. inner, outer = self._separate_at_paren(expr)
  325. # try for object expression (Map)
  326. sub_expressions = [list(self._separate(sub_expr.strip(), ':', 1)) for sub_expr in self._separate(inner)]
  327. if all(len(sub_expr) == 2 for sub_expr in sub_expressions):
  328. return dict(
  329. (key_expr if re.match(_NAME_RE, key_expr) else key_expr,
  330. self.interpret_expression(val_expr, local_vars, allow_recursion))
  331. for key_expr, val_expr in sub_expressions), should_return
  332. # or statement list
  333. inner, should_abort = self.interpret_statement(inner, local_vars, allow_recursion)
  334. if not outer or should_abort:
  335. return inner, should_abort or should_return
  336. else:
  337. expr = self._dump(inner, local_vars) + outer
  338. if expr.startswith('('):
  339. inner, outer = self._separate_at_paren(expr)
  340. inner, should_abort = self.interpret_statement(inner, local_vars, allow_recursion)
  341. if not outer or should_abort:
  342. return inner, should_abort or should_return
  343. else:
  344. expr = self._dump(inner, local_vars) + outer
  345. if expr.startswith('['):
  346. inner, outer = self._separate_at_paren(expr)
  347. name = self._named_object(local_vars, [
  348. self.interpret_expression(item, local_vars, allow_recursion)
  349. for item in self._separate(inner)])
  350. expr = name + outer
  351. m = re.match(r'''(?x)
  352. (?P<try>try)\s*\{|
  353. (?P<if>if)\s*\(|
  354. (?P<switch>switch)\s*\(|
  355. (?P<for>for)\s*\(
  356. ''', expr)
  357. md = m.groupdict() if m else {}
  358. if md.get('if'):
  359. cndn, expr = self._separate_at_paren(expr[m.end() - 1:])
  360. if_expr, expr = self._separate_at_paren(expr.lstrip())
  361. # TODO: "else if" is not handled
  362. else_expr = None
  363. m = re.match(r'else\s*{', expr)
  364. if m:
  365. else_expr, expr = self._separate_at_paren(expr[m.end() - 1:])
  366. cndn = _js_ternary(self.interpret_expression(cndn, local_vars, allow_recursion))
  367. ret, should_abort = self.interpret_statement(
  368. if_expr if cndn else else_expr, local_vars, allow_recursion)
  369. if should_abort:
  370. return ret, True
  371. if md.get('try'):
  372. try_expr, expr = self._separate_at_paren(expr[m.end() - 1:])
  373. err = None
  374. try:
  375. ret, should_abort = self.interpret_statement(try_expr, local_vars, allow_recursion)
  376. if should_abort:
  377. return ret, True
  378. except Exception as e:
  379. # XXX: This works for now, but makes debugging future issues very hard
  380. err = e
  381. pending = (None, False)
  382. m = re.match(r'catch\s*(?P<err>\(\s*{_NAME_RE}\s*\))?\{{'.format(**globals()), expr)
  383. if m:
  384. sub_expr, expr = self._separate_at_paren(expr[m.end() - 1:])
  385. if err:
  386. catch_vars = {}
  387. if m.group('err'):
  388. catch_vars[m.group('err')] = err.error if isinstance(err, JS_Throw) else err
  389. catch_vars = local_vars.new_child(m=catch_vars)
  390. err = None
  391. pending = self.interpret_statement(sub_expr, catch_vars, allow_recursion)
  392. m = re.match(r'finally\s*\{', expr)
  393. if m:
  394. sub_expr, expr = self._separate_at_paren(expr[m.end() - 1:])
  395. ret, should_abort = self.interpret_statement(sub_expr, local_vars, allow_recursion)
  396. if should_abort:
  397. return ret, True
  398. ret, should_abort = pending
  399. if should_abort:
  400. return ret, True
  401. if err:
  402. raise err
  403. elif md.get('for'):
  404. constructor, remaining = self._separate_at_paren(expr[m.end() - 1:])
  405. if remaining.startswith('{'):
  406. body, expr = self._separate_at_paren(remaining)
  407. else:
  408. switch_m = re.match(r'switch\s*\(', remaining) # FIXME
  409. if switch_m:
  410. switch_val, remaining = self._separate_at_paren(remaining[switch_m.end() - 1:])
  411. body, expr = self._separate_at_paren(remaining, '}')
  412. body = 'switch(%s){%s}' % (switch_val, body)
  413. else:
  414. body, expr = remaining, ''
  415. start, cndn, increment = self._separate(constructor, ';')
  416. self.interpret_expression(start, local_vars, allow_recursion)
  417. while True:
  418. if not _js_ternary(self.interpret_expression(cndn, local_vars, allow_recursion)):
  419. break
  420. try:
  421. ret, should_abort = self.interpret_statement(body, local_vars, allow_recursion)
  422. if should_abort:
  423. return ret, True
  424. except JS_Break:
  425. break
  426. except JS_Continue:
  427. pass
  428. self.interpret_expression(increment, local_vars, allow_recursion)
  429. elif md.get('switch'):
  430. switch_val, remaining = self._separate_at_paren(expr[m.end() - 1:])
  431. switch_val = self.interpret_expression(switch_val, local_vars, allow_recursion)
  432. body, expr = self._separate_at_paren(remaining, '}')
  433. items = body.replace('default:', 'case default:').split('case ')[1:]
  434. for default in (False, True):
  435. matched = False
  436. for item in items:
  437. case, stmt = (i.strip() for i in self._separate(item, ':', 1))
  438. if default:
  439. matched = matched or case == 'default'
  440. elif not matched:
  441. matched = (case != 'default'
  442. and switch_val == self.interpret_expression(case, local_vars, allow_recursion))
  443. if not matched:
  444. continue
  445. try:
  446. ret, should_abort = self.interpret_statement(stmt, local_vars, allow_recursion)
  447. if should_abort:
  448. return ret
  449. except JS_Break:
  450. break
  451. if matched:
  452. break
  453. if md:
  454. ret, should_abort = self.interpret_statement(expr, local_vars, allow_recursion)
  455. return ret, should_abort or should_return
  456. # Comma separated statements
  457. sub_expressions = list(self._separate(expr))
  458. if len(sub_expressions) > 1:
  459. for sub_expr in sub_expressions:
  460. ret, should_abort = self.interpret_statement(sub_expr, local_vars, allow_recursion)
  461. if should_abort:
  462. return ret, True
  463. return ret, False
  464. for m in re.finditer(r'''(?x)
  465. (?P<pre_sign>\+\+|--)(?P<var1>{_NAME_RE})|
  466. (?P<var2>{_NAME_RE})(?P<post_sign>\+\+|--)'''.format(**globals()), expr):
  467. var = m.group('var1') or m.group('var2')
  468. start, end = m.span()
  469. sign = m.group('pre_sign') or m.group('post_sign')
  470. ret = local_vars[var]
  471. local_vars[var] += 1 if sign[0] == '+' else -1
  472. if m.group('pre_sign'):
  473. ret = local_vars[var]
  474. expr = expr[:start] + self._dump(ret, local_vars) + expr[end:]
  475. if not expr:
  476. return None, should_return
  477. m = re.match(r'''(?x)
  478. (?P<assign>
  479. (?P<out>{_NAME_RE})(?:\[(?P<index>[^\]]+?)\])?\s*
  480. (?P<op>{_OPERATOR_RE})?
  481. =(?!=)(?P<expr>.*)$
  482. )|(?P<return>
  483. (?!if|return|true|false|null|undefined)(?P<name>{_NAME_RE})$
  484. )|(?P<indexing>
  485. (?P<in>{_NAME_RE})\[(?P<idx>.+)\]$
  486. )|(?P<attribute>
  487. (?P<var>{_NAME_RE})(?:(?P<nullish>\?)?\.(?P<member>[^(]+)|\[(?P<member2>[^\]]+)\])\s*
  488. )|(?P<function>
  489. (?P<fname>{_NAME_RE})\((?P<args>.*)\)$
  490. )'''.format(**globals()), expr)
  491. md = m.groupdict() if m else {}
  492. if md.get('assign'):
  493. left_val = local_vars.get(m.group('out'))
  494. if not m.group('index'):
  495. local_vars[m.group('out')] = self._operator(
  496. m.group('op'), left_val, m.group('expr'), expr, local_vars, allow_recursion)
  497. return local_vars[m.group('out')], should_return
  498. elif left_val in (None, JS_Undefined):
  499. raise self.Exception('Cannot index undefined variable ' + m.group('out'), expr=expr)
  500. idx = self.interpret_expression(m.group('index'), local_vars, allow_recursion)
  501. if not isinstance(idx, (int, float)):
  502. raise self.Exception('List index %s must be integer' % (idx, ), expr=expr)
  503. idx = int(idx)
  504. left_val[idx] = self._operator(
  505. m.group('op'), self._index(left_val, idx), m.group('expr'), expr, local_vars, allow_recursion)
  506. return left_val[idx], should_return
  507. elif expr.isdigit():
  508. return int(expr), should_return
  509. elif expr == 'break':
  510. raise JS_Break()
  511. elif expr == 'continue':
  512. raise JS_Continue()
  513. elif expr == 'undefined':
  514. return JS_Undefined, should_return
  515. elif expr == 'NaN':
  516. return float('NaN'), should_return
  517. elif md.get('return'):
  518. return local_vars[m.group('name')], should_return
  519. try:
  520. ret = json.loads(js_to_json(expr)) # strict=True)
  521. if not md.get('attribute'):
  522. return ret, should_return
  523. except ValueError:
  524. pass
  525. if md.get('indexing'):
  526. val = local_vars[m.group('in')]
  527. idx = self.interpret_expression(m.group('idx'), local_vars, allow_recursion)
  528. return self._index(val, idx), should_return
  529. for op, _ in self._all_operators():
  530. # hackety: </> have higher priority than <</>>, but don't confuse them
  531. skip_delim = (op + op) if op in '<>*?' else None
  532. if op == '?':
  533. skip_delim = (skip_delim, '?.')
  534. separated = list(self._separate(expr, op, skip_delims=skip_delim))
  535. if len(separated) < 2:
  536. continue
  537. right_expr = separated.pop()
  538. while op == '-' and len(separated) > 1 and not separated[-1].strip():
  539. right_expr = '-' + right_expr
  540. separated.pop()
  541. left_val = self.interpret_expression(op.join(separated), local_vars, allow_recursion)
  542. return self._operator(op, left_val, right_expr, expr, local_vars, allow_recursion), should_return
  543. if md.get('attribute'):
  544. variable, member, nullish = m.group('var', 'member', 'nullish')
  545. if not member:
  546. member = self.interpret_expression(m.group('member2'), local_vars, allow_recursion)
  547. arg_str = expr[m.end():]
  548. if arg_str.startswith('('):
  549. arg_str, remaining = self._separate_at_paren(arg_str)
  550. else:
  551. arg_str, remaining = None, arg_str
  552. def assertion(cndn, msg):
  553. """ assert, but without risk of getting optimized out """
  554. if not cndn:
  555. memb = member
  556. raise self.Exception('{member} {msg}'.format(**locals()), expr=expr)
  557. def eval_method():
  558. if (variable, member) == ('console', 'debug'):
  559. return
  560. types = {
  561. 'String': compat_str,
  562. 'Math': float,
  563. }
  564. obj = local_vars.get(variable)
  565. if obj in (JS_Undefined, None):
  566. obj = types.get(variable, JS_Undefined)
  567. if obj is JS_Undefined:
  568. try:
  569. if variable not in self._objects:
  570. self._objects[variable] = self.extract_object(variable)
  571. obj = self._objects[variable]
  572. except self.Exception:
  573. if not nullish:
  574. raise
  575. if nullish and obj is JS_Undefined:
  576. return JS_Undefined
  577. # Member access
  578. if arg_str is None:
  579. return self._index(obj, member, nullish)
  580. # Function call
  581. argvals = [
  582. self.interpret_expression(v, local_vars, allow_recursion)
  583. for v in self._separate(arg_str)]
  584. if obj == compat_str:
  585. if member == 'fromCharCode':
  586. assertion(argvals, 'takes one or more arguments')
  587. return ''.join(map(chr, argvals))
  588. raise self.Exception('Unsupported string method ' + member, expr=expr)
  589. elif obj == float:
  590. if member == 'pow':
  591. assertion(len(argvals) == 2, 'takes two arguments')
  592. return argvals[0] ** argvals[1]
  593. raise self.Exception('Unsupported Math method ' + member, expr=expr)
  594. if member == 'split':
  595. assertion(argvals, 'takes one or more arguments')
  596. assertion(len(argvals) == 1, 'with limit argument is not implemented')
  597. return obj.split(argvals[0]) if argvals[0] else list(obj)
  598. elif member == 'join':
  599. assertion(isinstance(obj, list), 'must be applied on a list')
  600. assertion(len(argvals) == 1, 'takes exactly one argument')
  601. return argvals[0].join(obj)
  602. elif member == 'reverse':
  603. assertion(not argvals, 'does not take any arguments')
  604. obj.reverse()
  605. return obj
  606. elif member == 'slice':
  607. assertion(isinstance(obj, list), 'must be applied on a list')
  608. assertion(len(argvals) == 1, 'takes exactly one argument')
  609. return obj[argvals[0]:]
  610. elif member == 'splice':
  611. assertion(isinstance(obj, list), 'must be applied on a list')
  612. assertion(argvals, 'takes one or more arguments')
  613. index, howMany = map(int, (argvals + [len(obj)])[:2])
  614. if index < 0:
  615. index += len(obj)
  616. add_items = argvals[2:]
  617. res = []
  618. for i in range(index, min(index + howMany, len(obj))):
  619. res.append(obj.pop(index))
  620. for i, item in enumerate(add_items):
  621. obj.insert(index + i, item)
  622. return res
  623. elif member == 'unshift':
  624. assertion(isinstance(obj, list), 'must be applied on a list')
  625. assertion(argvals, 'takes one or more arguments')
  626. for item in reversed(argvals):
  627. obj.insert(0, item)
  628. return obj
  629. elif member == 'pop':
  630. assertion(isinstance(obj, list), 'must be applied on a list')
  631. assertion(not argvals, 'does not take any arguments')
  632. if not obj:
  633. return
  634. return obj.pop()
  635. elif member == 'push':
  636. assertion(argvals, 'takes one or more arguments')
  637. obj.extend(argvals)
  638. return obj
  639. elif member == 'forEach':
  640. assertion(argvals, 'takes one or more arguments')
  641. assertion(len(argvals) <= 2, 'takes at-most 2 arguments')
  642. f, this = (argvals + [''])[:2]
  643. return [f((item, idx, obj), {'this': this}, allow_recursion) for idx, item in enumerate(obj)]
  644. elif member == 'indexOf':
  645. assertion(argvals, 'takes one or more arguments')
  646. assertion(len(argvals) <= 2, 'takes at-most 2 arguments')
  647. idx, start = (argvals + [0])[:2]
  648. try:
  649. return obj.index(idx, start)
  650. except ValueError:
  651. return -1
  652. elif member == 'charCodeAt':
  653. assertion(isinstance(obj, compat_str), 'must be applied on a string')
  654. # assertion(len(argvals) == 1, 'takes exactly one argument') # but not enforced
  655. idx = argvals[0] if isinstance(argvals[0], int) else 0
  656. if idx >= len(obj):
  657. return None
  658. return ord(obj[idx])
  659. idx = int(member) if isinstance(obj, list) else member
  660. return obj[idx](argvals, allow_recursion=allow_recursion)
  661. if remaining:
  662. ret, should_abort = self.interpret_statement(
  663. self._named_object(local_vars, eval_method()) + remaining,
  664. local_vars, allow_recursion)
  665. return ret, should_return or should_abort
  666. else:
  667. return eval_method(), should_return
  668. elif md.get('function'):
  669. fname = m.group('fname')
  670. argvals = [self.interpret_expression(v, local_vars, allow_recursion)
  671. for v in self._separate(m.group('args'))]
  672. if fname in local_vars:
  673. return local_vars[fname](argvals, allow_recursion=allow_recursion), should_return
  674. elif fname not in self._functions:
  675. self._functions[fname] = self.extract_function(fname)
  676. return self._functions[fname](argvals, allow_recursion=allow_recursion), should_return
  677. raise self.Exception(
  678. 'Unsupported JS expression ' + (expr[:40] if expr != stmt else ''), expr=stmt)
  679. def interpret_expression(self, expr, local_vars, allow_recursion):
  680. ret, should_return = self.interpret_statement(expr, local_vars, allow_recursion)
  681. if should_return:
  682. raise self.Exception('Cannot return from an expression', expr)
  683. return ret
  684. def extract_object(self, objname):
  685. _FUNC_NAME_RE = r'''(?:[a-zA-Z$0-9]+|"[a-zA-Z$0-9]+"|'[a-zA-Z$0-9]+')'''
  686. obj = {}
  687. obj_m = re.search(
  688. r'''(?x)
  689. (?<!this\.)%s\s*=\s*{\s*
  690. (?P<fields>(%s\s*:\s*function\s*\(.*?\)\s*{.*?}(?:,\s*)?)*)
  691. }\s*;
  692. ''' % (re.escape(objname), _FUNC_NAME_RE),
  693. self.code)
  694. if not obj_m:
  695. raise self.Exception('Could not find object ' + objname)
  696. fields = obj_m.group('fields')
  697. # Currently, it only supports function definitions
  698. fields_m = re.finditer(
  699. r'''(?x)
  700. (?P<key>%s)\s*:\s*function\s*\((?P<args>(?:%s|,)*)\){(?P<code>[^}]+)}
  701. ''' % (_FUNC_NAME_RE, _NAME_RE),
  702. fields)
  703. for f in fields_m:
  704. argnames = self.build_arglist(f.group('args'))
  705. obj[remove_quotes(f.group('key'))] = self.build_function(argnames, f.group('code'))
  706. return obj
  707. def extract_function_code(self, funcname):
  708. """ @returns argnames, code """
  709. func_m = re.search(
  710. r'''(?xs)
  711. (?:
  712. function\s+%(name)s|
  713. [{;,]\s*%(name)s\s*=\s*function|
  714. (?:var|const|let)\s+%(name)s\s*=\s*function
  715. )\s*
  716. \((?P<args>[^)]*)\)\s*
  717. (?P<code>{.+})''' % {'name': re.escape(funcname)},
  718. self.code)
  719. code, _ = self._separate_at_paren(func_m.group('code')) # refine the match
  720. if func_m is None:
  721. raise self.Exception('Could not find JS function "{funcname}"'.format(**locals()))
  722. return self.build_arglist(func_m.group('args')), code
  723. def extract_function(self, funcname):
  724. return self.extract_function_from_code(*self.extract_function_code(funcname))
  725. def extract_function_from_code(self, argnames, code, *global_stack):
  726. local_vars = {}
  727. while True:
  728. mobj = re.search(r'function\((?P<args>[^)]*)\)\s*{', code)
  729. if mobj is None:
  730. break
  731. start, body_start = mobj.span()
  732. body, remaining = self._separate_at_paren(code[body_start - 1:], '}')
  733. name = self._named_object(local_vars, self.extract_function_from_code(
  734. [x.strip() for x in mobj.group('args').split(',')],
  735. body, local_vars, *global_stack))
  736. code = code[:start] + name + remaining
  737. return self.build_function(argnames, code, local_vars, *global_stack)
  738. def call_function(self, funcname, *args):
  739. return self.extract_function(funcname)(args)
  740. @classmethod
  741. def build_arglist(cls, arg_text):
  742. if not arg_text:
  743. return []
  744. def valid_arg(y):
  745. y = y.strip()
  746. if not y:
  747. raise cls.Exception('Missing arg in "%s"' % (arg_text, ))
  748. return y
  749. return [valid_arg(x) for x in cls._separate(arg_text)]
  750. def build_function(self, argnames, code, *global_stack):
  751. global_stack = list(global_stack) or [{}]
  752. argnames = tuple(argnames)
  753. def resf(args, kwargs={}, allow_recursion=100):
  754. global_stack[0].update(
  755. zip_longest(argnames, args, fillvalue=None))
  756. global_stack[0].update(kwargs)
  757. var_stack = LocalNameSpace(*global_stack)
  758. ret, should_abort = self.interpret_statement(code.replace('\n', ' '), var_stack, allow_recursion - 1)
  759. if should_abort:
  760. return ret
  761. return resf