From 8543d5e055ff16dfda1a23ce18bfa84f654b4add Mon Sep 17 00:00:00 2001 From: Vincenzo Palazzo Date: Sun, 27 Nov 2022 05:07:35 +0100 Subject: [PATCH] checker: improve mut arg error msg (#16540) --- vlib/v/checker/fn.v | 7 ++++++- vlib/v/checker/tests/check_fn_init_as_mutable.out | 6 ++++++ vlib/v/checker/tests/check_fn_init_as_mutable.vv | 7 +++++++ vlib/v/checker/tests/pass_mut_lit.out | 4 ++-- 4 files changed, 21 insertions(+), 3 deletions(-) create mode 100644 vlib/v/checker/tests/check_fn_init_as_mutable.out create mode 100644 vlib/v/checker/tests/check_fn_init_as_mutable.vv diff --git a/vlib/v/checker/fn.v b/vlib/v/checker/fn.v index b4fc2765d..31e090589 100644 --- a/vlib/v/checker/fn.v +++ b/vlib/v/checker/fn.v @@ -1028,7 +1028,12 @@ fn (mut c Checker) fn_call(mut node ast.CallExpr, mut continue_check &bool) ast. if call_arg.is_mut { to_lock, pos := c.fail_if_immutable(call_arg.expr) if !call_arg.expr.is_lvalue() { - c.error('cannot pass expression as `mut`', call_arg.expr.pos()) + if call_arg.expr is ast.StructInit { + c.error('cannot pass a struct initialization as `mut`, you may want to use a variable `mut var := ${call_arg.expr}`', + call_arg.expr.pos()) + } else { + c.error('cannot pass expression as `mut`', call_arg.expr.pos()) + } } if !param.is_mut { tok := call_arg.share.str() diff --git a/vlib/v/checker/tests/check_fn_init_as_mutable.out b/vlib/v/checker/tests/check_fn_init_as_mutable.out new file mode 100644 index 000000000..f18dbcc78 --- /dev/null +++ b/vlib/v/checker/tests/check_fn_init_as_mutable.out @@ -0,0 +1,6 @@ +vlib/v/checker/tests/check_fn_init_as_mutable.vv:6:14: error: cannot pass a struct initialization as `mut`, you may want to use a variable `mut var := MyStruct{....}` + 4 | + 5 | fn main() { + 6 | process(mut MyStruct{}) + | ~~~~~~~~~~ + 7 | } diff --git a/vlib/v/checker/tests/check_fn_init_as_mutable.vv b/vlib/v/checker/tests/check_fn_init_as_mutable.vv new file mode 100644 index 000000000..3224de2b2 --- /dev/null +++ b/vlib/v/checker/tests/check_fn_init_as_mutable.vv @@ -0,0 +1,7 @@ +struct MyStruct {} + +fn process(mut ms MyStruct) {} + +fn main() { + process(mut MyStruct{}) +} diff --git a/vlib/v/checker/tests/pass_mut_lit.out b/vlib/v/checker/tests/pass_mut_lit.out index 09a03433a..a9e060af1 100644 --- a/vlib/v/checker/tests/pass_mut_lit.out +++ b/vlib/v/checker/tests/pass_mut_lit.out @@ -1,5 +1,5 @@ -vlib/v/checker/tests/pass_mut_lit.vv:10:12: error: cannot pass expression as `mut` +vlib/v/checker/tests/pass_mut_lit.vv:10:12: error: cannot pass a struct initialization as `mut`, you may want to use a variable `mut var := Box{....}` 8 | } - 9 | + 9 | 10 | modify(mut Box{}, 10) | ~~~~~ -- 2.39.5