jsinterp.py 48 KB

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