[jsinterp] Some optimizations and refactoring

Motivated by: https://github.com/ytdl-org/youtube-dl/issues/30641#issuecomment-1041904912

Authored by: dirkf, pukkandan
This commit is contained in:
pukkandan 2022-06-21 21:46:35 +05:30
parent e4afcfde08
commit 230d5c8239
No known key found for this signature in database
GPG key ID: 7EEE9E1E817D0A39

View file

@ -6,22 +6,19 @@
from .utils import ExtractorError, remove_quotes from .utils import ExtractorError, remove_quotes
_OPERATORS = [ _NAME_RE = r'[a-zA-Z_$][\w$]*'
('|', operator.or_), _OPERATORS = {
('^', operator.xor), '|': operator.or_,
('&', operator.and_), '^': operator.xor,
('>>', operator.rshift), '&': operator.and_,
('<<', operator.lshift), '>>': operator.rshift,
('-', operator.sub), '<<': operator.lshift,
('+', operator.add), '-': operator.sub,
('%', operator.mod), '+': operator.add,
('/', operator.truediv), '%': operator.mod,
('*', operator.mul), '/': operator.truediv,
] '*': operator.mul,
_ASSIGN_OPERATORS = [(op + '=', opfunc) for op, opfunc in _OPERATORS] }
_ASSIGN_OPERATORS.append(('=', (lambda cur, right: right)))
_NAME_RE = r'[a-zA-Z_$][a-zA-Z_$0-9]*'
_MATCHING_PARENS = dict(zip('({[', ')}]')) _MATCHING_PARENS = dict(zip('({[', ')}]'))
_QUOTES = '\'"' _QUOTES = '\'"'
@ -50,13 +47,11 @@ def __delitem__(self, key):
class JSInterpreter: class JSInterpreter:
__named_object_counter = 0
def __init__(self, code, objects=None): def __init__(self, code, objects=None):
if objects is None: self.code, self._functions = code, {}
objects = {} self._objects = {} if objects is None else objects
self.code = code
self._functions = {}
self._objects = objects
self.__named_object_counter = 0
def _named_object(self, namespace, obj): def _named_object(self, namespace, obj):
self.__named_object_counter += 1 self.__named_object_counter += 1
@ -93,9 +88,9 @@ def _separate(expr, delim=',', max_split=None):
break break
yield expr[start:] yield expr[start:]
@staticmethod @classmethod
def _separate_at_paren(expr, delim): def _separate_at_paren(cls, expr, delim):
separated = list(JSInterpreter._separate(expr, delim, 1)) separated = list(cls._separate(expr, delim, 1))
if len(separated) < 2: if len(separated) < 2:
raise ExtractorError(f'No terminating paren {delim} in {expr}') raise ExtractorError(f'No terminating paren {delim} in {expr}')
return separated[0][1:].strip(), separated[1].strip() return separated[0][1:].strip(), separated[1].strip()
@ -104,33 +99,29 @@ def interpret_statement(self, stmt, local_vars, allow_recursion=100):
if allow_recursion < 0: if allow_recursion < 0:
raise ExtractorError('Recursion limit reached') raise ExtractorError('Recursion limit reached')
sub_statements = list(self._separate(stmt, ';')) should_abort = False
stmt = (sub_statements or ['']).pop() sub_statements = list(self._separate(stmt, ';')) or ['']
stmt = sub_statements.pop().lstrip()
for sub_stmt in sub_statements: for sub_stmt in sub_statements:
ret, should_abort = self.interpret_statement(sub_stmt, local_vars, allow_recursion - 1) ret, should_abort = self.interpret_statement(sub_stmt, local_vars, allow_recursion - 1)
if should_abort: if should_abort:
return ret return ret, should_abort
should_abort = False m = re.match(r'(?P<var>var\s)|return(?:\s+|$)', stmt)
stmt = stmt.lstrip() if not m: # Try interpreting it as an expression
stmt_m = re.match(r'var\s', stmt) expr = stmt
if stmt_m: elif m.group('var'):
expr = stmt[len(stmt_m.group(0)):] expr = stmt[len(m.group(0)):]
else: else:
return_m = re.match(r'return(?:\s+|$)', stmt) expr = stmt[len(m.group(0)):]
if return_m: should_abort = True
expr = stmt[len(return_m.group(0)):]
should_abort = True
else:
# Try interpreting it as an expression
expr = stmt
v = self.interpret_expression(expr, local_vars, allow_recursion) return self.interpret_expression(expr, local_vars, allow_recursion), should_abort
return v, should_abort
def interpret_expression(self, expr, local_vars, allow_recursion): def interpret_expression(self, expr, local_vars, allow_recursion):
expr = expr.strip() expr = expr.strip()
if expr == '': # Empty expression if not expr:
return None return None
if expr.startswith('{'): if expr.startswith('{'):
@ -156,8 +147,8 @@ def interpret_expression(self, expr, local_vars, allow_recursion):
for item in self._separate(inner)]) for item in self._separate(inner)])
expr = name + outer expr = name + outer
m = re.match(r'try\s*', expr) m = re.match(r'(?P<try>try)\s*|(?:(?P<catch>catch)|(?P<for>for)|(?P<switch>switch))\s*\(', expr)
if m: if m and m.group('try'):
if expr[m.end()] == '{': if expr[m.end()] == '{':
try_expr, expr = self._separate_at_paren(expr[m.end():], '}') try_expr, expr = self._separate_at_paren(expr[m.end():], '}')
else: else:
@ -167,21 +158,19 @@ def interpret_expression(self, expr, local_vars, allow_recursion):
return ret return ret
return self.interpret_statement(expr, local_vars, allow_recursion - 1)[0] return self.interpret_statement(expr, local_vars, allow_recursion - 1)[0]
m = re.match(r'catch\s*\(', expr) elif m and m.group('catch'):
if m:
# We ignore the catch block # We ignore the catch block
_, expr = self._separate_at_paren(expr, '}') _, expr = self._separate_at_paren(expr, '}')
return self.interpret_statement(expr, local_vars, allow_recursion - 1)[0] return self.interpret_statement(expr, local_vars, allow_recursion - 1)[0]
m = re.match(r'for\s*\(', expr) elif m and m.group('for'):
if m:
constructor, remaining = self._separate_at_paren(expr[m.end() - 1:], ')') constructor, remaining = self._separate_at_paren(expr[m.end() - 1:], ')')
if remaining.startswith('{'): if remaining.startswith('{'):
body, expr = self._separate_at_paren(remaining, '}') body, expr = self._separate_at_paren(remaining, '}')
else: else:
m = re.match(r'switch\s*\(', remaining) # FIXME switch_m = re.match(r'switch\s*\(', remaining) # FIXME
if m: if switch_m:
switch_val, remaining = self._separate_at_paren(remaining[m.end() - 1:], ')') switch_val, remaining = self._separate_at_paren(remaining[switch_m.end() - 1:], ')')
body, expr = self._separate_at_paren(remaining, '}') body, expr = self._separate_at_paren(remaining, '}')
body = 'switch(%s){%s}' % (switch_val, body) body = 'switch(%s){%s}' % (switch_val, body)
else: else:
@ -206,8 +195,7 @@ def interpret_expression(self, expr, local_vars, allow_recursion):
f'Premature return in the initialization of a for loop in {constructor!r}') f'Premature return in the initialization of a for loop in {constructor!r}')
return self.interpret_statement(expr, local_vars, allow_recursion - 1)[0] return self.interpret_statement(expr, local_vars, allow_recursion - 1)[0]
m = re.match(r'switch\s*\(', expr) elif m and m.group('switch'):
if m:
switch_val, remaining = self._separate_at_paren(expr[m.end() - 1:], ')') switch_val, remaining = self._separate_at_paren(expr[m.end() - 1:], ')')
switch_val = self.interpret_expression(switch_val, local_vars, allow_recursion) switch_val = self.interpret_expression(switch_val, local_vars, allow_recursion)
body, expr = self._separate_at_paren(remaining, '}') body, expr = self._separate_at_paren(remaining, '}')
@ -250,55 +238,63 @@ def interpret_expression(self, expr, local_vars, allow_recursion):
ret = local_vars[var] ret = local_vars[var]
expr = expr[:start] + json.dumps(ret) + expr[end:] expr = expr[:start] + json.dumps(ret) + expr[end:]
for op, opfunc in _ASSIGN_OPERATORS: if not expr:
m = re.match(rf'''(?x) return None
(?P<out>{_NAME_RE})(?:\[(?P<index>[^\]]+?)\])?
\s*{re.escape(op)}
(?P<expr>.*)$''', expr)
if not m:
continue
right_val = self.interpret_expression(m.group('expr'), local_vars, allow_recursion)
if m.groupdict().get('index'): m = re.match(fr'''(?x)
lvar = local_vars[m.group('out')] (?P<assign>
idx = self.interpret_expression(m.group('index'), local_vars, allow_recursion) (?P<out>{_NAME_RE})(?:\[(?P<index>[^\]]+?)\])?\s*
if not isinstance(idx, int): (?P<op>{"|".join(map(re.escape, _OPERATORS))})?
raise ExtractorError(f'List indices must be integers: {idx}') =(?P<expr>.*)$
cur = lvar[idx] )|(?P<return>
val = opfunc(cur, right_val) (?!if|return|true|false|null)(?P<name>{_NAME_RE})$
lvar[idx] = val )|(?P<indexing>
return val (?P<in>{_NAME_RE})\[(?P<idx>.+)\]$
)|(?P<attribute>
(?P<var>{_NAME_RE})(?:\.(?P<member>[^(]+)|\[(?P<member2>[^\]]+)\])\s*
)|(?P<function>
(?P<fname>{_NAME_RE})\((?P<args>[\w$,]*)\)$
)''', expr)
if m and m.group('assign'):
if not m.group('op'):
opfunc = lambda curr, right: right
else: else:
cur = local_vars.get(m.group('out')) opfunc = _OPERATORS[m.group('op')]
val = opfunc(cur, right_val) right_val = self.interpret_expression(m.group('expr'), local_vars, allow_recursion)
local_vars[m.group('out')] = val left_val = local_vars.get(m.group('out'))
return val
if expr.isdigit(): if not m.group('index'):
local_vars[m.group('out')] = opfunc(left_val, right_val)
return local_vars[m.group('out')]
elif left_val is None:
raise ExtractorError(f'Cannot index undefined variable: {m.group("out")}')
idx = self.interpret_expression(m.group('index'), local_vars, allow_recursion)
if not isinstance(idx, int):
raise ExtractorError(f'List indices must be integers: {idx}')
left_val[idx] = opfunc(left_val[idx], right_val)
return left_val[idx]
elif expr.isdigit():
return int(expr) return int(expr)
if expr == 'break': elif expr == 'break':
raise JS_Break() raise JS_Break()
elif expr == 'continue': elif expr == 'continue':
raise JS_Continue() raise JS_Continue()
var_m = re.match( elif m and m.group('return'):
r'(?!if|return|true|false|null)(?P<name>%s)$' % _NAME_RE, return local_vars[m.group('name')]
expr)
if var_m:
return local_vars[var_m.group('name')]
with contextlib.suppress(ValueError): with contextlib.suppress(ValueError):
return json.loads(expr) return json.loads(expr)
m = re.match( if m and m.group('indexing'):
r'(?P<in>%s)\[(?P<idx>.+)\]$' % _NAME_RE, expr)
if m:
val = local_vars[m.group('in')] val = local_vars[m.group('in')]
idx = self.interpret_expression(m.group('idx'), local_vars, allow_recursion) idx = self.interpret_expression(m.group('idx'), local_vars, allow_recursion)
return val[idx] return val[idx]
for op, opfunc in _OPERATORS: for op, opfunc in _OPERATORS.items():
separated = list(self._separate(expr, op)) separated = list(self._separate(expr, op))
if len(separated) < 2: if len(separated) < 2:
continue continue
@ -314,10 +310,7 @@ def interpret_expression(self, expr, local_vars, allow_recursion):
raise ExtractorError(f'Premature right-side return of {op} in {expr!r}') raise ExtractorError(f'Premature right-side return of {op} in {expr!r}')
return opfunc(left_val or 0, right_val) return opfunc(left_val or 0, right_val)
m = re.match( if m and m.group('attribute'):
r'(?P<var>%s)(?:\.(?P<member>[^(]+)|\[(?P<member2>[^]]+)\])\s*' % _NAME_RE,
expr)
if m:
variable = m.group('var') variable = m.group('var')
member = remove_quotes(m.group('member') or m.group('member2')) member = remove_quotes(m.group('member') or m.group('member2'))
arg_str = expr[m.end():] arg_str = expr[m.end():]
@ -332,7 +325,6 @@ def assertion(cndn, msg):
raise ExtractorError(f'{member} {msg}: {expr}') raise ExtractorError(f'{member} {msg}: {expr}')
def eval_method(): def eval_method():
nonlocal member
if variable == 'String': if variable == 'String':
obj = str obj = str
elif variable in local_vars: elif variable in local_vars:
@ -342,8 +334,8 @@ def eval_method():
self._objects[variable] = self.extract_object(variable) self._objects[variable] = self.extract_object(variable)
obj = self._objects[variable] obj = self._objects[variable]
# Member access
if arg_str is None: if arg_str is None:
# Member access
if member == 'length': if member == 'length':
return len(obj) return len(obj)
return obj[member] return obj[member]
@ -418,9 +410,7 @@ def eval_method():
except ValueError: except ValueError:
return -1 return -1
if isinstance(obj, list): return obj[int(member) if isinstance(obj, list) else member](argvals)
member = int(member)
return obj[member](argvals)
if remaining: if remaining:
return self.interpret_expression( return self.interpret_expression(
@ -429,9 +419,8 @@ def eval_method():
else: else:
return eval_method() return eval_method()
m = re.match(r'^(?P<func>%s)\((?P<args>[a-zA-Z0-9_$,]*)\)$' % _NAME_RE, expr) elif m and m.group('function'):
if m: fname = m.group('fname')
fname = m.group('func')
argvals = tuple( argvals = tuple(
int(v) if v.isdigit() else local_vars[v] int(v) if v.isdigit() else local_vars[v]
for v in self._separate(m.group('args'))) for v in self._separate(m.group('args')))
@ -441,8 +430,7 @@ def eval_method():
self._functions[fname] = self.extract_function(fname) self._functions[fname] = self.extract_function(fname)
return self._functions[fname](argvals) return self._functions[fname](argvals)
if expr: raise ExtractorError(f'Unsupported JS expression {expr!r}')
raise ExtractorError('Unsupported JS expression %r' % expr)
def extract_object(self, objname): def extract_object(self, objname):
_FUNC_NAME_RE = r'''(?:[a-zA-Z$0-9]+|"[a-zA-Z$0-9]+"|'[a-zA-Z$0-9]+')''' _FUNC_NAME_RE = r'''(?:[a-zA-Z$0-9]+|"[a-zA-Z$0-9]+"|'[a-zA-Z$0-9]+')'''
@ -471,14 +459,17 @@ def extract_function_code(self, funcname):
""" @returns argnames, code """ """ @returns argnames, code """
func_m = re.search( func_m = re.search(
r'''(?x) r'''(?x)
(?:function\s+%s|[{;,]\s*%s\s*=\s*function|var\s+%s\s*=\s*function)\s* (?:
function\s+%(name)s|
[{;,]\s*%(name)s\s*=\s*function|
var\s+%(name)s\s*=\s*function
)\s*
\((?P<args>[^)]*)\)\s* \((?P<args>[^)]*)\)\s*
(?P<code>\{(?:(?!};)[^"]|"([^"]|\\")*")+\})''' % ( (?P<code>{(?:(?!};)[^"]|"([^"]|\\")*")+})''' % {'name': re.escape(funcname)},
re.escape(funcname), re.escape(funcname), re.escape(funcname)),
self.code) self.code)
code, _ = self._separate_at_paren(func_m.group('code'), '}') # refine the match code, _ = self._separate_at_paren(func_m.group('code'), '}') # refine the match
if func_m is None: if func_m is None:
raise ExtractorError('Could not find JS function %r' % funcname) raise ExtractorError(f'Could not find JS function "{funcname}"')
return func_m.group('args').split(','), code return func_m.group('args').split(','), code
def extract_function(self, funcname): def extract_function(self, funcname):
@ -492,11 +483,9 @@ def extract_function_from_code(self, argnames, code, *global_stack):
break break
start, body_start = mobj.span() start, body_start = mobj.span()
body, remaining = self._separate_at_paren(code[body_start - 1:], '}') body, remaining = self._separate_at_paren(code[body_start - 1:], '}')
name = self._named_object( name = self._named_object(local_vars, self.extract_function_from_code(
local_vars, [x.strip() for x in mobj.group('args').split(',')],
self.extract_function_from_code( body, local_vars, *global_stack))
[str.strip(x) for x in mobj.group('args').split(',')],
body, local_vars, *global_stack))
code = code[:start] + name + remaining code = code[:start] + name + remaining
return self.build_function(argnames, code, local_vars, *global_stack) return self.build_function(argnames, code, local_vars, *global_stack)