jsinterp.py 49 KB

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