diff --git a/custom_components/pyscript/eval.py b/custom_components/pyscript/eval.py index 281de59..17ebc94 100644 --- a/custom_components/pyscript/eval.py +++ b/custom_components/pyscript/eval.py @@ -529,6 +529,36 @@ def special_method(*args, **kwargs): return special_method +# the SyntaxError message for break or continue outside a loop, as in Python +STOP_FLOW_OUTSIDE_LOOP = { + "break": "'break' outside loop", + "continue": "'continue' not properly in loop", +} + + +def unbound_local_msg(name): + """Return Python's message for reading or deleting a local variable that has no value.""" + return f"cannot access local variable '{name}' where it is not associated with a value" + + +def unbound_free_msg(name): + """Return Python's message for reading or deleting an enclosing function's variable that has no value.""" + return f"cannot access free variable '{name}' where it is not associated with a value in enclosing scope" + + +def plural(items): + """Return "s" unless items has exactly one element, for messages that count them.""" + return "" if len(items) == 1 else "s" + + +def quoted_names(names): + """Quote and join argument names as Python's errors do: 'a', 'a' and 'b', or 'a', 'b', and 'c'.""" + quoted = [f"'{name}'" for name in names] + if len(quoted) <= 2: + return " and ".join(quoted) + return ", ".join(quoted[:-1]) + ", and " + quoted[-1] + + class EvalName: """Identifier that hasn't yet been resolved.""" @@ -720,6 +750,7 @@ async def call(self, ast_ctx, /, *args, **kwargs): args = [] kwargs = kwargs.copy() if kwargs else {} bad_kwargs = [] + missing = [] has_var_kwargs = self.func_def.args.kwarg is not None for i, func_def_arg in enumerate(self.func_def.args.posonlyargs + self.func_def.args.args): var_name = func_def_arg.arg @@ -738,31 +769,42 @@ async def call(self, ast_ctx, /, *args, **kwargs): elif self.num_posn_arg <= i < len(self.defaults) + self.num_posn_arg: val = self.defaults[i - self.num_posn_arg] else: - raise TypeError( - f"{self.name}() missing {self.num_posn_arg - i} required positional arguments" - ) + missing.append(var_name) + continue sym_table[var_name] = val if len(bad_kwargs) > 0: raise TypeError( f"{self.name}() got some positional-only arguments passed as keyword arguments: '{', '.join(bad_kwargs)}'" ) + if missing: + raise TypeError( + f"{self.name}() missing {len(missing)} required positional argument{plural(missing)}: " + f"{quoted_names(missing)}" + ) + num_kwonly_given = 0 for i, kwonlyarg in enumerate(self.func_def.args.kwonlyargs): var_name = kwonlyarg.arg if var_name in kwargs: val = kwargs[var_name] del kwargs[var_name] + num_kwonly_given += 1 elif i < len(self.kw_defaults) and self.kw_defaults[i]["ok"]: val = self.kw_defaults[i]["val"] else: - raise TypeError(f"{self.name}() missing required keyword-only arguments") + missing.append(var_name) + continue sym_table[var_name] = val + if missing: + raise TypeError( + f"{self.name}() missing {len(missing)} required keyword-only argument{plural(missing)}: " + f"{quoted_names(missing)}" + ) if self.func_def.args.kwarg: sym_table[self.func_def.args.kwarg.arg] = kwargs elif kwargs: - if unexpected := set(kwargs) - TRIGGER_KWARGS: - unexpected_str = ", ".join(sorted(unexpected)) - raise TypeError(f"{self.name}() called with unexpected keyword arguments: {unexpected_str}") + if unexpected := [name for name in kwargs if name not in TRIGGER_KWARGS]: + raise TypeError(f"{self.name}() got an unexpected keyword argument '{unexpected[0]}'") # Unexpected keyword arguments named in TRIGGER_KWARGS are still ignored in any call; # decorator wrappers rely on it to pass trigger kwargs on via **kwargs. # Deprecated: this will become a TypeError, as in Python. See @@ -785,7 +827,18 @@ async def call(self, ast_ctx, /, *args, **kwargs): else: sym_table[self.func_def.args.vararg.arg] = () elif len(args) > num_posn: - raise TypeError(f"{self.name}() called with too many positional arguments") + if self.defaults: + takes = f"from {num_posn - len(self.defaults)} to {num_posn} positional arguments" + else: + takes = f"{num_posn} positional argument{plural(range(num_posn))}" + given = f"{len(args)}" + if num_kwonly_given: + given += ( + f" positional argument{plural(args)} (and {num_kwonly_given}" + f" keyword-only argument{plural(range(num_kwonly_given))})" + ) + was = "was" if len(args) == 1 and not num_kwonly_given else "were" + raise TypeError(f"{self.name}() takes {takes} but {given} {was} given") for name, value in self.local_sym_table.items(): if name in sym_table: sym_table[name] = EvalLocalVar(name, sym_table[name]) @@ -990,9 +1043,9 @@ async def ast_module(self, arg): for arg1 in arg.body: val = await self.aeval(arg1) if isinstance(val, EvalReturn): - raise SyntaxError(f"{val.name()} statement outside function") + raise SyntaxError(f"'{val.name()}' outside function") if isinstance(val, EvalStopFlow): - raise SyntaxError(f"{val.name()} statement outside loop") + raise SyntaxError(STOP_FLOW_OUTSIDE_LOOP[val.name()]) return val async def ast_import(self, arg): @@ -1133,9 +1186,9 @@ async def ast_classdef(self, arg): for arg1 in arg.body: val = await self.aeval(arg1) if isinstance(val, EvalReturn): - raise SyntaxError(f"{val.name()} statement outside function") + raise SyntaxError(f"'{val.name()}' outside function") if isinstance(val, EvalStopFlow): - raise SyntaxError(f"{val.name()} statement outside loop") + raise SyntaxError(STOP_FLOW_OUTSIDE_LOOP[val.name()]) finally: # restore the enclosing scope even if the class body raises and the exception is caught self.class_sym_table = prev_class_sym_table @@ -1547,7 +1600,7 @@ async def ast_global(self, arg): async def ast_nonlocal(self, arg): """Execute nonlocal statement.""" if not self.curr_func: - raise SyntaxError("nonlocal statement outside function") + raise SyntaxError("nonlocal declaration not allowed at module level") for var_name in arg.names: self.curr_func.nonlocal_names.add(var_name) @@ -1555,9 +1608,10 @@ async def recurse_assign(self, lhs, val): """Recursive assignment.""" if isinstance(lhs, ast.Tuple): try: - vals = [*(iter(val))] - except Exception: - raise TypeError("cannot unpack non-iterable object") # pylint: disable=raise-missing-from + vals_iter = iter(val) + except TypeError: + raise TypeError(f"cannot unpack non-iterable {type(val).__name__} object") from None + vals = [*vals_iter] got_star = 0 for lhs_elt in lhs.elts: if isinstance(lhs_elt, ast.Starred): @@ -1568,9 +1622,11 @@ async def recurse_assign(self, lhs, val): err_msg = f"at least {len(lhs.elts) - got_star}" else: err_msg = f"{len(lhs.elts)}" - raise ValueError(f"too few values to unpack (expected {err_msg})") + raise ValueError(f"not enough values to unpack (expected {err_msg}, got {len(vals)})") if len(lhs.elts) < len(vals) and got_star == 0: - raise ValueError(f"too many values to unpack (expected {len(lhs.elts)})") + # as in Python, the count is given only for a list, tuple or dict + got = f", got {len(vals)}" if type(val) in (list, tuple, dict) else "" + raise ValueError(f"too many values to unpack (expected {len(lhs.elts)}{got})") val_idx = 0 for lhs_elt in lhs.elts: if isinstance(lhs_elt, ast.Starred): @@ -1711,6 +1767,10 @@ async def ast_delete(self, arg): if isinstance(self.sym_table[arg1.id], EvalLocalVar): if self.sym_table[arg1.id].is_defined(): self.sym_table[arg1.id].set_undefined() + elif self.curr_func and arg1.id in self.curr_func.nonlocal_names: + raise NameError(unbound_free_msg(arg1.id)) + elif self.curr_func and arg1.id in self.curr_func.local_names: + raise UnboundLocalError(unbound_local_msg(arg1.id)) else: raise NameError(f"name '{arg1.id}' is not defined") else: @@ -1803,7 +1863,7 @@ async def ast_name(self, arg): return val.get() if isinstance(val, EvalLocalVar) else val if arg.id in self.global_sym_table: return self.global_sym_table[arg.id] - raise NameError(f"global name '{arg.id}' is not defined") + raise NameError(f"name '{arg.id}' is not defined") # # now check in our current symbol table, and then some other places # @@ -1825,14 +1885,14 @@ async def ast_name(self, arg): and arg.id in self.curr_func.local_names ) if is_local: - raise UnboundLocalError(f"local variable '{arg.id}' referenced before assignment") - return val.get() + raise UnboundLocalError(unbound_local_msg(arg.id)) + raise NameError(unbound_free_msg(arg.id)) return val if arg.id in self.local_sym_table: return self.local_sym_table[arg.id] if arg.id in self.global_sym_table: if self.curr_func and arg.id in self.curr_func.local_names: - raise UnboundLocalError(f"local variable '{arg.id}' referenced before assignment") + raise UnboundLocalError(unbound_local_msg(arg.id)) return self.global_sym_table[arg.id] if arg.id in BUILTIN_AST_FUNCS_FACTORY: return BUILTIN_AST_FUNCS_FACTORY[arg.id](self) diff --git a/tests/test_unit_eval.py b/tests/test_unit_eval.py index c610c8a..d3c758d 100644 --- a/tests/test_unit_eval.py +++ b/tests/test_unit_eval.py @@ -2191,15 +2191,24 @@ class ED: ["1+", ED(SyntaxError, "invalid syntax (test, line 1)", col_offset=2, end_col_offset=3)], ["1+'x'", ED(TypeError, "unsupported operand type(s) for +: 'int' and 'str'", end_col_offset=5)], ["xx", ED(NameError, "name 'xx' is not defined", end_col_offset=2)], - ["(x, y) = (1, 2, 4)", ED(ValueError, "too many values to unpack (expected 2)", end_col_offset=6)], + [ + "(x, y) = (1, 2, 4)", + ED(ValueError, "too many values to unpack (expected 2, got 3)", end_col_offset=6), + ], ["(x, y) = iter([1, 2, 4])", ED(ValueError, "too many values to unpack (expected 2)", end_col_offset=6)], - ["(x, y, z) = (1, 2)", ED(ValueError, "too few values to unpack (expected 3)", end_col_offset=9)], - ["(x, y, z) = iter([1, 2])", ED(ValueError, "too few values to unpack (expected 3)", end_col_offset=9)], - ["(x, y) = 1", ED(TypeError, "cannot unpack non-iterable object", end_col_offset=6)], + [ + "(x, y, z) = (1, 2)", + ED(ValueError, "not enough values to unpack (expected 3, got 2)", end_col_offset=9), + ], + [ + "(x, y, z) = iter([1, 2])", + ED(ValueError, "not enough values to unpack (expected 3, got 2)", end_col_offset=9), + ], + ["(x, y) = 1", ED(TypeError, "cannot unpack non-iterable int object", end_col_offset=6)], ["x: int; x", ED(NameError, "name 'x' is not defined", col_offset=8, end_col_offset=9)], [ "a, *y, w, z = range(2)", - ED(ValueError, "too few values to unpack (expected at least 3)", end_col_offset=11), + ED(ValueError, "not enough values to unpack (expected at least 3, got 2)", end_col_offset=11), ], ["assert 1 == 0, 'this is an error'", ED(AssertionError, "this is an error", end_col_offset=33)], ["assert 1 == 0", ED(AssertionError, "", end_col_offset=13)], @@ -2227,13 +2236,13 @@ class ED: "pyscript.var1 = 1; state.delete('pyscript.var1'); pyscript.var1", ED(NameError, "name 'pyscript.var1' is not defined", col_offset=50, end_col_offset=63), ], - ["return", ED(SyntaxError, "return statement outside function")], - ["break", ED(SyntaxError, "break statement outside loop")], + ["return", ED(SyntaxError, "'return' outside function")], + ["break", ED(SyntaxError, "'break' outside loop")], [ "i = 1; break; i = 1/0", - ED(SyntaxError, "break statement outside loop"), + ED(SyntaxError, "'break' outside loop"), ], - ["continue", ED(SyntaxError, "continue statement outside loop")], + ["continue", ED(SyntaxError, "'continue' not properly in loop")], ["raise", ED(RuntimeError, "No active exception to reraise", end_col_offset=5)], ["yield", ED(NotImplementedError, "test: not implemented ast ast_yield", end_col_offset=5)], ["task.executor(5)", ED(TypeError, "function 5 is not callable by task.executor", end_col_offset=16)], @@ -2262,11 +2271,11 @@ class ED: ["func1(1)", ED(NameError, "name 'func1' is not defined", end_col_offset=5)], [ "def func(a):\n pass\nfunc()", - ED(TypeError, "func() missing 1 required positional arguments", lineno=3, end_col_offset=6), + ED(TypeError, "func() missing 1 required positional argument: 'a'", lineno=3, end_col_offset=6), ], [ "def func(a):\n pass\nfunc(1, 2)", - ED(TypeError, "func() called with too many positional arguments", lineno=3, end_col_offset=10), + ED(TypeError, "func() takes 1 positional argument but 2 were given", lineno=3, end_col_offset=10), ], [ "def func(a=1):\n pass\nfunc(1, a=3)", @@ -2274,7 +2283,7 @@ class ED: ], [ "def func(*a, b):\n pass\nfunc(1, 2)", - ED(TypeError, "func() missing required keyword-only arguments", lineno=3, end_col_offset=10), + ED(TypeError, "func() missing 1 required keyword-only argument: 'b'", lineno=3, end_col_offset=10), ], [ """ @@ -2283,7 +2292,7 @@ def func(b=1): func(a=2, trigger_type=1) """, - ED(TypeError, "func() called with unexpected keyword arguments: a", lineno=5, end_col_offset=25), + ED(TypeError, "func() got an unexpected keyword argument 'a'", lineno=5, end_col_offset=25), ], [ """ @@ -2317,7 +2326,7 @@ def f(x, /, **kw): return [x, kw] f(x=4) """, - ED(TypeError, "f() missing 1 required positional arguments", lineno=4, end_col_offset=6), + ED(TypeError, "f() missing 1 required positional argument: 'x'", lineno=4, end_col_offset=6), ], [ "from .xyz import abc", @@ -2362,7 +2371,7 @@ def func(): return x func() """, - ED(NameError, "global name 'x' is not defined", lineno=4, col_offset=11, end_col_offset=12), + ED(NameError, "name 'x' is not defined", lineno=4, col_offset=11, end_col_offset=12), ], [ """ @@ -2392,7 +2401,7 @@ def func(): """, ED( UnboundLocalError, - "local variable 'x' referenced before assignment", + "cannot access local variable 'x' where it is not associated with a value", lineno=4, col_offset=4, end_col_offset=5, @@ -2409,7 +2418,13 @@ def func2(): func2() func() """, - ED(NameError, "name 'x' is not defined", lineno=6, col_offset=8, end_col_offset=13), + ED( + NameError, + "cannot access free variable 'x' where it is not associated with a value in enclosing scope", + lineno=6, + col_offset=8, + end_col_offset=13, + ), ], [ """ @@ -2424,7 +2439,7 @@ def func2(): """, ED( UnboundLocalError, - "local variable 'x' referenced before assignment", + "cannot access local variable 'x' where it is not associated with a value", lineno=4, col_offset=12, end_col_offset=13,