Skip to content

Commit fa66183

Browse files
authored
checker: check error for map of generic struct init (#13999)
1 parent a0e7a46 commit fa66183

File tree

4 files changed

+32
-1
lines changed

4 files changed

+32
-1
lines changed

vlib/v/checker/containers.v

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -260,6 +260,22 @@ pub fn (mut c Checker) map_init(mut node ast.MapInit) ast.Type {
260260
// `x := map[string]string` - set in parser
261261
if node.typ != 0 {
262262
info := c.table.sym(node.typ).map_info()
263+
if info.value_type != 0 {
264+
val_sym := c.table.sym(info.value_type)
265+
if val_sym.kind == .struct_ {
266+
val_info := val_sym.info as ast.Struct
267+
if val_info.generic_types.len > 0 && val_info.concrete_types.len == 0
268+
&& !info.value_type.has_flag(.generic) {
269+
if c.table.cur_concrete_types.len == 0 {
270+
c.error('generic struct `$val_sym.name` must specify type parameter, e.g. Foo<int>',
271+
node.pos)
272+
} else {
273+
c.error('generic struct `$val_sym.name` must specify type parameter, e.g. Foo<T>',
274+
node.pos)
275+
}
276+
}
277+
}
278+
}
263279
c.ensure_type_exists(info.key_type, node.pos) or {}
264280
c.ensure_type_exists(info.value_type, node.pos) or {}
265281
node.key_type = info.key_type
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
vlib/v/checker/tests/map_of_generic_struct_init_err.vv:6:11: error: generic struct `Item` must specify type parameter, e.g. Foo<int>
2+
4 |
3+
5 | fn main() {
4+
6 | mut m := map[string]Item{}
5+
| ~~~~~~~~~~~~~~~~~
6+
7 | }
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
struct Item<T>{
2+
val T
3+
}
4+
5+
fn main() {
6+
mut m := map[string]Item{}
7+
}

vlib/v/parser/parser.v

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2140,10 +2140,12 @@ pub fn (mut p Parser) name_expr() ast.Expr {
21402140
p.expr_mod = ''
21412141
// `map[string]int` initialization
21422142
if p.tok.lit == 'map' && p.peek_tok.kind == .lsbr {
2143+
mut pos := p.tok.pos()
21432144
map_type := p.parse_map_type()
21442145
if p.tok.kind == .lcbr {
21452146
p.next()
21462147
if p.tok.kind == .rcbr {
2148+
pos = pos.extend(p.tok.pos())
21472149
p.next()
21482150
} else {
21492151
if p.pref.is_fmt {
@@ -2156,7 +2158,7 @@ pub fn (mut p Parser) name_expr() ast.Expr {
21562158
}
21572159
return ast.MapInit{
21582160
typ: map_type
2159-
pos: p.prev_tok.pos()
2161+
pos: pos
21602162
}
21612163
}
21622164
// `chan typ{...}`

0 commit comments

Comments
 (0)