jsinterp.py 49 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266
  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. # TODO: execute matches with these flags (remaining: d, y)
  310. 'd': 1024, # Generate indices for substring matches
  311. 'g': 2048, # Global search
  312. 'i': re.I, # Case-insensitive search
  313. 'm': re.M, # Multi-line search
  314. 's': re.S, # Allows . to match newline characters
  315. 'u': re.U, # Treat a pattern as a sequence of unicode code points
  316. 'y': 4096, # Perform a "sticky" search that matches starting at the current position in the target string
  317. }
  318. def __init__(self, pattern_txt, flags=0):
  319. if isinstance(flags, compat_str):
  320. flags, _ = self.regex_flags(flags)
  321. # First, avoid https://github.com/python/cpython/issues/74534
  322. self.__self = None
  323. self.__pattern_txt = pattern_txt.replace('[[', r'[\[')
  324. self.__flags = flags
  325. def __instantiate(self):
  326. if self.__self:
  327. return
  328. self.__self = re.compile(self.__pattern_txt, self.__flags)
  329. # Thx: https://stackoverflow.com/questions/44773522/setattr-on-python2-sre-sre-pattern
  330. for name in dir(self.__self):
  331. # Only these? Obviously __class__, __init__.
  332. # PyPy creates a __weakref__ attribute with value None
  333. # that can't be setattr'd but also can't need to be copied.
  334. if name in ('__class__', '__init__', '__weakref__'):
  335. continue
  336. setattr(self, name, getattr(self.__self, name))
  337. def __getattr__(self, name):
  338. self.__instantiate()
  339. # make Py 2.6 conform to its lying documentation
  340. if name == 'flags':
  341. self.flags = self.__flags
  342. return self.flags
  343. elif name == 'pattern':
  344. self.pattern = self.__pattern_txt
  345. return self.pattern
  346. elif hasattr(self.__self, name):
  347. v = getattr(self.__self, name)
  348. setattr(self, name, v)
  349. return v
  350. elif name in ('groupindex', 'groups'):
  351. return 0 if name == 'groupindex' else {}
  352. raise AttributeError('{0} has no attribute named {1}'.format(self, name))
  353. @classmethod
  354. def regex_flags(cls, expr):
  355. flags = 0
  356. if not expr:
  357. return flags, expr
  358. for idx, ch in enumerate(expr):
  359. if ch not in cls.RE_FLAGS:
  360. break
  361. flags |= cls.RE_FLAGS[ch]
  362. return flags, expr[idx + 1:]
  363. @classmethod
  364. def __op_chars(cls):
  365. op_chars = set(';,[')
  366. for op in cls._all_operators():
  367. if op[0].isalpha():
  368. continue
  369. op_chars.update(op[0])
  370. return op_chars
  371. def _named_object(self, namespace, obj):
  372. self.__named_object_counter += 1
  373. name = '%s%d' % (self._OBJ_NAME, self.__named_object_counter)
  374. if callable(obj) and not isinstance(obj, function_with_repr):
  375. obj = function_with_repr(obj, 'F<%s>' % (self.__named_object_counter, ))
  376. namespace[name] = obj
  377. return name
  378. @classmethod
  379. def _separate(cls, expr, delim=',', max_split=None, skip_delims=None):
  380. if not expr:
  381. return
  382. # collections.Counter() is ~10% slower in both 2.7 and 3.9
  383. counters = dict((k, 0) for k in _MATCHING_PARENS.values())
  384. start, splits, pos, delim_len = 0, 0, 0, len(delim) - 1
  385. in_quote, escaping, after_op, in_regex_char_group = None, False, True, False
  386. skipping = 0
  387. if skip_delims:
  388. skip_delims = variadic(skip_delims)
  389. for idx, char in enumerate(expr):
  390. paren_delta = 0
  391. if not in_quote:
  392. if char in _MATCHING_PARENS:
  393. counters[_MATCHING_PARENS[char]] += 1
  394. paren_delta = 1
  395. elif char in counters:
  396. counters[char] -= 1
  397. paren_delta = -1
  398. if not escaping:
  399. if char in _QUOTES and in_quote in (char, None):
  400. if in_quote or after_op or char != '/':
  401. in_quote = None if in_quote and not in_regex_char_group else char
  402. elif in_quote == '/' and char in '[]':
  403. in_regex_char_group = char == '['
  404. escaping = not escaping and in_quote and char == '\\'
  405. after_op = not in_quote and (char in cls.OP_CHARS or paren_delta > 0 or (after_op and char.isspace()))
  406. if char != delim[pos] or any(counters.values()) or in_quote:
  407. pos = skipping = 0
  408. continue
  409. elif skipping > 0:
  410. skipping -= 1
  411. continue
  412. elif pos == 0 and skip_delims:
  413. here = expr[idx:]
  414. for s in skip_delims:
  415. if here.startswith(s) and s:
  416. skipping = len(s) - 1
  417. break
  418. if skipping > 0:
  419. continue
  420. if pos < delim_len:
  421. pos += 1
  422. continue
  423. yield expr[start: idx - delim_len]
  424. start, pos = idx + 1, 0
  425. splits += 1
  426. if max_split and splits >= max_split:
  427. break
  428. yield expr[start:]
  429. @classmethod
  430. def _separate_at_paren(cls, expr, delim=None):
  431. if delim is None:
  432. delim = expr and _MATCHING_PARENS[expr[0]]
  433. separated = list(cls._separate(expr, delim, 1))
  434. if len(separated) < 2:
  435. raise cls.Exception('No terminating paren {delim} in {expr!r:.5500}'.format(**locals()))
  436. return separated[0][1:].strip(), separated[1].strip()
  437. @staticmethod
  438. def _all_operators(_cached=[]):
  439. if not _cached:
  440. _cached.extend(itertools.chain(
  441. # Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
  442. _SC_OPERATORS, _LOG_OPERATORS, _COMP_OPERATORS, _OPERATORS, _UNARY_OPERATORS_X))
  443. return _cached
  444. def _operator(self, op, left_val, right_expr, expr, local_vars, allow_recursion):
  445. if op in ('||', '&&'):
  446. if (op == '&&') ^ _js_ternary(left_val):
  447. return left_val # short circuiting
  448. elif op == '??':
  449. if left_val not in (None, JS_Undefined):
  450. return left_val
  451. elif op == '?':
  452. right_expr = _js_ternary(left_val, *self._separate(right_expr, ':', 1))
  453. right_val = self.interpret_expression(right_expr, local_vars, allow_recursion)
  454. opfunc = op and next((v for k, v in self._all_operators() if k == op), None)
  455. if not opfunc:
  456. return right_val
  457. try:
  458. # print('Eval:', opfunc.__name__, left_val, right_val)
  459. return opfunc(left_val, right_val)
  460. except Exception as e:
  461. raise self.Exception('Failed to evaluate {left_val!r:.50} {op} {right_val!r:.50}'.format(**locals()), expr, cause=e)
  462. def _index(self, obj, idx, allow_undefined=True):
  463. if idx == 'length' and isinstance(obj, list):
  464. return len(obj)
  465. try:
  466. return obj[int(idx)] if isinstance(obj, list) else obj[compat_str(idx)]
  467. except (TypeError, KeyError, IndexError) as e:
  468. if allow_undefined:
  469. # when is not allowed?
  470. return JS_Undefined
  471. raise self.Exception('Cannot get index {idx!r:.100}'.format(**locals()), expr=repr(obj), cause=e)
  472. def _dump(self, obj, namespace):
  473. try:
  474. return json.dumps(obj)
  475. except TypeError:
  476. return self._named_object(namespace, obj)
  477. # used below
  478. _VAR_RET_THROW_RE = re.compile(r'''(?x)
  479. (?P<var>(?:var|const|let)\s)|return(?:\s+|(?=["'])|$)|(?P<throw>throw\s+)
  480. ''')
  481. _COMPOUND_RE = re.compile(r'''(?x)
  482. (?P<try>try)\s*\{|
  483. (?P<if>if)\s*\(|
  484. (?P<switch>switch)\s*\(|
  485. (?P<for>for)\s*\(|
  486. (?P<while>while)\s*\(
  487. ''')
  488. _FINALLY_RE = re.compile(r'finally\s*\{')
  489. _SWITCH_RE = re.compile(r'switch\s*\(')
  490. def handle_operators(self, expr, local_vars, allow_recursion):
  491. for op, _ in self._all_operators():
  492. # hackety: </> have higher priority than <</>>, but don't confuse them
  493. skip_delim = (op + op) if op in '<>*?' else None
  494. if op == '?':
  495. skip_delim = (skip_delim, '?.')
  496. separated = list(self._separate(expr, op, skip_delims=skip_delim))
  497. if len(separated) < 2:
  498. continue
  499. right_expr = separated.pop()
  500. # handle operators that are both unary and binary, minimal BODMAS
  501. if op in ('+', '-'):
  502. # simplify/adjust consecutive instances of these operators
  503. undone = 0
  504. separated = [s.strip() for s in separated]
  505. while len(separated) > 1 and not separated[-1]:
  506. undone += 1
  507. separated.pop()
  508. if op == '-' and undone % 2 != 0:
  509. right_expr = op + right_expr
  510. elif op == '+':
  511. while len(separated) > 1 and set(separated[-1]) <= self.OP_CHARS:
  512. right_expr = separated.pop() + right_expr
  513. if separated[-1][-1:] in self.OP_CHARS:
  514. right_expr = separated.pop() + right_expr
  515. # hanging op at end of left => unary + (strip) or - (push right)
  516. left_val = separated[-1] if separated else ''
  517. for dm_op in ('*', '%', '/', '**'):
  518. bodmas = tuple(self._separate(left_val, dm_op, skip_delims=skip_delim))
  519. if len(bodmas) > 1 and not bodmas[-1].strip():
  520. expr = op.join(separated) + op + right_expr
  521. if len(separated) > 1:
  522. separated.pop()
  523. right_expr = op.join((left_val, right_expr))
  524. else:
  525. separated = [op.join((left_val, right_expr))]
  526. right_expr = None
  527. break
  528. if right_expr is None:
  529. continue
  530. left_val = self.interpret_expression(op.join(separated), local_vars, allow_recursion)
  531. return self._operator(op, left_val, right_expr, expr, local_vars, allow_recursion), True
  532. @Debugger.wrap_interpreter
  533. def interpret_statement(self, stmt, local_vars, allow_recursion=100):
  534. if allow_recursion < 0:
  535. raise self.Exception('Recursion limit reached')
  536. allow_recursion -= 1
  537. # print('At: ' + stmt[:60])
  538. should_return = False
  539. # fails on (eg) if (...) stmt1; else stmt2;
  540. sub_statements = list(self._separate(stmt, ';')) or ['']
  541. expr = stmt = sub_statements.pop().strip()
  542. for sub_stmt in sub_statements:
  543. ret, should_return = self.interpret_statement(sub_stmt, local_vars, allow_recursion)
  544. if should_return:
  545. return ret, should_return
  546. m = self._VAR_RET_THROW_RE.match(stmt)
  547. if m:
  548. expr = stmt[len(m.group(0)):].strip()
  549. if m.group('throw'):
  550. raise JS_Throw(self.interpret_expression(expr, local_vars, allow_recursion))
  551. should_return = not m.group('var')
  552. if not expr:
  553. return None, should_return
  554. if expr[0] in _QUOTES:
  555. inner, outer = self._separate(expr, expr[0], 1)
  556. if expr[0] == '/':
  557. flags, outer = self.JS_RegExp.regex_flags(outer)
  558. inner = self.JS_RegExp(inner[1:], flags=flags)
  559. else:
  560. inner = json.loads(js_to_json(inner + expr[0])) # , strict=True))
  561. if not outer:
  562. return inner, should_return
  563. expr = self._named_object(local_vars, inner) + outer
  564. new_kw, _, obj = expr.partition('new ')
  565. if not new_kw:
  566. for klass, konstr in (('Date', lambda x: int(unified_timestamp(x, False) * 1000)),
  567. ('RegExp', self.JS_RegExp),
  568. ('Error', self.Exception)):
  569. if not obj.startswith(klass + '('):
  570. continue
  571. left, right = self._separate_at_paren(obj[len(klass):])
  572. argvals = self.interpret_iter(left, local_vars, allow_recursion)
  573. expr = konstr(*argvals)
  574. if expr is None:
  575. raise self.Exception('Failed to parse {klass} {left!r:.100}'.format(**locals()), expr=expr)
  576. expr = self._dump(expr, local_vars) + right
  577. break
  578. else:
  579. raise self.Exception('Unsupported object {obj:.100}'.format(**locals()), expr=expr)
  580. for op, _ in _UNARY_OPERATORS_X:
  581. if not expr.startswith(op):
  582. continue
  583. operand = expr[len(op):]
  584. if not operand or operand[0] != ' ':
  585. continue
  586. op_result = self.handle_operators(expr, local_vars, allow_recursion)
  587. if op_result:
  588. return op_result[0], should_return
  589. if expr.startswith('{'):
  590. inner, outer = self._separate_at_paren(expr)
  591. # try for object expression (Map)
  592. sub_expressions = [list(self._separate(sub_expr.strip(), ':', 1)) for sub_expr in self._separate(inner)]
  593. if all(len(sub_expr) == 2 for sub_expr in sub_expressions):
  594. return dict(
  595. (key_expr if re.match(_NAME_RE, key_expr) else key_expr,
  596. self.interpret_expression(val_expr, local_vars, allow_recursion))
  597. for key_expr, val_expr in sub_expressions), should_return
  598. # or statement list
  599. inner, should_abort = self.interpret_statement(inner, local_vars, allow_recursion)
  600. if not outer or should_abort:
  601. return inner, should_abort or should_return
  602. else:
  603. expr = self._dump(inner, local_vars) + outer
  604. if expr.startswith('('):
  605. m = re.match(r'\((?P<d>[a-z])%(?P<e>[a-z])\.length\+(?P=e)\.length\)%(?P=e)\.length', expr)
  606. if m:
  607. # short-cut eval of frequently used `(d%e.length+e.length)%e.length`, worth ~6% on `pytest -k test_nsig`
  608. outer = None
  609. inner, should_abort = self._offset_e_by_d(m.group('d'), m.group('e'), local_vars)
  610. else:
  611. inner, outer = self._separate_at_paren(expr)
  612. inner, should_abort = self.interpret_statement(inner, local_vars, allow_recursion)
  613. if not outer or should_abort:
  614. return inner, should_abort or should_return
  615. else:
  616. expr = self._dump(inner, local_vars) + outer
  617. if expr.startswith('['):
  618. inner, outer = self._separate_at_paren(expr)
  619. name = self._named_object(local_vars, [
  620. self.interpret_expression(item, local_vars, allow_recursion)
  621. for item in self._separate(inner)])
  622. expr = name + outer
  623. m = self._COMPOUND_RE.match(expr)
  624. md = m.groupdict() if m else {}
  625. if md.get('if'):
  626. cndn, expr = self._separate_at_paren(expr[m.end() - 1:])
  627. if expr.startswith('{'):
  628. if_expr, expr = self._separate_at_paren(expr)
  629. else:
  630. # may lose ... else ... because of ll.368-374
  631. if_expr, expr = self._separate_at_paren(' %s;' % (expr,), delim=';')
  632. else_expr = None
  633. m = re.match(r'else\s*(?P<block>\{)?', expr)
  634. if m:
  635. if m.group('block'):
  636. else_expr, expr = self._separate_at_paren(expr[m.end() - 1:])
  637. else:
  638. # handle subset ... else if (...) {...} else ...
  639. # TODO: make interpret_statement do this properly, if possible
  640. exprs = list(self._separate(expr[m.end():], delim='}', max_split=2))
  641. if len(exprs) > 1:
  642. if re.match(r'\s*if\s*\(', exprs[0]) and re.match(r'\s*else\b', exprs[1]):
  643. else_expr = exprs[0] + '}' + exprs[1]
  644. expr = (exprs[2] + '}') if len(exprs) == 3 else None
  645. else:
  646. else_expr = exprs[0]
  647. exprs.append('')
  648. expr = '}'.join(exprs[1:])
  649. else:
  650. else_expr = exprs[0]
  651. expr = None
  652. else_expr = else_expr.lstrip() + '}'
  653. cndn = _js_ternary(self.interpret_expression(cndn, local_vars, allow_recursion))
  654. ret, should_abort = self.interpret_statement(
  655. if_expr if cndn else else_expr, local_vars, allow_recursion)
  656. if should_abort:
  657. return ret, True
  658. elif md.get('try'):
  659. try_expr, expr = self._separate_at_paren(expr[m.end() - 1:])
  660. err = None
  661. try:
  662. ret, should_abort = self.interpret_statement(try_expr, local_vars, allow_recursion)
  663. if should_abort:
  664. return ret, True
  665. except Exception as e:
  666. # XXX: This works for now, but makes debugging future issues very hard
  667. err = e
  668. pending = (None, False)
  669. m = re.match(r'catch\s*(?P<err>\(\s*{_NAME_RE}\s*\))?\{{'.format(**globals()), expr)
  670. if m:
  671. sub_expr, expr = self._separate_at_paren(expr[m.end() - 1:])
  672. if err:
  673. catch_vars = {}
  674. if m.group('err'):
  675. catch_vars[m.group('err')] = err.error if isinstance(err, JS_Throw) else err
  676. catch_vars = local_vars.new_child(m=catch_vars)
  677. err, pending = None, self.interpret_statement(sub_expr, catch_vars, allow_recursion)
  678. m = self._FINALLY_RE.match(expr)
  679. if m:
  680. sub_expr, expr = self._separate_at_paren(expr[m.end() - 1:])
  681. ret, should_abort = self.interpret_statement(sub_expr, local_vars, allow_recursion)
  682. if should_abort:
  683. return ret, True
  684. ret, should_abort = pending
  685. if should_abort:
  686. return ret, True
  687. if err:
  688. raise err
  689. elif md.get('for') or md.get('while'):
  690. init_or_cond, remaining = self._separate_at_paren(expr[m.end() - 1:])
  691. if remaining.startswith('{'):
  692. body, expr = self._separate_at_paren(remaining)
  693. else:
  694. switch_m = self._SWITCH_RE.match(remaining) # FIXME
  695. if switch_m:
  696. switch_val, remaining = self._separate_at_paren(remaining[switch_m.end() - 1:])
  697. body, expr = self._separate_at_paren(remaining, '}')
  698. body = 'switch(%s){%s}' % (switch_val, body)
  699. else:
  700. body, expr = remaining, ''
  701. if md.get('for'):
  702. start, cndn, increment = self._separate(init_or_cond, ';')
  703. self.interpret_expression(start, local_vars, allow_recursion)
  704. else:
  705. cndn, increment = init_or_cond, None
  706. while _js_ternary(self.interpret_expression(cndn, local_vars, allow_recursion)):
  707. try:
  708. ret, should_abort = self.interpret_statement(body, local_vars, allow_recursion)
  709. if should_abort:
  710. return ret, True
  711. except JS_Break:
  712. break
  713. except JS_Continue:
  714. pass
  715. if increment:
  716. self.interpret_expression(increment, local_vars, allow_recursion)
  717. elif md.get('switch'):
  718. switch_val, remaining = self._separate_at_paren(expr[m.end() - 1:])
  719. switch_val = self.interpret_expression(switch_val, local_vars, allow_recursion)
  720. body, expr = self._separate_at_paren(remaining, '}')
  721. items = body.replace('default:', 'case default:').split('case ')[1:]
  722. for default in (False, True):
  723. matched = False
  724. for item in items:
  725. case, stmt = (i.strip() for i in self._separate(item, ':', 1))
  726. if default:
  727. matched = matched or case == 'default'
  728. elif not matched:
  729. matched = (case != 'default'
  730. and switch_val == self.interpret_expression(case, local_vars, allow_recursion))
  731. if not matched:
  732. continue
  733. try:
  734. ret, should_abort = self.interpret_statement(stmt, local_vars, allow_recursion)
  735. if should_abort:
  736. return ret
  737. except JS_Break:
  738. break
  739. if matched:
  740. break
  741. if md:
  742. ret, should_abort = self.interpret_statement(expr, local_vars, allow_recursion)
  743. return ret, should_abort or should_return
  744. # Comma separated statements
  745. sub_expressions = list(self._separate(expr))
  746. if len(sub_expressions) > 1:
  747. for sub_expr in sub_expressions:
  748. ret, should_abort = self.interpret_statement(sub_expr, local_vars, allow_recursion)
  749. if should_abort:
  750. return ret, True
  751. return ret, False
  752. for m in re.finditer(r'''(?x)
  753. (?P<pre_sign>\+\+|--)(?P<var1>{_NAME_RE})|
  754. (?P<var2>{_NAME_RE})(?P<post_sign>\+\+|--)'''.format(**globals()), expr):
  755. var = m.group('var1') or m.group('var2')
  756. start, end = m.span()
  757. sign = m.group('pre_sign') or m.group('post_sign')
  758. ret = local_vars[var]
  759. local_vars[var] = _js_add(ret, 1 if sign[0] == '+' else -1)
  760. if m.group('pre_sign'):
  761. ret = local_vars[var]
  762. expr = expr[:start] + self._dump(ret, local_vars) + expr[end:]
  763. if not expr:
  764. return None, should_return
  765. m = re.match(r'''(?x)
  766. (?P<assign>
  767. (?P<out>{_NAME_RE})(?:\[(?P<out_idx>(?:.+?\]\s*\[)*.+?)\])?\s*
  768. (?P<op>{_OPERATOR_RE})?
  769. =(?!=)(?P<expr>.*)$
  770. )|(?P<return>
  771. (?!if|return|true|false|null|undefined|NaN|Infinity)(?P<name>{_NAME_RE})$
  772. )|(?P<indexing>
  773. (?P<in>{_NAME_RE})\[(?P<in_idx>(?:.+?\]\s*\[)*.+?)\]$
  774. )|(?P<attribute>
  775. (?P<var>{_NAME_RE})(?:(?P<nullish>\?)?\.(?P<member>[^(]+)|\[(?P<member2>[^\]]+)\])\s*
  776. )|(?P<function>
  777. (?P<fname>{_NAME_RE})\((?P<args>.*)\)$
  778. )'''.format(**globals()), expr)
  779. md = m.groupdict() if m else {}
  780. if md.get('assign'):
  781. left_val = local_vars.get(m.group('out'))
  782. if not m.group('out_idx'):
  783. local_vars[m.group('out')] = self._operator(
  784. m.group('op'), left_val, m.group('expr'), expr, local_vars, allow_recursion)
  785. return local_vars[m.group('out')], should_return
  786. elif left_val in (None, JS_Undefined):
  787. raise self.Exception('Cannot index undefined variable ' + m.group('out'), expr=expr)
  788. indexes = re.split(r'\]\s*\[', m.group('out_idx'))
  789. for i, idx in enumerate(indexes, 1):
  790. idx = self.interpret_expression(idx, local_vars, allow_recursion)
  791. if i < len(indexes):
  792. left_val = self._index(left_val, idx)
  793. if isinstance(idx, float):
  794. idx = int(idx)
  795. left_val[idx] = self._operator(
  796. m.group('op'), self._index(left_val, idx) if m.group('op') else None,
  797. m.group('expr'), expr, local_vars, allow_recursion)
  798. return left_val[idx], should_return
  799. elif expr.isdigit():
  800. return int(expr), should_return
  801. elif expr == 'break':
  802. raise JS_Break()
  803. elif expr == 'continue':
  804. raise JS_Continue()
  805. elif expr == 'undefined':
  806. return JS_Undefined, should_return
  807. elif expr == 'NaN':
  808. return _NaN, should_return
  809. elif expr == 'Infinity':
  810. return _Infinity, should_return
  811. elif md.get('return'):
  812. return local_vars[m.group('name')], should_return
  813. try:
  814. ret = json.loads(js_to_json(expr)) # strict=True)
  815. if not md.get('attribute'):
  816. return ret, should_return
  817. except ValueError:
  818. pass
  819. if md.get('indexing'):
  820. val = local_vars[m.group('in')]
  821. for idx in re.split(r'\]\s*\[', m.group('in_idx')):
  822. idx = self.interpret_expression(idx, local_vars, allow_recursion)
  823. val = self._index(val, idx)
  824. return val, should_return
  825. op_result = self.handle_operators(expr, local_vars, allow_recursion)
  826. if op_result:
  827. return op_result[0], should_return
  828. if md.get('attribute'):
  829. variable, member, nullish = m.group('var', 'member', 'nullish')
  830. if not member:
  831. member = self.interpret_expression(m.group('member2'), local_vars, allow_recursion)
  832. arg_str = expr[m.end():]
  833. if arg_str.startswith('('):
  834. arg_str, remaining = self._separate_at_paren(arg_str)
  835. else:
  836. arg_str, remaining = None, arg_str
  837. def assertion(cndn, msg):
  838. """ assert, but without risk of getting optimized out """
  839. if not cndn:
  840. memb = member
  841. raise self.Exception('{memb} {msg}'.format(**locals()), expr=expr)
  842. def eval_method(variable, member):
  843. if (variable, member) == ('console', 'debug'):
  844. if Debugger.ENABLED:
  845. Debugger.write(self.interpret_expression('[{}]'.format(arg_str), local_vars, allow_recursion))
  846. return
  847. types = {
  848. 'String': compat_str,
  849. 'Math': float,
  850. 'Array': list,
  851. }
  852. obj = local_vars.get(variable)
  853. if obj in (JS_Undefined, None):
  854. obj = types.get(variable, JS_Undefined)
  855. if obj is JS_Undefined:
  856. try:
  857. if variable not in self._objects:
  858. self._objects[variable] = self.extract_object(variable)
  859. obj = self._objects[variable]
  860. except self.Exception:
  861. if not nullish:
  862. raise
  863. if nullish and obj is JS_Undefined:
  864. return JS_Undefined
  865. # Member access
  866. if arg_str is None:
  867. return self._index(obj, member)
  868. # Function call
  869. argvals = [
  870. self.interpret_expression(v, local_vars, allow_recursion)
  871. for v in self._separate(arg_str)]
  872. # Fixup prototype call
  873. if isinstance(obj, type):
  874. new_member, rest = member.partition('.')[0::2]
  875. if new_member == 'prototype':
  876. new_member, func_prototype = rest.partition('.')[0::2]
  877. assertion(argvals, 'takes one or more arguments')
  878. assertion(isinstance(argvals[0], obj), 'must bind to type {0}'.format(obj))
  879. if func_prototype == 'call':
  880. obj = argvals.pop(0)
  881. elif func_prototype == 'apply':
  882. assertion(len(argvals) == 2, 'takes two arguments')
  883. obj, argvals = argvals
  884. assertion(isinstance(argvals, list), 'second argument must be a list')
  885. else:
  886. raise self.Exception('Unsupported Function method ' + func_prototype, expr)
  887. member = new_member
  888. if obj is compat_str:
  889. if member == 'fromCharCode':
  890. assertion(argvals, 'takes one or more arguments')
  891. return ''.join(compat_chr(int(n)) for n in argvals)
  892. raise self.Exception('Unsupported string method ' + member, expr=expr)
  893. elif obj is float:
  894. if member == 'pow':
  895. assertion(len(argvals) == 2, 'takes two arguments')
  896. return argvals[0] ** argvals[1]
  897. raise self.Exception('Unsupported Math method ' + member, expr=expr)
  898. if member == 'split':
  899. assertion(argvals, 'takes one or more arguments')
  900. assertion(len(argvals) == 1, 'with limit argument is not implemented')
  901. return obj.split(argvals[0]) if argvals[0] else list(obj)
  902. elif member == 'join':
  903. assertion(isinstance(obj, list), 'must be applied on a list')
  904. assertion(len(argvals) == 1, 'takes exactly one argument')
  905. return argvals[0].join(obj)
  906. elif member == 'reverse':
  907. assertion(not argvals, 'does not take any arguments')
  908. obj.reverse()
  909. return obj
  910. elif member == 'slice':
  911. assertion(isinstance(obj, (list, compat_str)), 'must be applied on a list or string')
  912. # From [1]:
  913. # .slice() - like [:]
  914. # .slice(n) - like [n:] (not [slice(n)]
  915. # .slice(m, n) - like [m:n] or [slice(m, n)]
  916. # [1] https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/slice
  917. assertion(len(argvals) <= 2, 'takes between 0 and 2 arguments')
  918. if len(argvals) < 2:
  919. argvals += (None,)
  920. return obj[slice(*argvals)]
  921. elif member == 'splice':
  922. assertion(isinstance(obj, list), 'must be applied on a list')
  923. assertion(argvals, 'takes one or more arguments')
  924. index, how_many = map(int, (argvals + [len(obj)])[:2])
  925. if index < 0:
  926. index += len(obj)
  927. add_items = argvals[2:]
  928. res = []
  929. for _ in range(index, min(index + how_many, len(obj))):
  930. res.append(obj.pop(index))
  931. for i, item in enumerate(add_items):
  932. obj.insert(index + i, item)
  933. return res
  934. elif member == 'unshift':
  935. assertion(isinstance(obj, list), 'must be applied on a list')
  936. assertion(argvals, 'takes one or more arguments')
  937. for item in reversed(argvals):
  938. obj.insert(0, item)
  939. return obj
  940. elif member == 'pop':
  941. assertion(isinstance(obj, list), 'must be applied on a list')
  942. assertion(not argvals, 'does not take any arguments')
  943. if not obj:
  944. return
  945. return obj.pop()
  946. elif member == 'push':
  947. assertion(argvals, 'takes one or more arguments')
  948. obj.extend(argvals)
  949. return obj
  950. elif member == 'forEach':
  951. assertion(argvals, 'takes one or more arguments')
  952. assertion(len(argvals) <= 2, 'takes at-most 2 arguments')
  953. f, this = (argvals + [''])[:2]
  954. return [f((item, idx, obj), {'this': this}, allow_recursion) for idx, item in enumerate(obj)]
  955. elif member == 'indexOf':
  956. assertion(argvals, 'takes one or more arguments')
  957. assertion(len(argvals) <= 2, 'takes at-most 2 arguments')
  958. idx, start = (argvals + [0])[:2]
  959. try:
  960. return obj.index(idx, start)
  961. except ValueError:
  962. return -1
  963. elif member == 'charCodeAt':
  964. assertion(isinstance(obj, compat_str), 'must be applied on a string')
  965. # assertion(len(argvals) == 1, 'takes exactly one argument') # but not enforced
  966. idx = argvals[0] if isinstance(argvals[0], int) else 0
  967. if idx >= len(obj):
  968. return None
  969. return ord(obj[idx])
  970. elif member in ('replace', 'replaceAll'):
  971. assertion(isinstance(obj, compat_str), 'must be applied on a string')
  972. assertion(len(argvals) == 2, 'takes exactly two arguments')
  973. # TODO: argvals[1] callable, other Py vs JS edge cases
  974. if isinstance(argvals[0], self.JS_RegExp):
  975. count = 0 if argvals[0].flags & self.JS_RegExp.RE_FLAGS['g'] else 1
  976. assertion(member != 'replaceAll' or count == 0,
  977. 'replaceAll must be called with a global RegExp')
  978. return argvals[0].sub(argvals[1], obj, count=count)
  979. count = ('replaceAll', 'replace').index(member)
  980. return re.sub(re.escape(argvals[0]), argvals[1], obj, count=count)
  981. idx = int(member) if isinstance(obj, list) else member
  982. return obj[idx](argvals, allow_recursion=allow_recursion)
  983. if remaining:
  984. ret, should_abort = self.interpret_statement(
  985. self._named_object(local_vars, eval_method(variable, member)) + remaining,
  986. local_vars, allow_recursion)
  987. return ret, should_return or should_abort
  988. else:
  989. return eval_method(variable, member), should_return
  990. elif md.get('function'):
  991. fname = m.group('fname')
  992. argvals = [self.interpret_expression(v, local_vars, allow_recursion)
  993. for v in self._separate(m.group('args'))]
  994. if fname in local_vars:
  995. return local_vars[fname](argvals, allow_recursion=allow_recursion), should_return
  996. elif fname not in self._functions:
  997. self._functions[fname] = self.extract_function(fname)
  998. return self._functions[fname](argvals, allow_recursion=allow_recursion), should_return
  999. raise self.Exception(
  1000. 'Unsupported JS expression ' + (expr[:40] if expr != stmt else ''), expr=stmt)
  1001. def interpret_expression(self, expr, local_vars, allow_recursion):
  1002. ret, should_return = self.interpret_statement(expr, local_vars, allow_recursion)
  1003. if should_return:
  1004. raise self.Exception('Cannot return from an expression', expr)
  1005. return ret
  1006. def interpret_iter(self, list_txt, local_vars, allow_recursion):
  1007. for v in self._separate(list_txt):
  1008. yield self.interpret_expression(v, local_vars, allow_recursion)
  1009. def extract_object(self, objname):
  1010. _FUNC_NAME_RE = r'''(?:[a-zA-Z$0-9]+|"[a-zA-Z$0-9]+"|'[a-zA-Z$0-9]+')'''
  1011. obj = {}
  1012. fields = next(filter(None, (
  1013. obj_m.group('fields') for obj_m in re.finditer(
  1014. r'''(?xs)
  1015. {0}\s*\.\s*{1}|{1}\s*=\s*\{{\s*
  1016. (?P<fields>({2}\s*:\s*function\s*\(.*?\)\s*\{{.*?}}(?:,\s*)?)*)
  1017. }}\s*;
  1018. '''.format(_NAME_RE, re.escape(objname), _FUNC_NAME_RE),
  1019. self.code))), None)
  1020. if not fields:
  1021. raise self.Exception('Could not find object ' + objname)
  1022. # Currently, it only supports function definitions
  1023. for f in re.finditer(
  1024. r'''(?x)
  1025. (?P<key>%s)\s*:\s*function\s*\((?P<args>(?:%s|,)*)\){(?P<code>[^}]+)}
  1026. ''' % (_FUNC_NAME_RE, _NAME_RE),
  1027. fields):
  1028. argnames = self.build_arglist(f.group('args'))
  1029. name = remove_quotes(f.group('key'))
  1030. obj[name] = function_with_repr(self.build_function(argnames, f.group('code')), 'F<{0}>'.format(name))
  1031. return obj
  1032. @staticmethod
  1033. def _offset_e_by_d(d, e, local_vars):
  1034. """ Short-cut eval: (d%e.length+e.length)%e.length """
  1035. try:
  1036. d = local_vars[d]
  1037. e = local_vars[e]
  1038. e = len(e)
  1039. return _js_mod(_js_mod(d, e) + e, e), False
  1040. except Exception:
  1041. return None, True
  1042. def extract_function_code(self, funcname):
  1043. """ @returns argnames, code """
  1044. func_m = re.search(
  1045. r'''(?xs)
  1046. (?:
  1047. function\s+%(name)s|
  1048. [{;,]\s*%(name)s\s*=\s*function|
  1049. (?:var|const|let)\s+%(name)s\s*=\s*function
  1050. )\s*
  1051. \((?P<args>[^)]*)\)\s*
  1052. (?P<code>{.+})''' % {'name': re.escape(funcname)},
  1053. self.code)
  1054. if func_m is None:
  1055. raise self.Exception('Could not find JS function "{funcname}"'.format(**locals()))
  1056. code, _ = self._separate_at_paren(func_m.group('code')) # refine the match
  1057. return self.build_arglist(func_m.group('args')), code
  1058. def extract_function(self, funcname):
  1059. return function_with_repr(
  1060. self.extract_function_from_code(*self.extract_function_code(funcname)),
  1061. 'F<%s>' % (funcname,))
  1062. def extract_function_from_code(self, argnames, code, *global_stack):
  1063. local_vars = {}
  1064. while True:
  1065. mobj = re.search(r'function\((?P<args>[^)]*)\)\s*{', code)
  1066. if mobj is None:
  1067. break
  1068. start, body_start = mobj.span()
  1069. body, remaining = self._separate_at_paren(code[body_start - 1:])
  1070. name = self._named_object(local_vars, self.extract_function_from_code(
  1071. [x.strip() for x in mobj.group('args').split(',')],
  1072. body, local_vars, *global_stack))
  1073. code = code[:start] + name + remaining
  1074. return self.build_function(argnames, code, local_vars, *global_stack)
  1075. def call_function(self, funcname, *args):
  1076. return self.extract_function(funcname)(args)
  1077. @classmethod
  1078. def build_arglist(cls, arg_text):
  1079. if not arg_text:
  1080. return []
  1081. def valid_arg(y):
  1082. y = y.strip()
  1083. if not y:
  1084. raise cls.Exception('Missing arg in "%s"' % (arg_text, ))
  1085. return y
  1086. return [valid_arg(x) for x in cls._separate(arg_text)]
  1087. def build_function(self, argnames, code, *global_stack):
  1088. global_stack = list(global_stack) or [{}]
  1089. argnames = tuple(argnames)
  1090. def resf(args, kwargs={}, allow_recursion=100):
  1091. global_stack[0].update(zip_longest(argnames, args, fillvalue=None))
  1092. global_stack[0].update(kwargs)
  1093. var_stack = LocalNameSpace(*global_stack)
  1094. ret, should_abort = self.interpret_statement(code.replace('\n', ' '), var_stack, allow_recursion - 1)
  1095. if should_abort:
  1096. return ret
  1097. return resf