parser: allow map cast syntax map[k]v(expr) (#23401)

This commit is contained in:
Felipe Pena 2025-01-07 15:56:52 -03:00 committed by GitHub
parent 7078a2e185
commit 9fc83526aa
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
2 changed files with 39 additions and 1 deletions

View File

@ -2719,10 +2719,23 @@ fn (mut p Parser) name_expr() ast.Expr {
if is_option {
map_type = map_type.set_flag(.option)
}
return ast.MapInit{
node = ast.MapInit{
typ: map_type
pos: pos
}
if p.tok.kind == .lpar {
// ?map[int]int(none) cast expr
p.check(.lpar)
expr := p.expr(0)
p.check(.rpar)
return ast.CastExpr{
typ: map_type
typname: p.table.sym(map_type).name
expr: expr
pos: pos.extend(p.tok.pos())
}
}
return node
}
// `chan typ{...}`
if p.tok.lit == 'chan' {

View File

@ -0,0 +1,25 @@
fn foo() map[int]int {
return {
1: 2
}
}
fn test_main() {
a := ?map[int]int(none)
assert a == none
b := ?map[int]int({
1: 2
})
assert b?[1] == 2
c := ?map[int]map[string]string({
1: {
'foo': 'bar'
}
})
assert c?[1]['foo'] == 'bar'
d := ?map[int]int(foo())
assert d?[1] == 2
}