jsinterp.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677
  1. from __future__ import unicode_literals
  2. import itertools
  3. import json
  4. import math
  5. import operator
  6. import re
  7. from .utils import (
  8. NO_DEFAULT,
  9. ExtractorError,
  10. js_to_json,
  11. remove_quotes,
  12. unified_timestamp,
  13. )
  14. from .compat import (
  15. compat_collections_chain_map as ChainMap,
  16. compat_itertools_zip_longest as zip_longest,
  17. compat_str,
  18. )
  19. _NAME_RE = r'[a-zA-Z_$][\w$]*'
  20. # (op, definition) in order of binding priority, tightest first
  21. # avoid dict to maintain order
  22. # definition None => Defined in JSInterpreter._operator
  23. _DOT_OPERATORS = (
  24. ('.', None),
  25. # TODO: ('?.', None),
  26. )
  27. _OPERATORS = (
  28. ('|', operator.or_),
  29. ('^', operator.xor),
  30. ('&', operator.and_),
  31. ('>>', operator.rshift),
  32. ('<<', operator.lshift),
  33. ('+', operator.add),
  34. ('-', operator.sub),
  35. ('*', operator.mul),
  36. ('/', operator.truediv),
  37. ('%', operator.mod),
  38. )
  39. _COMP_OPERATORS = (
  40. ('===', operator.is_),
  41. ('==', operator.eq),
  42. ('!==', operator.is_not),
  43. ('!=', operator.ne),
  44. ('<=', operator.le),
  45. ('>=', operator.ge),
  46. ('<', operator.lt),
  47. ('>', operator.gt),
  48. )
  49. _LOG_OPERATORS = (
  50. ('&', operator.and_),
  51. ('|', operator.or_),
  52. ('^', operator.xor),
  53. )
  54. _SC_OPERATORS = (
  55. ('?', None),
  56. ('||', None),
  57. ('&&', None),
  58. # TODO: ('??', None),
  59. )
  60. _OPERATOR_RE = '|'.join(map(lambda x: re.escape(x[0]), _OPERATORS + _LOG_OPERATORS))
  61. _MATCHING_PARENS = dict(zip(*zip('()', '{}', '[]')))
  62. _QUOTES = '\'"'
  63. def _ternary(cndn, if_true=True, if_false=False):
  64. """Simulate JS's ternary operator (cndn?if_true:if_false)"""
  65. if cndn in (False, None, 0, ''):
  66. return if_false
  67. try:
  68. if math.isnan(cndn): # NB: NaN cannot be checked by membership
  69. return if_false
  70. except TypeError:
  71. pass
  72. return if_true
  73. class JS_Break(ExtractorError):
  74. def __init__(self):
  75. ExtractorError.__init__(self, 'Invalid break')
  76. class JS_Continue(ExtractorError):
  77. def __init__(self):
  78. ExtractorError.__init__(self, 'Invalid continue')
  79. class LocalNameSpace(ChainMap):
  80. def __setitem__(self, key, value):
  81. for scope in self.maps:
  82. if key in scope:
  83. scope[key] = value
  84. return
  85. self.maps[0][key] = value
  86. def __delitem__(self, key):
  87. raise NotImplementedError('Deleting is not supported')
  88. def __repr__(self):
  89. return 'LocalNameSpace%s' % (self.maps, )
  90. class JSInterpreter(object):
  91. __named_object_counter = 0
  92. def __init__(self, code, objects=None):
  93. self.code, self._functions = code, {}
  94. self._objects = {} if objects is None else objects
  95. class Exception(ExtractorError):
  96. def __init__(self, msg, *args, **kwargs):
  97. expr = kwargs.pop('expr', None)
  98. if expr is not None:
  99. msg = '{0} in: {1!r}'.format(msg.rstrip(), expr[:100])
  100. super(JSInterpreter.Exception, self).__init__(msg, *args, **kwargs)
  101. def _named_object(self, namespace, obj):
  102. self.__named_object_counter += 1
  103. name = '__youtube_dl_jsinterp_obj%d' % (self.__named_object_counter, )
  104. namespace[name] = obj
  105. return name
  106. @staticmethod
  107. def _separate(expr, delim=',', max_split=None, skip_delims=None):
  108. if not expr:
  109. return
  110. counters = {k: 0 for k in _MATCHING_PARENS.values()}
  111. start, splits, pos, skipping, delim_len = 0, 0, 0, 0, len(delim) - 1
  112. in_quote, escaping = None, False
  113. for idx, char in enumerate(expr):
  114. if not in_quote:
  115. if char in _MATCHING_PARENS:
  116. counters[_MATCHING_PARENS[char]] += 1
  117. elif char in counters:
  118. counters[char] -= 1
  119. if not escaping:
  120. if char in _QUOTES and in_quote in (char, None):
  121. in_quote = None if in_quote else char
  122. else:
  123. escaping = in_quote and char == '\\'
  124. else:
  125. escaping = False
  126. if char != delim[pos] or any(counters.values()) or in_quote:
  127. pos = skipping = 0
  128. continue
  129. elif skipping > 0:
  130. skipping -= 1
  131. continue
  132. elif pos == 0 and skip_delims:
  133. here = expr[idx:]
  134. for s in skip_delims if isinstance(skip_delims, (list, tuple)) else [skip_delims]:
  135. if here.startswith(s) and s:
  136. skipping = len(s) - 1
  137. break
  138. if skipping > 0:
  139. continue
  140. if pos < delim_len:
  141. pos += 1
  142. continue
  143. yield expr[start: idx - delim_len]
  144. start, pos = idx + 1, 0
  145. splits += 1
  146. if max_split and splits >= max_split:
  147. break
  148. yield expr[start:]
  149. @classmethod
  150. def _separate_at_paren(cls, expr, delim):
  151. separated = list(cls._separate(expr, delim, 1))
  152. if len(separated) < 2:
  153. raise cls.Exception('No terminating paren {delim} in {expr}'.format(**locals()))
  154. return separated[0][1:].strip(), separated[1].strip()
  155. @staticmethod
  156. def _all_operators():
  157. return itertools.chain(
  158. _SC_OPERATORS, _LOG_OPERATORS, _COMP_OPERATORS, _OPERATORS)
  159. def _operator(self, op, left_val, right_expr, expr, local_vars, allow_recursion):
  160. if op in ('||', '&&'):
  161. if (op == '&&') ^ _ternary(left_val):
  162. return left_val # short circuiting
  163. elif op == '?':
  164. right_expr = _ternary(left_val, *self._separate(right_expr, ':', 1))
  165. right_val = self.interpret_expression(right_expr, local_vars, allow_recursion)
  166. opfunc = op and next((v for k, v in self._all_operators() if k == op), None)
  167. if not opfunc:
  168. return right_val
  169. try:
  170. return opfunc(left_val, right_val)
  171. except Exception as e:
  172. raise self.Exception('Failed to evaluate {left_val!r} {op} {right_val!r}'.format(**locals()), expr, cause=e)
  173. def _index(self, obj, idx):
  174. if idx == 'length':
  175. return len(obj)
  176. try:
  177. return obj[int(idx)] if isinstance(obj, list) else obj[idx]
  178. except Exception as e:
  179. raise self.Exception('Cannot get index {idx}'.format(**locals()), expr=repr(obj), cause=e)
  180. def _dump(self, obj, namespace):
  181. try:
  182. return json.dumps(obj)
  183. except TypeError:
  184. return self._named_object(namespace, obj)
  185. def interpret_statement(self, stmt, local_vars, allow_recursion=100):
  186. if allow_recursion < 0:
  187. raise self.Exception('Recursion limit reached')
  188. allow_recursion -= 1
  189. should_return = False
  190. sub_statements = list(self._separate(stmt, ';')) or ['']
  191. expr = stmt = sub_statements.pop().strip()
  192. for sub_stmt in sub_statements:
  193. ret, should_return = self.interpret_statement(sub_stmt, local_vars, allow_recursion)
  194. if should_return:
  195. return ret, should_return
  196. m = re.match(r'(?P<var>(?:var|const|let)\s)|return(?:\s+|$)', stmt)
  197. if m:
  198. expr = stmt[len(m.group(0)):].strip()
  199. should_return = not m.group('var')
  200. if not expr:
  201. return None, should_return
  202. if expr[0] in _QUOTES:
  203. inner, outer = self._separate(expr, expr[0], 1)
  204. inner = json.loads(js_to_json(inner + expr[0])) # , strict=True))
  205. if not outer:
  206. return inner, should_return
  207. expr = self._named_object(local_vars, inner) + outer
  208. if expr.startswith('new '):
  209. obj = expr[4:]
  210. if obj.startswith('Date('):
  211. left, right = self._separate_at_paren(obj[4:], ')')
  212. left = self.interpret_expression(left, local_vars, allow_recursion)
  213. expr = unified_timestamp(left, False)
  214. if not expr:
  215. raise self.Exception('Failed to parse date {left!r}'.format(**locals()), expr=expr)
  216. expr = self._dump(int(expr * 1000), local_vars) + right
  217. else:
  218. raise self.Exception('Unsupported object {obj}'.format(**locals()), expr=expr)
  219. if expr.startswith('void '):
  220. left = self.interpret_expression(expr[5:], local_vars, allow_recursion)
  221. return None, should_return
  222. if expr.startswith('{'):
  223. inner, outer = self._separate_at_paren(expr, '}')
  224. inner, should_abort = self.interpret_statement(inner, local_vars, allow_recursion)
  225. if not outer or should_abort:
  226. return inner, should_abort or should_return
  227. else:
  228. expr = self._dump(inner, local_vars) + outer
  229. if expr.startswith('('):
  230. inner, outer = self._separate_at_paren(expr, ')')
  231. inner, should_abort = self.interpret_statement(inner, local_vars, allow_recursion)
  232. if not outer or should_abort:
  233. return inner, should_abort or should_return
  234. else:
  235. expr = self._dump(inner, local_vars) + outer
  236. if expr.startswith('['):
  237. inner, outer = self._separate_at_paren(expr, ']')
  238. name = self._named_object(local_vars, [
  239. self.interpret_expression(item, local_vars, allow_recursion)
  240. for item in self._separate(inner)])
  241. expr = name + outer
  242. m = re.match(r'(?P<try>try|finally)\s*|(?:(?P<catch>catch)|(?P<for>for)|(?P<switch>switch))\s*\(', expr)
  243. md = m.groupdict() if m else {}
  244. if md.get('try'):
  245. if expr[m.end()] == '{':
  246. try_expr, expr = self._separate_at_paren(expr[m.end():], '}')
  247. else:
  248. try_expr, expr = expr[m.end() - 1:], ''
  249. ret, should_abort = self.interpret_statement(try_expr, local_vars, allow_recursion)
  250. if should_abort:
  251. return ret, True
  252. ret, should_abort = self.interpret_statement(expr, local_vars, allow_recursion)
  253. return ret, should_abort or should_return
  254. elif md.get('catch'):
  255. # We ignore the catch block
  256. _, expr = self._separate_at_paren(expr, '}')
  257. ret, should_abort = self.interpret_statement(expr, local_vars, allow_recursion)
  258. return ret, should_abort or should_return
  259. elif md.get('for'):
  260. constructor, remaining = self._separate_at_paren(expr[m.end() - 1:], ')')
  261. if remaining.startswith('{'):
  262. body, expr = self._separate_at_paren(remaining, '}')
  263. else:
  264. switch_m = re.match(r'switch\s*\(', remaining) # FIXME
  265. if switch_m:
  266. switch_val, remaining = self._separate_at_paren(remaining[switch_m.end() - 1:], ')')
  267. body, expr = self._separate_at_paren(remaining, '}')
  268. body = 'switch(%s){%s}' % (switch_val, body)
  269. else:
  270. body, expr = remaining, ''
  271. start, cndn, increment = self._separate(constructor, ';')
  272. self.interpret_expression(start, local_vars, allow_recursion)
  273. while True:
  274. if not _ternary(self.interpret_expression(cndn, local_vars, allow_recursion)):
  275. break
  276. try:
  277. ret, should_abort = self.interpret_statement(body, local_vars, allow_recursion)
  278. if should_abort:
  279. return ret, True
  280. except JS_Break:
  281. break
  282. except JS_Continue:
  283. pass
  284. self.interpret_expression(increment, local_vars, allow_recursion)
  285. ret, should_abort = self.interpret_statement(expr, local_vars, allow_recursion)
  286. return ret, should_abort or should_return
  287. elif md.get('switch'):
  288. switch_val, remaining = self._separate_at_paren(expr[m.end() - 1:], ')')
  289. switch_val = self.interpret_expression(switch_val, local_vars, allow_recursion)
  290. body, expr = self._separate_at_paren(remaining, '}')
  291. items = body.replace('default:', 'case default:').split('case ')[1:]
  292. for default in (False, True):
  293. matched = False
  294. for item in items:
  295. case, stmt = (i.strip() for i in self._separate(item, ':', 1))
  296. if default:
  297. matched = matched or case == 'default'
  298. elif not matched:
  299. matched = (case != 'default'
  300. and switch_val == self.interpret_expression(case, local_vars, allow_recursion))
  301. if not matched:
  302. continue
  303. try:
  304. ret, should_abort = self.interpret_statement(stmt, local_vars, allow_recursion)
  305. if should_abort:
  306. return ret
  307. except JS_Break:
  308. break
  309. if matched:
  310. break
  311. ret, should_abort = self.interpret_statement(expr, local_vars, allow_recursion)
  312. return ret, should_abort or should_return
  313. # Comma separated statements
  314. sub_expressions = list(self._separate(expr))
  315. if len(sub_expressions) > 1:
  316. for sub_expr in sub_expressions:
  317. ret, should_abort = self.interpret_statement(sub_expr, local_vars, allow_recursion)
  318. if should_abort:
  319. return ret, True
  320. return ret, False
  321. for m in re.finditer(r'''(?x)
  322. (?P<pre_sign>\+\+|--)(?P<var1>{_NAME_RE})|
  323. (?P<var2>{_NAME_RE})(?P<post_sign>\+\+|--)'''.format(**globals()), expr):
  324. var = m.group('var1') or m.group('var2')
  325. start, end = m.span()
  326. sign = m.group('pre_sign') or m.group('post_sign')
  327. ret = local_vars[var]
  328. local_vars[var] += 1 if sign[0] == '+' else -1
  329. if m.group('pre_sign'):
  330. ret = local_vars[var]
  331. expr = expr[:start] + self._dump(ret, local_vars) + expr[end:]
  332. if not expr:
  333. return None, should_return
  334. m = re.match(r'''(?x)
  335. (?P<assign>
  336. (?P<out>{_NAME_RE})(?:\[(?P<index>[^\]]+?)\])?\s*
  337. (?P<op>{_OPERATOR_RE})?
  338. =(?P<expr>.*)$
  339. )|(?P<return>
  340. (?!if|return|true|false|null|undefined)(?P<name>{_NAME_RE})$
  341. )|(?P<indexing>
  342. (?P<in>{_NAME_RE})\[(?P<idx>.+)\]$
  343. )|(?P<attribute>
  344. (?P<var>{_NAME_RE})(?:\.(?P<member>[^(]+)|\[(?P<member2>[^\]]+)\])\s*
  345. )|(?P<function>
  346. (?P<fname>{_NAME_RE})\((?P<args>.*)\)$
  347. )'''.format(**globals()), expr)
  348. md = m.groupdict() if m else {}
  349. if md.get('assign'):
  350. left_val = local_vars.get(m.group('out'))
  351. if not m.group('index'):
  352. local_vars[m.group('out')] = self._operator(
  353. m.group('op'), left_val, m.group('expr'), expr, local_vars, allow_recursion)
  354. return local_vars[m.group('out')], should_return
  355. elif left_val is None:
  356. raise self.Exception('Cannot index undefined variable ' + m.group('out'), expr=expr)
  357. idx = self.interpret_expression(m.group('index'), local_vars, allow_recursion)
  358. if not isinstance(idx, (int, float)):
  359. raise self.Exception('List index %s must be integer' % (idx, ), expr=expr)
  360. idx = int(idx)
  361. left_val[idx] = self._operator(
  362. m.group('op'), left_val[idx], m.group('expr'), expr, local_vars, allow_recursion)
  363. return left_val[idx], should_return
  364. elif expr.isdigit():
  365. return int(expr), should_return
  366. elif expr == 'break':
  367. raise JS_Break()
  368. elif expr == 'continue':
  369. raise JS_Continue()
  370. elif md.get('return'):
  371. return local_vars[m.group('name')], should_return
  372. try:
  373. ret = json.loads(js_to_json(expr)) # strict=True)
  374. if not md.get('attribute'):
  375. return ret, should_return
  376. except ValueError:
  377. pass
  378. if md.get('indexing'):
  379. val = local_vars[m.group('in')]
  380. idx = self.interpret_expression(m.group('idx'), local_vars, allow_recursion)
  381. return self._index(val, idx), should_return
  382. for op, _ in self._all_operators():
  383. # hackety: </> have higher priority than <</>>, but don't confuse them
  384. skip_delim = (op + op) if op in ('<', '>') else None
  385. separated = list(self._separate(expr, op, skip_delims=skip_delim))
  386. if len(separated) < 2:
  387. continue
  388. right_expr = separated.pop()
  389. while op == '-' and len(separated) > 1 and not separated[-1].strip():
  390. right_expr = '-' + right_expr
  391. separated.pop()
  392. left_val = self.interpret_expression(op.join(separated), local_vars, allow_recursion)
  393. return self._operator(op, 0 if left_val is None else left_val,
  394. right_expr, expr, local_vars, allow_recursion), should_return
  395. if md.get('attribute'):
  396. variable = m.group('var')
  397. member = m.group('member')
  398. if not member:
  399. member = self.interpret_expression(m.group('member2'), local_vars, allow_recursion)
  400. arg_str = expr[m.end():]
  401. if arg_str.startswith('('):
  402. arg_str, remaining = self._separate_at_paren(arg_str, ')')
  403. else:
  404. arg_str, remaining = None, arg_str
  405. def assertion(cndn, msg):
  406. """ assert, but without risk of getting optimized out """
  407. if not cndn:
  408. raise ExtractorError('{member} {msg}'.format(**locals()), expr=expr)
  409. def eval_method():
  410. if (variable, member) == ('console', 'debug'):
  411. return
  412. types = {
  413. 'String': compat_str,
  414. 'Math': float,
  415. }
  416. obj = local_vars.get(variable, types.get(variable, NO_DEFAULT))
  417. if obj is NO_DEFAULT:
  418. if variable not in self._objects:
  419. self._objects[variable] = self.extract_object(variable)
  420. obj = self._objects[variable]
  421. # Member access
  422. if arg_str is None:
  423. return self._index(obj, member)
  424. # Function call
  425. argvals = [
  426. self.interpret_expression(v, local_vars, allow_recursion)
  427. for v in self._separate(arg_str)]
  428. if obj == compat_str:
  429. if member == 'fromCharCode':
  430. assertion(argvals, 'takes one or more arguments')
  431. return ''.join(map(chr, argvals))
  432. raise self.Exception('Unsupported string method ' + member, expr=expr)
  433. elif obj == float:
  434. if member == 'pow':
  435. assertion(len(argvals) == 2, 'takes two arguments')
  436. return argvals[0] ** argvals[1]
  437. raise self.Exception('Unsupported Math method ' + member, expr=expr)
  438. if member == 'split':
  439. assertion(argvals, 'takes one or more arguments')
  440. assertion(len(argvals) == 1, 'with limit argument is not implemented')
  441. return obj.split(argvals[0]) if argvals[0] else list(obj)
  442. elif member == 'join':
  443. assertion(isinstance(obj, list), 'must be applied on a list')
  444. assertion(len(argvals) == 1, 'takes exactly one argument')
  445. return argvals[0].join(obj)
  446. elif member == 'reverse':
  447. assertion(not argvals, 'does not take any arguments')
  448. obj.reverse()
  449. return obj
  450. elif member == 'slice':
  451. assertion(isinstance(obj, list), 'must be applied on a list')
  452. assertion(len(argvals) == 1, 'takes exactly one argument')
  453. return obj[argvals[0]:]
  454. elif member == 'splice':
  455. assertion(isinstance(obj, list), 'must be applied on a list')
  456. assertion(argvals, 'takes one or more arguments')
  457. index, howMany = map(int, (argvals + [len(obj)])[:2])
  458. if index < 0:
  459. index += len(obj)
  460. add_items = argvals[2:]
  461. res = []
  462. for i in range(index, min(index + howMany, len(obj))):
  463. res.append(obj.pop(index))
  464. for i, item in enumerate(add_items):
  465. obj.insert(index + i, item)
  466. return res
  467. elif member == 'unshift':
  468. assertion(isinstance(obj, list), 'must be applied on a list')
  469. assertion(argvals, 'takes one or more arguments')
  470. for item in reversed(argvals):
  471. obj.insert(0, item)
  472. return obj
  473. elif member == 'pop':
  474. assertion(isinstance(obj, list), 'must be applied on a list')
  475. assertion(not argvals, 'does not take any arguments')
  476. if not obj:
  477. return
  478. return obj.pop()
  479. elif member == 'push':
  480. assertion(argvals, 'takes one or more arguments')
  481. obj.extend(argvals)
  482. return obj
  483. elif member == 'forEach':
  484. assertion(argvals, 'takes one or more arguments')
  485. assertion(len(argvals) <= 2, 'takes at-most 2 arguments')
  486. f, this = (argvals + [''])[:2]
  487. return [f((item, idx, obj), {'this': this}, allow_recursion) for idx, item in enumerate(obj)]
  488. elif member == 'indexOf':
  489. assertion(argvals, 'takes one or more arguments')
  490. assertion(len(argvals) <= 2, 'takes at-most 2 arguments')
  491. idx, start = (argvals + [0])[:2]
  492. try:
  493. return obj.index(idx, start)
  494. except ValueError:
  495. return -1
  496. idx = int(member) if isinstance(obj, list) else member
  497. return obj[idx](argvals, allow_recursion=allow_recursion)
  498. if remaining:
  499. ret, should_abort = self.interpret_statement(
  500. self._named_object(local_vars, eval_method()) + remaining,
  501. local_vars, allow_recursion)
  502. return ret, should_return or should_abort
  503. else:
  504. return eval_method(), should_return
  505. elif md.get('function'):
  506. fname = m.group('fname')
  507. argvals = [self.interpret_expression(v, local_vars, allow_recursion)
  508. for v in self._separate(m.group('args'))]
  509. if fname in local_vars:
  510. return local_vars[fname](argvals, allow_recursion=allow_recursion), should_return
  511. elif fname not in self._functions:
  512. self._functions[fname] = self.extract_function(fname)
  513. return self._functions[fname](argvals, allow_recursion=allow_recursion), should_return
  514. raise self.Exception(
  515. 'Unsupported JS expression ' + (expr[:40] if expr != stmt else ''), expr=stmt)
  516. def interpret_expression(self, expr, local_vars, allow_recursion):
  517. ret, should_return = self.interpret_statement(expr, local_vars, allow_recursion)
  518. if should_return:
  519. raise self.Exception('Cannot return from an expression', expr)
  520. return ret
  521. def extract_object(self, objname):
  522. _FUNC_NAME_RE = r'''(?:[a-zA-Z$0-9]+|"[a-zA-Z$0-9]+"|'[a-zA-Z$0-9]+')'''
  523. obj = {}
  524. obj_m = re.search(
  525. r'''(?x)
  526. (?<!this\.)%s\s*=\s*{\s*
  527. (?P<fields>(%s\s*:\s*function\s*\(.*?\)\s*{.*?}(?:,\s*)?)*)
  528. }\s*;
  529. ''' % (re.escape(objname), _FUNC_NAME_RE),
  530. self.code)
  531. if not obj_m:
  532. raise self.Exception('Could not find object ' + objname)
  533. fields = obj_m.group('fields')
  534. # Currently, it only supports function definitions
  535. fields_m = re.finditer(
  536. r'''(?x)
  537. (?P<key>%s)\s*:\s*function\s*\((?P<args>(?:%s|,)*)\){(?P<code>[^}]+)}
  538. ''' % (_FUNC_NAME_RE, _NAME_RE),
  539. fields)
  540. for f in fields_m:
  541. argnames = self.build_arglist(f.group('args'))
  542. obj[remove_quotes(f.group('key'))] = self.build_function(argnames, f.group('code'))
  543. return obj
  544. def extract_function_code(self, funcname):
  545. """ @returns argnames, code """
  546. func_m = re.search(
  547. r'''(?xs)
  548. (?:
  549. function\s+%(name)s|
  550. [{;,]\s*%(name)s\s*=\s*function|
  551. (?:var|const|let)\s+%(name)s\s*=\s*function
  552. )\s*
  553. \((?P<args>[^)]*)\)\s*
  554. (?P<code>{.+})''' % {'name': re.escape(funcname)},
  555. self.code)
  556. code, _ = self._separate_at_paren(func_m.group('code'), '}') # refine the match
  557. if func_m is None:
  558. raise self.Exception('Could not find JS function "{funcname}"'.format(**locals()))
  559. return self.build_arglist(func_m.group('args')), code
  560. def extract_function(self, funcname):
  561. return self.extract_function_from_code(*self.extract_function_code(funcname))
  562. def extract_function_from_code(self, argnames, code, *global_stack):
  563. local_vars = {}
  564. while True:
  565. mobj = re.search(r'function\((?P<args>[^)]*)\)\s*{', code)
  566. if mobj is None:
  567. break
  568. start, body_start = mobj.span()
  569. body, remaining = self._separate_at_paren(code[body_start - 1:], '}')
  570. name = self._named_object(
  571. local_vars,
  572. self.extract_function_from_code(
  573. self.build_arglist(mobj.group('args')),
  574. body, local_vars, *global_stack))
  575. code = code[:start] + name + remaining
  576. return self.build_function(argnames, code, local_vars, *global_stack)
  577. def call_function(self, funcname, *args):
  578. return self.extract_function(funcname)(args)
  579. @classmethod
  580. def build_arglist(cls, arg_text):
  581. if not arg_text:
  582. return []
  583. return list(filter(None, (x.strip() or None for x in cls._separate(arg_text))))
  584. def build_function(self, argnames, code, *global_stack):
  585. global_stack = list(global_stack) or [{}]
  586. argnames = tuple(argnames)
  587. def resf(args, kwargs={}, allow_recursion=100):
  588. global_stack[0].update(
  589. zip_longest(argnames, args, fillvalue=None))
  590. global_stack[0].update(kwargs)
  591. var_stack = LocalNameSpace(*global_stack)
  592. ret, should_abort = self.interpret_statement(code.replace('\n', ''), var_stack, allow_recursion - 1)
  593. if should_abort:
  594. return ret
  595. return resf