jsinterp.py 51 KB

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