jsinterp.py 41 KB

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