cgen: implement fixed array `.len` property (#6212)

pull/6219/head
Nick Treleaven 2020-08-25 07:48:28 +01:00 committed by GitHub
parent 8e4ee54070
commit 479bfa28de
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
4 changed files with 12 additions and 3 deletions

View File

@ -106,7 +106,7 @@ pub:
pub struct SelectorExpr { pub struct SelectorExpr {
pub: pub:
pos token.Position pos token.Position
expr Expr expr Expr // expr.field_name
field_name string field_name string
pub mut: pub mut:
expr_type table.Type // type of `Foo` in `Foo.bar` expr_type table.Type // type of `Foo` in `Foo.bar`

View File

@ -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)) sym := c.table.get_type_symbol(c.unwrap_generic(typ))
field_name := selector_expr.field_name field_name := selector_expr.field_name
// variadic // variadic
if typ.has_flag(.variadic) { if typ.has_flag(.variadic) || sym.kind == .array_fixed {
if field_name == 'len' { if field_name == 'len' {
selector_expr.typ = table.int_type selector_expr.typ = table.int_type
return table.int_type return table.int_type

View File

@ -2100,6 +2100,13 @@ fn (mut g Gen) expr(node ast.Expr) {
g.struct_init(node) g.struct_init(node)
} }
ast.SelectorExpr { 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) g.expr(node.expr)
if node.expr_type.is_ptr() { if node.expr_type.is_ptr() {
g.write('->') g.write('->')

View File

@ -11,7 +11,7 @@ fn test_fixed_array_can_be_assigned() {
v = [8]f64{} v = [8]f64{}
assert v[1] == 0 assert v[1] == 0
// test slicing // test slicing
for e in v[0..8] { for e in v[0..v.len] {
assert e == 0 assert e == 0
} }
v = [8]f64{init: 3.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() { fn test_fixed_array_can_be_used_in_declaration() {
x := 2.32 x := 2.32
v := [1.0, x, 3.0,4.0,5.0,6.0,7.0,8.0]!! v := [1.0, x, 3.0,4.0,5.0,6.0,7.0,8.0]!!
assert v.len == 8
assert v[1] == x assert v[1] == x
} }
@ -32,6 +33,7 @@ struct Context {
fn test_fixed_array_can_be_assigned_to_a_struct_field() { fn test_fixed_array_can_be_assigned_to_a_struct_field() {
mut ctx := Context{} mut ctx := Context{}
assert ctx.vb.len == 8
x := 2.32 x := 2.32
ctx.vb = [1.1, x, 3.3, 4.4, 5.0, 6.0, 7.0, 8.9]!! ctx.vb = [1.1, x, 3.3, 4.4, 5.0, 6.0, 7.0, 8.9]!!
assert ctx.vb[1] == x assert ctx.vb[1] == x