From 6a9688ce9deb2ff92502070df581f55d621484bf Mon Sep 17 00:00:00 2001 From: yuyi Date: Wed, 18 Jan 2023 15:22:38 +0800 Subject: [PATCH] checker, cgen: fix `for mut i in arr { i = i * i }` (#17020) --- vlib/v/checker/infix.v | 2 +- vlib/v/gen/c/infix.v | 7 ++++++- vlib/v/tests/for_in_mut_array_with_mul_test.v | 8 ++++++++ 3 files changed, 15 insertions(+), 2 deletions(-) create mode 100644 vlib/v/tests/for_in_mut_array_with_mul_test.v diff --git a/vlib/v/checker/infix.v b/vlib/v/checker/infix.v index 9566cb44bd16f7..d0279fcf2bd9d0 100644 --- a/vlib/v/checker/infix.v +++ b/vlib/v/checker/infix.v @@ -69,7 +69,7 @@ fn (mut c Checker) infix_expr(mut node ast.InfixExpr) ast.Type { c.error('invalid number of operand for `${node.op}`. Only one allowed on each side.', left_right_pos) } - if left_type.is_any_kind_of_pointer() + if left_type.is_any_kind_of_pointer() && !node.left.is_auto_deref_var() && node.op in [.plus, .minus, .mul, .div, .mod, .xor, .amp, .pipe] { if !c.pref.translated && ((right_type.is_any_kind_of_pointer() && node.op != .minus) || (!right_type.is_any_kind_of_pointer() && node.op !in [.plus, .minus])) { diff --git a/vlib/v/gen/c/infix.v b/vlib/v/gen/c/infix.v index 6ff4725ed62965..cbd8a4ba6f586b 100644 --- a/vlib/v/gen/c/infix.v +++ b/vlib/v/gen/c/infix.v @@ -966,7 +966,12 @@ fn (mut g Gen) gen_plain_infix_expr(node ast.InfixExpr) { } g.expr(node.left) g.write(' ${node.op.str()} ') - g.expr_with_cast(node.right, node.right_type, node.left_type) + if node.right_type.is_ptr() && node.right.is_auto_deref_var() { + g.write('*') + g.expr(node.right) + } else { + g.expr_with_cast(node.right, node.right_type, node.left_type) + } } fn (mut g Gen) op_arg(expr ast.Expr, expected ast.Type, got ast.Type) { diff --git a/vlib/v/tests/for_in_mut_array_with_mul_test.v b/vlib/v/tests/for_in_mut_array_with_mul_test.v new file mode 100644 index 00000000000000..1dd0a9f65c4893 --- /dev/null +++ b/vlib/v/tests/for_in_mut_array_with_mul_test.v @@ -0,0 +1,8 @@ +fn test_for_in_mut_array_with_mul() { + mut ints_a := [1, 2] + for mut i in ints_a { + i = i * i + } + print('${ints_a}') + assert ints_a == [1, 4] +}