jsinterp.py 47 KB

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