jsinterp.py 9.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263
  1. from __future__ import unicode_literals
  2. import json
  3. import operator
  4. import re
  5. from .utils import (
  6. ExtractorError,
  7. remove_quotes,
  8. )
  9. _OPERATORS = [
  10. ('|', operator.or_),
  11. ('^', operator.xor),
  12. ('&', operator.and_),
  13. ('>>', operator.rshift),
  14. ('<<', operator.lshift),
  15. ('-', operator.sub),
  16. ('+', operator.add),
  17. ('%', operator.mod),
  18. ('/', operator.truediv),
  19. ('*', operator.mul),
  20. ]
  21. _ASSIGN_OPERATORS = [(op + '=', opfunc) for op, opfunc in _OPERATORS]
  22. _ASSIGN_OPERATORS.append(('=', lambda cur, right: right))
  23. _NAME_RE = r'[a-zA-Z_$][a-zA-Z_$0-9]*'
  24. class JSInterpreter(object):
  25. def __init__(self, code, objects=None):
  26. if objects is None:
  27. objects = {}
  28. self.code = code
  29. self._functions = {}
  30. self._objects = objects
  31. def interpret_statement(self, stmt, local_vars, allow_recursion=100):
  32. if allow_recursion < 0:
  33. raise ExtractorError('Recursion limit reached')
  34. should_abort = False
  35. stmt = stmt.lstrip()
  36. stmt_m = re.match(r'var\s', stmt)
  37. if stmt_m:
  38. expr = stmt[len(stmt_m.group(0)):]
  39. else:
  40. return_m = re.match(r'return(?:\s+|$)', stmt)
  41. if return_m:
  42. expr = stmt[len(return_m.group(0)):]
  43. should_abort = True
  44. else:
  45. # Try interpreting it as an expression
  46. expr = stmt
  47. v = self.interpret_expression(expr, local_vars, allow_recursion)
  48. return v, should_abort
  49. def interpret_expression(self, expr, local_vars, allow_recursion):
  50. expr = expr.strip()
  51. if expr == '': # Empty expression
  52. return None
  53. if expr.startswith('('):
  54. parens_count = 0
  55. for m in re.finditer(r'[()]', expr):
  56. if m.group(0) == '(':
  57. parens_count += 1
  58. else:
  59. parens_count -= 1
  60. if parens_count == 0:
  61. sub_expr = expr[1:m.start()]
  62. sub_result = self.interpret_expression(
  63. sub_expr, local_vars, allow_recursion)
  64. remaining_expr = expr[m.end():].strip()
  65. if not remaining_expr:
  66. return sub_result
  67. else:
  68. expr = json.dumps(sub_result) + remaining_expr
  69. break
  70. else:
  71. raise ExtractorError('Premature end of parens in %r' % expr)
  72. for op, opfunc in _ASSIGN_OPERATORS:
  73. m = re.match(r'''(?x)
  74. (?P<out>%s)(?:\[(?P<index>[^\]]+?)\])?
  75. \s*%s
  76. (?P<expr>.*)$''' % (_NAME_RE, re.escape(op)), expr)
  77. if not m:
  78. continue
  79. right_val = self.interpret_expression(
  80. m.group('expr'), local_vars, allow_recursion - 1)
  81. if m.groupdict().get('index'):
  82. lvar = local_vars[m.group('out')]
  83. idx = self.interpret_expression(
  84. m.group('index'), local_vars, allow_recursion)
  85. assert isinstance(idx, int)
  86. cur = lvar[idx]
  87. val = opfunc(cur, right_val)
  88. lvar[idx] = val
  89. return val
  90. else:
  91. cur = local_vars.get(m.group('out'))
  92. val = opfunc(cur, right_val)
  93. local_vars[m.group('out')] = val
  94. return val
  95. if expr.isdigit():
  96. return int(expr)
  97. var_m = re.match(
  98. r'(?!if|return|true|false)(?P<name>%s)$' % _NAME_RE,
  99. expr)
  100. if var_m:
  101. return local_vars[var_m.group('name')]
  102. try:
  103. return json.loads(expr)
  104. except ValueError:
  105. pass
  106. m = re.match(
  107. r'(?P<in>%s)\[(?P<idx>.+)\]$' % _NAME_RE, expr)
  108. if m:
  109. val = local_vars[m.group('in')]
  110. idx = self.interpret_expression(
  111. m.group('idx'), local_vars, allow_recursion - 1)
  112. return val[idx]
  113. m = re.match(
  114. r'(?P<var>%s)(?:\.(?P<member>[^(]+)|\[(?P<member2>[^]]+)\])\s*(?:\(+(?P<args>[^()]*)\))?$' % _NAME_RE,
  115. expr)
  116. if m:
  117. variable = m.group('var')
  118. member = remove_quotes(m.group('member') or m.group('member2'))
  119. arg_str = m.group('args')
  120. if variable in local_vars:
  121. obj = local_vars[variable]
  122. else:
  123. if variable not in self._objects:
  124. self._objects[variable] = self.extract_object(variable)
  125. obj = self._objects[variable]
  126. if arg_str is None:
  127. # Member access
  128. if member == 'length':
  129. return len(obj)
  130. return obj[member]
  131. assert expr.endswith(')')
  132. # Function call
  133. if arg_str == '':
  134. argvals = tuple()
  135. else:
  136. argvals = tuple([
  137. self.interpret_expression(v, local_vars, allow_recursion)
  138. for v in arg_str.split(',')])
  139. if member == 'split':
  140. assert argvals == ('',)
  141. return list(obj)
  142. if member == 'join':
  143. assert len(argvals) == 1
  144. return argvals[0].join(obj)
  145. if member == 'reverse':
  146. assert len(argvals) == 0
  147. obj.reverse()
  148. return obj
  149. if member == 'slice':
  150. assert len(argvals) == 1
  151. return obj[argvals[0]:]
  152. if member == 'splice':
  153. assert isinstance(obj, list)
  154. index, howMany = argvals
  155. res = []
  156. for i in range(index, min(index + howMany, len(obj))):
  157. res.append(obj.pop(index))
  158. return res
  159. return obj[member](argvals)
  160. for op, opfunc in _OPERATORS:
  161. m = re.match(r'(?P<x>.+?)%s(?P<y>.+)' % re.escape(op), expr)
  162. if not m:
  163. continue
  164. x, abort = self.interpret_statement(
  165. m.group('x'), local_vars, allow_recursion - 1)
  166. if abort:
  167. raise ExtractorError(
  168. 'Premature left-side return of %s in %r' % (op, expr))
  169. y, abort = self.interpret_statement(
  170. m.group('y'), local_vars, allow_recursion - 1)
  171. if abort:
  172. raise ExtractorError(
  173. 'Premature right-side return of %s in %r' % (op, expr))
  174. return opfunc(x, y)
  175. m = re.match(
  176. r'^(?P<func>%s)\((?P<args>[a-zA-Z0-9_$,]*)\)$' % _NAME_RE, expr)
  177. if m:
  178. fname = m.group('func')
  179. argvals = tuple([
  180. int(v) if v.isdigit() else local_vars[v]
  181. for v in m.group('args').split(',')]) if len(m.group('args')) > 0 else tuple()
  182. if fname not in self._functions:
  183. self._functions[fname] = self.extract_function(fname)
  184. return self._functions[fname](argvals)
  185. raise ExtractorError('Unsupported JS expression %r' % expr)
  186. def extract_object(self, objname):
  187. _FUNC_NAME_RE = r'''(?:[a-zA-Z$0-9]+|"[a-zA-Z$0-9]+"|'[a-zA-Z$0-9]+')'''
  188. obj = {}
  189. obj_m = re.search(
  190. r'''(?x)
  191. (?<!this\.)%s\s*=\s*{\s*
  192. (?P<fields>(%s\s*:\s*function\s*\(.*?\)\s*{.*?}(?:,\s*)?)*)
  193. }\s*;
  194. ''' % (re.escape(objname), _FUNC_NAME_RE),
  195. self.code)
  196. fields = obj_m.group('fields')
  197. # Currently, it only supports function definitions
  198. fields_m = re.finditer(
  199. r'''(?x)
  200. (?P<key>%s)\s*:\s*function\s*\((?P<args>[a-z,]+)\){(?P<code>[^}]+)}
  201. ''' % _FUNC_NAME_RE,
  202. fields)
  203. for f in fields_m:
  204. argnames = f.group('args').split(',')
  205. obj[remove_quotes(f.group('key'))] = self.build_function(argnames, f.group('code'))
  206. return obj
  207. def extract_function(self, funcname):
  208. func_m = re.search(
  209. r'''(?x)
  210. (?:function\s+%s|[{;,]\s*%s\s*=\s*function|var\s+%s\s*=\s*function)\s*
  211. \((?P<args>[^)]*)\)\s*
  212. \{(?P<code>[^}]+)\}''' % (
  213. re.escape(funcname), re.escape(funcname), re.escape(funcname)),
  214. self.code)
  215. if func_m is None:
  216. raise ExtractorError('Could not find JS function %r' % funcname)
  217. argnames = func_m.group('args').split(',')
  218. return self.build_function(argnames, func_m.group('code'))
  219. def call_function(self, funcname, *args):
  220. f = self.extract_function(funcname)
  221. return f(args)
  222. def build_function(self, argnames, code):
  223. def resf(args):
  224. local_vars = dict(zip(argnames, args))
  225. for stmt in code.split(';'):
  226. res, abort = self.interpret_statement(stmt, local_vars)
  227. if abort:
  228. break
  229. return res
  230. return resf