From 479bfa28de17f2494bf2291d855ab0d27d326a49 Mon Sep 17 00:00:00 2001 From: Nick Treleaven Date: Tue, 25 Aug 2020 07:48:28 +0100 Subject: [PATCH] cgen: implement fixed array `.len` property (#6212) --- vlib/v/ast/ast.v | 2 +- vlib/v/checker/checker.v | 2 +- vlib/v/gen/cgen.v | 7 +++++++ vlib/v/tests/fixed_array_test.v | 4 +++- 4 files changed, 12 insertions(+), 3 deletions(-) diff --git a/vlib/v/ast/ast.v b/vlib/v/ast/ast.v index d8243e79c4..9ef18e2887 100644 --- a/vlib/v/ast/ast.v +++ b/vlib/v/ast/ast.v @@ -106,7 +106,7 @@ pub: pub struct SelectorExpr { pub: pos token.Position - expr Expr + expr Expr // expr.field_name field_name string pub mut: expr_type table.Type // type of `Foo` in `Foo.bar` diff --git a/vlib/v/checker/checker.v b/vlib/v/checker/checker.v index b3fff38ea0..ff01021029 100644 --- a/vlib/v/checker/checker.v +++ b/vlib/v/checker/checker.v @@ -1470,7 +1470,7 @@ pub fn (mut c Checker) selector_expr(mut selector_expr ast.SelectorExpr) table.T sym := c.table.get_type_symbol(c.unwrap_generic(typ)) field_name := selector_expr.field_name // variadic - if typ.has_flag(.variadic) { + if typ.has_flag(.variadic) || sym.kind == .array_fixed { if field_name == 'len' { selector_expr.typ = table.int_type return table.int_type diff --git a/vlib/v/gen/cgen.v b/vlib/v/gen/cgen.v index 259ea6b649..e3df4b88db 100644 --- a/vlib/v/gen/cgen.v +++ b/vlib/v/gen/cgen.v @@ -2100,6 +2100,13 @@ fn (mut g Gen) expr(node ast.Expr) { g.struct_init(node) } ast.SelectorExpr { + sym := g.table.get_type_symbol(node.expr_type) + if sym.kind == .array_fixed { + assert node.field_name == 'len' + info := sym.info as table.ArrayFixed + g.write('$info.size') + return + } g.expr(node.expr) if node.expr_type.is_ptr() { g.write('->') diff --git a/vlib/v/tests/fixed_array_test.v b/vlib/v/tests/fixed_array_test.v index f54e1673ba..11fa7f128b 100644 --- a/vlib/v/tests/fixed_array_test.v +++ b/vlib/v/tests/fixed_array_test.v @@ -11,7 +11,7 @@ fn test_fixed_array_can_be_assigned() { v = [8]f64{} assert v[1] == 0 // test slicing - for e in v[0..8] { + for e in v[0..v.len] { assert e == 0 } v = [8]f64{init: 3.0} @@ -21,6 +21,7 @@ fn test_fixed_array_can_be_assigned() { fn test_fixed_array_can_be_used_in_declaration() { x := 2.32 v := [1.0, x, 3.0,4.0,5.0,6.0,7.0,8.0]!! + assert v.len == 8 assert v[1] == x } @@ -32,6 +33,7 @@ struct Context { fn test_fixed_array_can_be_assigned_to_a_struct_field() { mut ctx := Context{} + assert ctx.vb.len == 8 x := 2.32 ctx.vb = [1.1, x, 3.3, 4.4, 5.0, 6.0, 7.0, 8.9]!! assert ctx.vb[1] == x