jsinterp.py 45 KB

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