summaryrefslogtreecommitdiff
path: root/youtube_dl/jsinterp.py
blob: d13329396f5be7b297c309ea599d7191bb6dad8e (plain)
    1 from __future__ import unicode_literals
    2 
    3 import itertools
    4 import json
    5 import math
    6 import operator
    7 import re
    8 
    9 from .utils import (
   10     error_to_compat_str,
   11     ExtractorError,
   12     js_to_json,
   13     remove_quotes,
   14     unified_timestamp,
   15 )
   16 from .compat import (
   17     compat_basestring,
   18     compat_collections_chain_map as ChainMap,
   19     compat_itertools_zip_longest as zip_longest,
   20     compat_str,
   21 )
   22 
   23 
   24 def _js_bit_op(op):
   25 
   26     def zeroise(x):
   27         return 0 if x in (None, JS_Undefined) else x
   28 
   29     def wrapped(a, b):
   30         return op(zeroise(a), zeroise(b)) & 0xffffffff
   31 
   32     return wrapped
   33 
   34 
   35 def _js_arith_op(op):
   36 
   37     def wrapped(a, b):
   38         if JS_Undefined in (a, b):
   39             return float('nan')
   40         return op(a or 0, b or 0)
   41 
   42     return wrapped
   43 
   44 
   45 def _js_div(a, b):
   46     if JS_Undefined in (a, b) or not (a and b):
   47         return float('nan')
   48     return operator.truediv(a or 0, b) if b else float('inf')
   49 
   50 
   51 def _js_mod(a, b):
   52     if JS_Undefined in (a, b) or not b:
   53         return float('nan')
   54     return (a or 0) % b
   55 
   56 
   57 def _js_exp(a, b):
   58     if not b:
   59         return 1  # even 0 ** 0 !!
   60     elif JS_Undefined in (a, b):
   61         return float('nan')
   62     return (a or 0) ** b
   63 
   64 
   65 def _js_eq_op(op):
   66 
   67     def wrapped(a, b):
   68         if set((a, b)) <= set((None, JS_Undefined)):
   69             return op(a, a)
   70         return op(a, b)
   71 
   72     return wrapped
   73 
   74 
   75 def _js_comp_op(op):
   76 
   77     def wrapped(a, b):
   78         if JS_Undefined in (a, b):
   79             return False
   80         if isinstance(a, compat_basestring):
   81             b = compat_str(b or 0)
   82         elif isinstance(b, compat_basestring):
   83             a = compat_str(a or 0)
   84         return op(a or 0, b or 0)
   85 
   86     return wrapped
   87 
   88 
   89 def _js_ternary(cndn, if_true=True, if_false=False):
   90     """Simulate JS's ternary operator (cndn?if_true:if_false)"""
   91     if cndn in (False, None, 0, '', JS_Undefined):
   92         return if_false
   93     try:
   94         if math.isnan(cndn):  # NB: NaN cannot be checked by membership
   95             return if_false
   96     except TypeError:
   97         pass
   98     return if_true
   99 
  100 
  101 # (op, definition) in order of binding priority, tightest first
  102 # avoid dict to maintain order
  103 # definition None => Defined in JSInterpreter._operator
  104 _OPERATORS = (
  105     ('>>', _js_bit_op(operator.rshift)),
  106     ('<<', _js_bit_op(operator.lshift)),
  107     ('+', _js_arith_op(operator.add)),
  108     ('-', _js_arith_op(operator.sub)),
  109     ('*', _js_arith_op(operator.mul)),
  110     ('/', _js_div),
  111     ('%', _js_mod),
  112     ('**', _js_exp),
  113 )
  114 
  115 _COMP_OPERATORS = (
  116     ('===', operator.is_),
  117     ('!==', operator.is_not),
  118     ('==', _js_eq_op(operator.eq)),
  119     ('!=', _js_eq_op(operator.ne)),
  120     ('<=', _js_comp_op(operator.le)),
  121     ('>=', _js_comp_op(operator.ge)),
  122     ('<', _js_comp_op(operator.lt)),
  123     ('>', _js_comp_op(operator.gt)),
  124 )
  125 
  126 _LOG_OPERATORS = (
  127     ('|', _js_bit_op(operator.or_)),
  128     ('^', _js_bit_op(operator.xor)),
  129     ('&', _js_bit_op(operator.and_)),
  130 )
  131 
  132 _SC_OPERATORS = (
  133     ('?', None),
  134     ('??', None),
  135     ('||', None),
  136     ('&&', None),
  137 )
  138 
  139 _OPERATOR_RE = '|'.join(map(lambda x: re.escape(x[0]), _OPERATORS + _LOG_OPERATORS))
  140 
  141 _NAME_RE = r'[a-zA-Z_$][\w$]*'
  142 _MATCHING_PARENS = dict(zip(*zip('()', '{}', '[]')))
  143 _QUOTES = '\'"/'
  144 
  145 
  146 class JS_Undefined(object):
  147     pass
  148 
  149 
  150 class JS_Break(ExtractorError):
  151     def __init__(self):
  152         ExtractorError.__init__(self, 'Invalid break')
  153 
  154 
  155 class JS_Continue(ExtractorError):
  156     def __init__(self):
  157         ExtractorError.__init__(self, 'Invalid continue')
  158 
  159 
  160 class JS_Throw(ExtractorError):
  161     def __init__(self, e):
  162         self.error = e
  163         ExtractorError.__init__(self, 'Uncaught exception ' + error_to_compat_str(e))
  164 
  165 
  166 class LocalNameSpace(ChainMap):
  167     def __getitem__(self, key):
  168         try:
  169             return super(LocalNameSpace, self).__getitem__(key)
  170         except KeyError:
  171             return JS_Undefined
  172 
  173     def __setitem__(self, key, value):
  174         for scope in self.maps:
  175             if key in scope:
  176                 scope[key] = value
  177                 return
  178         self.maps[0][key] = value
  179 
  180     def __delitem__(self, key):
  181         raise NotImplementedError('Deleting is not supported')
  182 
  183     def __repr__(self):
  184         return 'LocalNameSpace%s' % (self.maps, )
  185 
  186 
  187 class JSInterpreter(object):
  188     __named_object_counter = 0
  189 
  190     _RE_FLAGS = {
  191         # special knowledge: Python's re flags are bitmask values, current max 128
  192         # invent new bitmask values well above that for literal parsing
  193         # TODO: new pattern class to execute matches with these flags
  194         'd': 1024,  # Generate indices for substring matches
  195         'g': 2048,  # Global search
  196         'i': re.I,  # Case-insensitive search
  197         'm': re.M,  # Multi-line search
  198         's': re.S,  # Allows . to match newline characters
  199         'u': re.U,  # Treat a pattern as a sequence of unicode code points
  200         'y': 4096,  # Perform a "sticky" search that matches starting at the current position in the target string
  201     }
  202 
  203     _OBJ_NAME = '__youtube_dl_jsinterp_obj'
  204 
  205     OP_CHARS = None
  206 
  207     def __init__(self, code, objects=None):
  208         self.code, self._functions = code, {}
  209         self._objects = {} if objects is None else objects
  210         if type(self).OP_CHARS is None:
  211             type(self).OP_CHARS = self.OP_CHARS = self.__op_chars()
  212 
  213     class Exception(ExtractorError):
  214         def __init__(self, msg, *args, **kwargs):
  215             expr = kwargs.pop('expr', None)
  216             if expr is not None:
  217                 msg = '{0} in: {1!r}'.format(msg.rstrip(), expr[:100])
  218             super(JSInterpreter.Exception, self).__init__(msg, *args, **kwargs)
  219 
  220     @classmethod
  221     def __op_chars(cls):
  222         op_chars = set(';,')
  223         for op in cls._all_operators():
  224             for c in op[0]:
  225                 op_chars.add(c)
  226         return op_chars
  227 
  228     def _named_object(self, namespace, obj):
  229         self.__named_object_counter += 1
  230         name = '%s%d' % (self._OBJ_NAME, self.__named_object_counter)
  231         namespace[name] = obj
  232         return name
  233 
  234     @classmethod
  235     def _regex_flags(cls, expr):
  236         flags = 0
  237         if not expr:
  238             return flags, expr
  239         for idx, ch in enumerate(expr):
  240             if ch not in cls._RE_FLAGS:
  241                 break
  242             flags |= cls._RE_FLAGS[ch]
  243         return flags, expr[idx + 1:]
  244 
  245     @classmethod
  246     def _separate(cls, expr, delim=',', max_split=None, skip_delims=None):
  247         if not expr:
  248             return
  249         # collections.Counter() is ~10% slower in both 2.7 and 3.9
  250         counters = {k: 0 for k in _MATCHING_PARENS.values()}
  251         start, splits, pos, delim_len = 0, 0, 0, len(delim) - 1
  252         in_quote, escaping, skipping = None, False, 0
  253         after_op, in_regex_char_group, skip_re = True, False, 0
  254 
  255         for idx, char in enumerate(expr):
  256             if skip_re > 0:
  257                 skip_re -= 1
  258                 continue
  259             if not in_quote:
  260                 if char in _MATCHING_PARENS:
  261                     counters[_MATCHING_PARENS[char]] += 1
  262                 elif char in counters:
  263                     counters[char] -= 1
  264             if not escaping:
  265                 if char in _QUOTES and in_quote in (char, None):
  266                     if in_quote or after_op or char != '/':
  267                         in_quote = None if in_quote and not in_regex_char_group else char
  268                 elif in_quote == '/' and char in '[]':
  269                     in_regex_char_group = char == '['
  270             escaping = not escaping and in_quote and char == '\\'
  271             after_op = not in_quote and (char in cls.OP_CHARS or (char.isspace() and after_op))
  272 
  273             if char != delim[pos] or any(counters.values()) or in_quote:
  274                 pos = skipping = 0
  275                 continue
  276             elif skipping > 0:
  277                 skipping -= 1
  278                 continue
  279             elif pos == 0 and skip_delims:
  280                 here = expr[idx:]
  281                 for s in skip_delims if isinstance(skip_delims, (list, tuple)) else [skip_delims]:
  282                     if here.startswith(s) and s:
  283                         skipping = len(s) - 1
  284                         break
  285                 if skipping > 0:
  286                     continue
  287             if pos < delim_len:
  288                 pos += 1
  289                 continue
  290             yield expr[start: idx - delim_len]
  291             start, pos = idx + 1, 0
  292             splits += 1
  293             if max_split and splits >= max_split:
  294                 break
  295         yield expr[start:]
  296 
  297     @classmethod
  298     def _separate_at_paren(cls, expr, delim=None):
  299         if delim is None:
  300             delim = expr and _MATCHING_PARENS[expr[0]]
  301         separated = list(cls._separate(expr, delim, 1))
  302 
  303         if len(separated) < 2:
  304             raise cls.Exception('No terminating paren {delim} in {expr}'.format(**locals()))
  305         return separated[0][1:].strip(), separated[1].strip()
  306 
  307     @staticmethod
  308     def _all_operators():
  309         return itertools.chain(
  310             # Ref: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_Precedence
  311             _SC_OPERATORS, _LOG_OPERATORS, _COMP_OPERATORS, _OPERATORS)
  312 
  313     def _operator(self, op, left_val, right_expr, expr, local_vars, allow_recursion):
  314         if op in ('||', '&&'):
  315             if (op == '&&') ^ _js_ternary(left_val):
  316                 return left_val  # short circuiting
  317         elif op == '??':
  318             if left_val not in (None, JS_Undefined):
  319                 return left_val
  320         elif op == '?':
  321             right_expr = _js_ternary(left_val, *self._separate(right_expr, ':', 1))
  322 
  323         right_val = self.interpret_expression(right_expr, local_vars, allow_recursion)
  324         opfunc = op and next((v for k, v in self._all_operators() if k == op), None)
  325         if not opfunc:
  326             return right_val
  327 
  328         try:
  329             return opfunc(left_val, right_val)
  330         except Exception as e:
  331             raise self.Exception('Failed to evaluate {left_val!r} {op} {right_val!r}'.format(**locals()), expr, cause=e)
  332 
  333     def _index(self, obj, idx, allow_undefined=False):
  334         if idx == 'length':
  335             return len(obj)
  336         try:
  337             return obj[int(idx)] if isinstance(obj, list) else obj[idx]
  338         except Exception as e:
  339             if allow_undefined:
  340                 return JS_Undefined
  341             raise self.Exception('Cannot get index {idx}'.format(**locals()), expr=repr(obj), cause=e)
  342 
  343     def _dump(self, obj, namespace):
  344         try:
  345             return json.dumps(obj)
  346         except TypeError:
  347             return self._named_object(namespace, obj)
  348 
  349     def interpret_statement(self, stmt, local_vars, allow_recursion=100):
  350         if allow_recursion < 0:
  351             raise self.Exception('Recursion limit reached')
  352         allow_recursion -= 1
  353 
  354         should_return = False
  355         sub_statements = list(self._separate(stmt, ';')) or ['']
  356         expr = stmt = sub_statements.pop().strip()
  357         for sub_stmt in sub_statements:
  358             ret, should_return = self.interpret_statement(sub_stmt, local_vars, allow_recursion)
  359             if should_return:
  360                 return ret, should_return
  361 
  362         m = re.match(r'(?P<var>(?:var|const|let)\s)|return(?:\s+|(?=["\'])|$)|(?P<throw>throw\s+)', stmt)
  363         if m:
  364             expr = stmt[len(m.group(0)):].strip()
  365             if m.group('throw'):
  366                 raise JS_Throw(self.interpret_expression(expr, local_vars, allow_recursion))
  367             should_return = not m.group('var')
  368         if not expr:
  369             return None, should_return
  370 
  371         if expr[0] in _QUOTES:
  372             inner, outer = self._separate(expr, expr[0], 1)
  373             if expr[0] == '/':
  374                 flags, outer = self._regex_flags(outer)
  375                 inner = re.compile(inner[1:], flags=flags)  # , strict=True))
  376             else:
  377                 inner = json.loads(js_to_json(inner + expr[0]))  # , strict=True))
  378             if not outer:
  379                 return inner, should_return
  380             expr = self._named_object(local_vars, inner) + outer
  381 
  382         if expr.startswith('new '):
  383             obj = expr[4:]
  384             if obj.startswith('Date('):
  385                 left, right = self._separate_at_paren(obj[4:])
  386                 expr = unified_timestamp(
  387                     self.interpret_expression(left, local_vars, allow_recursion), False)
  388                 if not expr:
  389                     raise self.Exception('Failed to parse date {left!r}'.format(**locals()), expr=expr)
  390                 expr = self._dump(int(expr * 1000), local_vars) + right
  391             else:
  392                 raise self.Exception('Unsupported object {obj}'.format(**locals()), expr=expr)
  393 
  394         if expr.startswith('void '):
  395             left = self.interpret_expression(expr[5:], local_vars, allow_recursion)
  396             return None, should_return
  397 
  398         if expr.startswith('{'):
  399             inner, outer = self._separate_at_paren(expr)
  400             # try for object expression (Map)
  401             sub_expressions = [list(self._separate(sub_expr.strip(), ':', 1)) for sub_expr in self._separate(inner)]
  402             if all(len(sub_expr) == 2 for sub_expr in sub_expressions):
  403                 return dict(
  404                     (key_expr if re.match(_NAME_RE, key_expr) else key_expr,
  405                      self.interpret_expression(val_expr, local_vars, allow_recursion))
  406                     for key_expr, val_expr in sub_expressions), should_return
  407             # or statement list
  408             inner, should_abort = self.interpret_statement(inner, local_vars, allow_recursion)
  409             if not outer or should_abort:
  410                 return inner, should_abort or should_return
  411             else:
  412                 expr = self._dump(inner, local_vars) + outer
  413 
  414         if expr.startswith('('):
  415             inner, outer = self._separate_at_paren(expr)
  416             inner, should_abort = self.interpret_statement(inner, local_vars, allow_recursion)
  417             if not outer or should_abort:
  418                 return inner, should_abort or should_return
  419             else:
  420                 expr = self._dump(inner, local_vars) + outer
  421 
  422         if expr.startswith('['):
  423             inner, outer = self._separate_at_paren(expr)
  424             name = self._named_object(local_vars, [
  425                 self.interpret_expression(item, local_vars, allow_recursion)
  426                 for item in self._separate(inner)])
  427             expr = name + outer
  428 
  429         m = re.match(r'''(?x)
  430                 (?P<try>try)\s*\{|
  431                 (?P<switch>switch)\s*\(|
  432                 (?P<for>for)\s*\(
  433                 ''', expr)
  434         md = m.groupdict() if m else {}
  435         if md.get('try'):
  436             try_expr, expr = self._separate_at_paren(expr[m.end() - 1:])
  437             err = None
  438             try:
  439                 ret, should_abort = self.interpret_statement(try_expr, local_vars, allow_recursion)
  440                 if should_abort:
  441                     return ret, True
  442             except Exception as e:
  443                 # XXX: This works for now, but makes debugging future issues very hard
  444                 err = e
  445 
  446             pending = (None, False)
  447             m = re.match(r'catch\s*(?P<err>\(\s*{_NAME_RE}\s*\))?\{{'.format(**globals()), expr)
  448             if m:
  449                 sub_expr, expr = self._separate_at_paren(expr[m.end() - 1:])
  450                 if err:
  451                     catch_vars = {}
  452                     if m.group('err'):
  453                         catch_vars[m.group('err')] = err.error if isinstance(err, JS_Throw) else err
  454                     catch_vars = local_vars.new_child(m=catch_vars)
  455                     err = None
  456                     pending = self.interpret_statement(sub_expr, catch_vars, allow_recursion)
  457 
  458             m = re.match(r'finally\s*\{', expr)
  459             if m:
  460                 sub_expr, expr = self._separate_at_paren(expr[m.end() - 1:])
  461                 ret, should_abort = self.interpret_statement(sub_expr, local_vars, allow_recursion)
  462                 if should_abort:
  463                     return ret, True
  464 
  465             ret, should_abort = pending
  466             if should_abort:
  467                 return ret, True
  468 
  469             if err:
  470                 raise err
  471 
  472         elif md.get('for'):
  473             constructor, remaining = self._separate_at_paren(expr[m.end() - 1:])
  474             if remaining.startswith('{'):
  475                 body, expr = self._separate_at_paren(remaining)
  476             else:
  477                 switch_m = re.match(r'switch\s*\(', remaining)  # FIXME
  478                 if switch_m:
  479                     switch_val, remaining = self._separate_at_paren(remaining[switch_m.end() - 1:])
  480                     body, expr = self._separate_at_paren(remaining, '}')
  481                     body = 'switch(%s){%s}' % (switch_val, body)
  482                 else:
  483                     body, expr = remaining, ''
  484             start, cndn, increment = self._separate(constructor, ';')
  485             self.interpret_expression(start, local_vars, allow_recursion)
  486             while True:
  487                 if not _js_ternary(self.interpret_expression(cndn, local_vars, allow_recursion)):
  488                     break
  489                 try:
  490                     ret, should_abort = self.interpret_statement(body, local_vars, allow_recursion)
  491                     if should_abort:
  492                         return ret, True
  493                 except JS_Break:
  494                     break
  495                 except JS_Continue:
  496                     pass
  497                 self.interpret_expression(increment, local_vars, allow_recursion)
  498 
  499         elif md.get('switch'):
  500             switch_val, remaining = self._separate_at_paren(expr[m.end() - 1:])
  501             switch_val = self.interpret_expression(switch_val, local_vars, allow_recursion)
  502             body, expr = self._separate_at_paren(remaining, '}')
  503             items = body.replace('default:', 'case default:').split('case ')[1:]
  504             for default in (False, True):
  505                 matched = False
  506                 for item in items:
  507                     case, stmt = (i.strip() for i in self._separate(item, ':', 1))
  508                     if default:
  509                         matched = matched or case == 'default'
  510                     elif not matched:
  511                         matched = (case != 'default'
  512                                    and switch_val == self.interpret_expression(case, local_vars, allow_recursion))
  513                     if not matched:
  514                         continue
  515                     try:
  516                         ret, should_abort = self.interpret_statement(stmt, local_vars, allow_recursion)
  517                         if should_abort:
  518                             return ret
  519                     except JS_Break:
  520                         break
  521                 if matched:
  522                     break
  523 
  524         if md:
  525             ret, should_abort = self.interpret_statement(expr, local_vars, allow_recursion)
  526             return ret, should_abort or should_return
  527 
  528         # Comma separated statements
  529         sub_expressions = list(self._separate(expr))
  530         if len(sub_expressions) > 1:
  531             for sub_expr in sub_expressions:
  532                 ret, should_abort = self.interpret_statement(sub_expr, local_vars, allow_recursion)
  533                 if should_abort:
  534                     return ret, True
  535             return ret, False
  536 
  537         for m in re.finditer(r'''(?x)
  538                 (?P<pre_sign>\+\+|--)(?P<var1>{_NAME_RE})|
  539                 (?P<var2>{_NAME_RE})(?P<post_sign>\+\+|--)'''.format(**globals()), expr):
  540             var = m.group('var1') or m.group('var2')
  541             start, end = m.span()
  542             sign = m.group('pre_sign') or m.group('post_sign')
  543             ret = local_vars[var]
  544             local_vars[var] += 1 if sign[0] == '+' else -1
  545             if m.group('pre_sign'):
  546                 ret = local_vars[var]
  547             expr = expr[:start] + self._dump(ret, local_vars) + expr[end:]
  548 
  549         if not expr:
  550             return None, should_return
  551 
  552         m = re.match(r'''(?x)
  553             (?P<assign>
  554                 (?P<out>{_NAME_RE})(?:\[(?P<index>[^\]]+?)\])?\s*
  555                 (?P<op>{_OPERATOR_RE})?
  556                 =(?!=)(?P<expr>.*)$
  557             )|(?P<return>
  558                 (?!if|return|true|false|null|undefined)(?P<name>{_NAME_RE})$
  559             )|(?P<indexing>
  560                 (?P<in>{_NAME_RE})\[(?P<idx>.+)\]$
  561             )|(?P<attribute>
  562                 (?P<var>{_NAME_RE})(?:(?P<nullish>\?)?\.(?P<member>[^(]+)|\[(?P<member2>[^\]]+)\])\s*
  563             )|(?P<function>
  564                 (?P<fname>{_NAME_RE})\((?P<args>.*)\)$
  565             )'''.format(**globals()), expr)
  566         md = m.groupdict() if m else {}
  567         if md.get('assign'):
  568             left_val = local_vars.get(m.group('out'))
  569 
  570             if not m.group('index'):
  571                 local_vars[m.group('out')] = self._operator(
  572                     m.group('op'), left_val, m.group('expr'), expr, local_vars, allow_recursion)
  573                 return local_vars[m.group('out')], should_return
  574             elif left_val in (None, JS_Undefined):
  575                 raise self.Exception('Cannot index undefined variable ' + m.group('out'), expr=expr)
  576 
  577             idx = self.interpret_expression(m.group('index'), local_vars, allow_recursion)
  578             if not isinstance(idx, (int, float)):
  579                 raise self.Exception('List index %s must be integer' % (idx, ), expr=expr)
  580             idx = int(idx)
  581             left_val[idx] = self._operator(
  582                 m.group('op'), self._index(left_val, idx), m.group('expr'), expr, local_vars, allow_recursion)
  583             return left_val[idx], should_return
  584 
  585         elif expr.isdigit():
  586             return int(expr), should_return
  587 
  588         elif expr == 'break':
  589             raise JS_Break()
  590         elif expr == 'continue':
  591             raise JS_Continue()
  592 
  593         elif expr == 'undefined':
  594             return JS_Undefined, should_return
  595         elif expr == 'NaN':
  596             return float('NaN'), should_return
  597 
  598         elif md.get('return'):
  599             return local_vars[m.group('name')], should_return
  600 
  601         try:
  602             ret = json.loads(js_to_json(expr))  # strict=True)
  603             if not md.get('attribute'):
  604                 return ret, should_return
  605         except ValueError:
  606             pass
  607 
  608         if md.get('indexing'):
  609             val = local_vars[m.group('in')]
  610             idx = self.interpret_expression(m.group('idx'), local_vars, allow_recursion)
  611             return self._index(val, idx), should_return
  612 
  613         for op, _ in self._all_operators():
  614             # hackety: </> have higher priority than <</>>, but don't confuse them
  615             skip_delim = (op + op) if op in '<>*?' else None
  616             if op == '?':
  617                 skip_delim = (skip_delim, '?.')
  618             separated = list(self._separate(expr, op, skip_delims=skip_delim))
  619             if len(separated) < 2:
  620                 continue
  621 
  622             right_expr = separated.pop()
  623             while op == '-' and len(separated) > 1 and not separated[-1].strip():
  624                 right_expr = '-' + right_expr
  625                 separated.pop()
  626             left_val = self.interpret_expression(op.join(separated), local_vars, allow_recursion)
  627             return self._operator(op, left_val, right_expr, expr, local_vars, allow_recursion), should_return
  628 
  629         if md.get('attribute'):
  630             variable, member, nullish = m.group('var', 'member', 'nullish')
  631             if not member:
  632                 member = self.interpret_expression(m.group('member2'), local_vars, allow_recursion)
  633             arg_str = expr[m.end():]
  634             if arg_str.startswith('('):
  635                 arg_str, remaining = self._separate_at_paren(arg_str)
  636             else:
  637                 arg_str, remaining = None, arg_str
  638 
  639             def assertion(cndn, msg):
  640                 """ assert, but without risk of getting optimized out """
  641                 if not cndn:
  642                     memb = member
  643                     raise self.Exception('{member} {msg}'.format(**locals()), expr=expr)
  644 
  645             def eval_method():
  646                 if (variable, member) == ('console', 'debug'):
  647                     return
  648                 types = {
  649                     'String': compat_str,
  650                     'Math': float,
  651                 }
  652                 obj = local_vars.get(variable)
  653                 if obj in (JS_Undefined, None):
  654                     obj = types.get(variable, JS_Undefined)
  655                 if obj is JS_Undefined:
  656                     try:
  657                         if variable not in self._objects:
  658                             self._objects[variable] = self.extract_object(variable)
  659                         obj = self._objects[variable]
  660                     except self.Exception:
  661                         if not nullish:
  662                             raise
  663 
  664                 if nullish and obj is JS_Undefined:
  665                     return JS_Undefined
  666 
  667                 # Member access
  668                 if arg_str is None:
  669                     return self._index(obj, member, nullish)
  670 
  671                 # Function call
  672                 argvals = [
  673                     self.interpret_expression(v, local_vars, allow_recursion)
  674                     for v in self._separate(arg_str)]
  675 
  676                 if obj == compat_str:
  677                     if member == 'fromCharCode':
  678                         assertion(argvals, 'takes one or more arguments')
  679                         return ''.join(map(chr, argvals))
  680                     raise self.Exception('Unsupported string method ' + member, expr=expr)
  681                 elif obj == float:
  682                     if member == 'pow':
  683                         assertion(len(argvals) == 2, 'takes two arguments')
  684                         return argvals[0] ** argvals[1]
  685                     raise self.Exception('Unsupported Math method ' + member, expr=expr)
  686 
  687                 if member == 'split':
  688                     assertion(argvals, 'takes one or more arguments')
  689                     assertion(len(argvals) == 1, 'with limit argument is not implemented')
  690                     return obj.split(argvals[0]) if argvals[0] else list(obj)
  691                 elif member == 'join':
  692                     assertion(isinstance(obj, list), 'must be applied on a list')
  693                     assertion(len(argvals) == 1, 'takes exactly one argument')
  694                     return argvals[0].join(obj)
  695                 elif member == 'reverse':
  696                     assertion(not argvals, 'does not take any arguments')
  697                     obj.reverse()
  698                     return obj
  699                 elif member == 'slice':
  700                     assertion(isinstance(obj, list), 'must be applied on a list')
  701                     assertion(len(argvals) == 1, 'takes exactly one argument')
  702                     return obj[argvals[0]:]
  703                 elif member == 'splice':
  704                     assertion(isinstance(obj, list), 'must be applied on a list')
  705                     assertion(argvals, 'takes one or more arguments')
  706                     index, howMany = map(int, (argvals + [len(obj)])[:2])
  707                     if index < 0:
  708                         index += len(obj)
  709                     add_items = argvals[2:]
  710                     res = []
  711                     for i in range(index, min(index + howMany, len(obj))):
  712                         res.append(obj.pop(index))
  713                     for i, item in enumerate(add_items):
  714                         obj.insert(index + i, item)
  715                     return res
  716                 elif member == 'unshift':
  717                     assertion(isinstance(obj, list), 'must be applied on a list')
  718                     assertion(argvals, 'takes one or more arguments')
  719                     for item in reversed(argvals):
  720                         obj.insert(0, item)
  721                     return obj
  722                 elif member == 'pop':
  723                     assertion(isinstance(obj, list), 'must be applied on a list')
  724                     assertion(not argvals, 'does not take any arguments')
  725                     if not obj:
  726                         return
  727                     return obj.pop()
  728                 elif member == 'push':
  729                     assertion(argvals, 'takes one or more arguments')
  730                     obj.extend(argvals)
  731                     return obj
  732                 elif member == 'forEach':
  733                     assertion(argvals, 'takes one or more arguments')
  734                     assertion(len(argvals) <= 2, 'takes at-most 2 arguments')
  735                     f, this = (argvals + [''])[:2]
  736                     return [f((item, idx, obj), {'this': this}, allow_recursion) for idx, item in enumerate(obj)]
  737                 elif member == 'indexOf':
  738                     assertion(argvals, 'takes one or more arguments')
  739                     assertion(len(argvals) <= 2, 'takes at-most 2 arguments')
  740                     idx, start = (argvals + [0])[:2]
  741                     try:
  742                         return obj.index(idx, start)
  743                     except ValueError:
  744                         return -1
  745                 elif member == 'charCodeAt':
  746                     assertion(isinstance(obj, compat_str), 'must be applied on a string')
  747                     # assertion(len(argvals) == 1, 'takes exactly one argument') # but not enforced
  748                     idx = argvals[0] if isinstance(argvals[0], int) else 0
  749                     if idx >= len(obj):
  750                         return None
  751                     return ord(obj[idx])
  752 
  753                 idx = int(member) if isinstance(obj, list) else member
  754                 return obj[idx](argvals, allow_recursion=allow_recursion)
  755 
  756             if remaining:
  757                 ret, should_abort = self.interpret_statement(
  758                     self._named_object(local_vars, eval_method()) + remaining,
  759                     local_vars, allow_recursion)
  760                 return ret, should_return or should_abort
  761             else:
  762                 return eval_method(), should_return
  763 
  764         elif md.get('function'):
  765             fname = m.group('fname')
  766             argvals = [self.interpret_expression(v, local_vars, allow_recursion)
  767                        for v in self._separate(m.group('args'))]
  768             if fname in local_vars:
  769                 return local_vars[fname](argvals, allow_recursion=allow_recursion), should_return
  770             elif fname not in self._functions:
  771                 self._functions[fname] = self.extract_function(fname)
  772             return self._functions[fname](argvals, allow_recursion=allow_recursion), should_return
  773 
  774         raise self.Exception(
  775             'Unsupported JS expression ' + (expr[:40] if expr != stmt else ''), expr=stmt)
  776 
  777     def interpret_expression(self, expr, local_vars, allow_recursion):
  778         ret, should_return = self.interpret_statement(expr, local_vars, allow_recursion)
  779         if should_return:
  780             raise self.Exception('Cannot return from an expression', expr)
  781         return ret
  782 
  783     def extract_object(self, objname):
  784         _FUNC_NAME_RE = r'''(?:[a-zA-Z$0-9]+|"[a-zA-Z$0-9]+"|'[a-zA-Z$0-9]+')'''
  785         obj = {}
  786         obj_m = re.search(
  787             r'''(?x)
  788                 (?<!this\.)%s\s*=\s*{\s*
  789                     (?P<fields>(%s\s*:\s*function\s*\(.*?\)\s*{.*?}(?:,\s*)?)*)
  790                 }\s*;
  791             ''' % (re.escape(objname), _FUNC_NAME_RE),
  792             self.code)
  793         if not obj_m:
  794             raise self.Exception('Could not find object ' + objname)
  795         fields = obj_m.group('fields')
  796         # Currently, it only supports function definitions
  797         fields_m = re.finditer(
  798             r'''(?x)
  799                 (?P<key>%s)\s*:\s*function\s*\((?P<args>(?:%s|,)*)\){(?P<code>[^}]+)}
  800             ''' % (_FUNC_NAME_RE, _NAME_RE),
  801             fields)
  802         for f in fields_m:
  803             argnames = self.build_arglist(f.group('args'))
  804             obj[remove_quotes(f.group('key'))] = self.build_function(argnames, f.group('code'))
  805 
  806         return obj
  807 
  808     def extract_function_code(self, funcname):
  809         """ @returns argnames, code """
  810         func_m = re.search(
  811             r'''(?xs)
  812                 (?:
  813                     function\s+%(name)s|
  814                     [{;,]\s*%(name)s\s*=\s*function|
  815                     (?:var|const|let)\s+%(name)s\s*=\s*function
  816                 )\s*
  817                 \((?P<args>[^)]*)\)\s*
  818                 (?P<code>{.+})''' % {'name': re.escape(funcname)},
  819             self.code)
  820         code, _ = self._separate_at_paren(func_m.group('code'))  # refine the match
  821         if func_m is None:
  822             raise self.Exception('Could not find JS function "{funcname}"'.format(**locals()))
  823         return self.build_arglist(func_m.group('args')), code
  824 
  825     def extract_function(self, funcname):
  826         return self.extract_function_from_code(*self.extract_function_code(funcname))
  827 
  828     def extract_function_from_code(self, argnames, code, *global_stack):
  829         local_vars = {}
  830         while True:
  831             mobj = re.search(r'function\((?P<args>[^)]*)\)\s*{', code)
  832             if mobj is None:
  833                 break
  834             start, body_start = mobj.span()
  835             body, remaining = self._separate_at_paren(code[body_start - 1:], '}')
  836             name = self._named_object(local_vars, self.extract_function_from_code(
  837                 [x.strip() for x in mobj.group('args').split(',')],
  838                 body, local_vars, *global_stack))
  839             code = code[:start] + name + remaining
  840         return self.build_function(argnames, code, local_vars, *global_stack)
  841 
  842     def call_function(self, funcname, *args):
  843         return self.extract_function(funcname)(args)
  844 
  845     @classmethod
  846     def build_arglist(cls, arg_text):
  847         if not arg_text:
  848             return []
  849 
  850         def valid_arg(y):
  851             y = y.strip()
  852             if not y:
  853                 raise cls.Exception('Missing arg in "%s"' % (arg_text, ))
  854             return y
  855 
  856         return [valid_arg(x) for x in cls._separate(arg_text)]
  857 
  858     def build_function(self, argnames, code, *global_stack):
  859         global_stack = list(global_stack) or [{}]
  860         argnames = tuple(argnames)
  861 
  862         def resf(args, kwargs={}, allow_recursion=100):
  863             global_stack[0].update(
  864                 zip_longest(argnames, args, fillvalue=None))
  865             global_stack[0].update(kwargs)
  866             var_stack = LocalNameSpace(*global_stack)
  867             ret, should_abort = self.interpret_statement(code.replace('\n', ' '), var_stack, allow_recursion - 1)
  868             if should_abort:
  869                 return ret
  870         return resf

Generated by cgit