jsinterp.py 39 KB

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