Skip to content

Commit

Permalink
checker: check generic struct no_keys init (fix #17061) (#17067)
Browse files Browse the repository at this point in the history
  • Loading branch information
yuyi98 committed Jan 22, 2023
1 parent 3aeb617 commit 865c0ea
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 0 deletions.
9 changes: 9 additions & 0 deletions vlib/v/checker/struct.v
Original file line number Diff line number Diff line change
Expand Up @@ -387,6 +387,15 @@ fn (mut c Checker) struct_init(mut node ast.StructInit) ast.Type {
field.typ = c.expr(field.expr)
field.expected_type = field.typ
}
sym := c.table.sym(c.unwrap_generic(node.typ))
if sym.kind == .struct_ {
info := sym.info as ast.Struct
if node.no_keys && node.fields.len != info.fields.len {
fname := if info.fields.len != 1 { 'fields' } else { 'field' }
c.error('initializing struct `${sym.name}` needs `${info.fields.len}` ${fname}, but got `${node.fields.len}`',
node.pos)
}
}
}
// string & array are also structs but .kind of string/array
.struct_, .string, .array, .alias {
Expand Down
7 changes: 7 additions & 0 deletions vlib/v/checker/tests/generics_struct_nokeys_init_err.out
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
vlib/v/checker/tests/generics_struct_nokeys_init_err.vv:6:9: error: initializing struct `Am` needs `1` field, but got `2`
4 |
5 | fn convert[T](num int) T {
6 | return T{num, 1}
| ~~~~~~~~~
7 | }
8 |
12 changes: 12 additions & 0 deletions vlib/v/checker/tests/generics_struct_nokeys_init_err.vv
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
struct Am {
inner int
}

fn convert[T](num int) T {
return T{num, 1}
}

fn main() {
println(convert[Am](3).inner)
assert convert[Am](3).inner == 3
}

0 comments on commit 865c0ea

Please sign in to comment.