Explorar o código

[JSInterp] Improve indexing
* catch invalid list index with `ValueError` (eg [1, 2]['ab'] -> undefined)
* allow assignment outside existing list (eg var l = [1,2]; l[9] = 0;)

dirkf hai 5 meses
pai
achega
a4fc1151f1
Modificáronse 1 ficheiros con 5 adicións e 1 borrados
  1. 5 1
      youtube_dl/jsinterp.py

+ 5 - 1
youtube_dl/jsinterp.py

@@ -678,7 +678,7 @@ class JSInterpreter(object):
             return len(obj)
             return len(obj)
         try:
         try:
             return obj[int(idx)] if isinstance(obj, list) else obj[compat_str(idx)]
             return obj[int(idx)] if isinstance(obj, list) else obj[compat_str(idx)]
-        except (TypeError, KeyError, IndexError) as e:
+        except (TypeError, KeyError, IndexError, ValueError) as e:
             # allow_undefined is None gives correct behaviour
             # allow_undefined is None gives correct behaviour
             if allow_undefined or (
             if allow_undefined or (
                     allow_undefined is None and not isinstance(e, TypeError)):
                     allow_undefined is None and not isinstance(e, TypeError)):
@@ -1038,6 +1038,10 @@ class JSInterpreter(object):
                     left_val = self._index(left_val, idx)
                     left_val = self._index(left_val, idx)
             if isinstance(idx, float):
             if isinstance(idx, float):
                 idx = int(idx)
                 idx = int(idx)
+            if isinstance(left_val, list) and len(left_val) <= int_or_none(idx, default=-1):
+                # JS Array is a sparsely assignable list
+                # TODO: handle extreme sparsity without memory bloat, eg using auxiliary dict
+                left_val.extend((idx - len(left_val) + 1) * [JS_Undefined])
             left_val[idx] = self._operator(
             left_val[idx] = self._operator(
                 m.group('op'), self._index(left_val, idx) if m.group('op') else None,
                 m.group('op'), self._index(left_val, idx) if m.group('op') else None,
                 m.group('expr'), expr, local_vars, allow_recursion)
                 m.group('expr'), expr, local_vars, allow_recursion)