Skip to content

Commit 9fc8352

Browse files
authored
parser: allow map cast syntax map[k]v(expr) (#23401)
1 parent 7078a2e commit 9fc8352

2 files changed

Lines changed: 39 additions & 1 deletion

File tree

‎vlib/v/parser/parser.v‎

Lines changed: 14 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2719,10 +2719,23 @@ fn (mut p Parser) name_expr() ast.Expr {
27192719
if is_option {
27202720
map_type = map_type.set_flag(.option)
27212721
}
2722-
return ast.MapInit{
2722+
node = ast.MapInit{
27232723
typ: map_type
27242724
pos: pos
27252725
}
2726+
if p.tok.kind == .lpar {
2727+
// ?map[int]int(none) cast expr
2728+
p.check(.lpar)
2729+
expr := p.expr(0)
2730+
p.check(.rpar)
2731+
return ast.CastExpr{
2732+
typ: map_type
2733+
typname: p.table.sym(map_type).name
2734+
expr: expr
2735+
pos: pos.extend(p.tok.pos())
2736+
}
2737+
}
2738+
return node
27262739
}
27272740
// `chan typ{...}`
27282741
if p.tok.lit == 'chan' {

‎vlib/v/tests/map_cast_test.v‎

Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
fn foo() map[int]int {
2+
return {
3+
1: 2
4+
}
5+
}
6+
7+
fn test_main() {
8+
a := ?map[int]int(none)
9+
assert a == none
10+
11+
b := ?map[int]int({
12+
1: 2
13+
})
14+
assert b?[1] == 2
15+
16+
c := ?map[int]map[string]string({
17+
1: {
18+
'foo': 'bar'
19+
}
20+
})
21+
assert c?[1]['foo'] == 'bar'
22+
23+
d := ?map[int]int(foo())
24+
assert d?[1] == 2
25+
}

0 commit comments

Comments
 (0)