From d8b8aca51e519c8b99e54e9c9900e2c27b8d719f Mon Sep 17 00:00:00 2001 From: Enzo Date: Wed, 2 Dec 2020 04:35:00 +0100 Subject: [PATCH] gen: fix `arr.last().field` (#7076) --- vlib/builtin/array_test.v | 21 +++++++++++++++++++++ vlib/v/gen/fn.v | 7 ++++++- 2 files changed, 27 insertions(+), 1 deletion(-) diff --git a/vlib/builtin/array_test.v b/vlib/builtin/array_test.v index b01f5d9fc6..af3e258988 100644 --- a/vlib/builtin/array_test.v +++ b/vlib/builtin/array_test.v @@ -1002,6 +1002,27 @@ fn test_array_string_pop() { assert a.cap == 3 } +fn test_array_first() { + a := [3] + assert a.first() == 3 + b := [1, 2, 3, 4] + assert b.first() == 1 + c := ['abc', 'def'] + assert c.first()[0] == `a` + s := [Chunk{'a'}] + assert s.first().val == 'a' +} + +fn test_array_last() { + a := [3] + assert a.last() == 3 + b := [1, 2, 3, 4] + assert b.last() == 4 + c := ['abc', 'def'] + assert c.last()[0] == `d` + s := [Chunk{'a'}] + assert s.last().val == 'a' +} [direct_array_access] fn test_direct_array_access() { diff --git a/vlib/v/gen/fn.v b/vlib/v/gen/fn.v index 247a69502f..6356b69e2d 100644 --- a/vlib/v/gen/fn.v +++ b/vlib/v/gen/fn.v @@ -365,6 +365,7 @@ fn (mut g Gen) method_call(node ast.CallExpr) { if node.name == 'str' { g.gen_str_for_type(node.receiver_type) } + mut has_cast := false // TODO performance, detect `array` method differently if left_sym.kind == .array && node.name in ['repeat', 'sort_with_compare', 'free', 'push_many', 'trim', 'first', 'last', 'pop', 'clone', 'reverse', 'slice'] { @@ -374,7 +375,8 @@ fn (mut g Gen) method_call(node ast.CallExpr) { receiver_type_name = 'array' if node.name in ['last', 'first', 'pop'] { return_type_str := g.typ(node.return_type) - g.write('*($return_type_str*)') + has_cast = true + g.write('(*($return_type_str*)') } } mut name := util.no_dots('${receiver_type_name}_$node.name') @@ -428,6 +430,9 @@ fn (mut g Gen) method_call(node ast.CallExpr) { } else { g.expr(node.left) } + if has_cast { + g.write(')') + } is_variadic := node.expected_arg_types.len > 0 && node.expected_arg_types[node.expected_arg_types.len - 1].has_flag(.variadic) if node.args.len > 0 || is_variadic {