checker,cgen: allow alias to map type Dict = map[string]string (fix #24878) (#24883)

This commit is contained in:
Felipe Pena 2025-07-13 04:25:02 -03:00 committed by GitHub
parent f80fc37775
commit 34c67878b9
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
6 changed files with 15 additions and 23 deletions

View File

@ -643,6 +643,7 @@ fn (mut c Checker) alias_type_decl(mut node ast.AliasTypeDecl) {
info := parent_typ_sym.info as ast.Map
c.check_alias_vs_element_type_of_parent(node, info.key_type, 'map key')
c.check_alias_vs_element_type_of_parent(node, info.value_type, 'map value')
c.markused_used_maps(c.table.used_features.used_maps == 0)
}
.sum_type {
// TODO: decide whether the following should be allowed. Note that it currently works,

View File

@ -523,16 +523,6 @@ fn (mut c Checker) struct_init(mut node ast.StructInit, is_field_zero_struct_ini
c.error('union `${struct_sym.name}` can have only one field initialised',
node.pos)
}
} else if struct_sym.info is ast.Alias {
parent_sym := c.table.sym(struct_sym.info.parent_type)
// e.g. ´x := MyMapAlias{}´, should be a cast to alias type ´x := MyMapAlias(map[...]...)´
if parent_sym.kind == .map {
alias_str := c.table.type_to_str(node.typ)
map_str := c.table.type_to_str(struct_sym.info.parent_type)
c.error('direct map alias init is not possible, use `${alias_str}(${map_str}{})` instead',
node.pos)
return ast.void_type
}
} else if struct_sym.info is ast.FnType {
c.error('functions must be defined, not instantiated like structs', node.pos)
}
@ -649,8 +639,8 @@ fn (mut c Checker) struct_init(mut node ast.StructInit, is_field_zero_struct_ini
.struct {
info = sym.info as ast.Struct
}
.array, .array_fixed {
// we do allow []int{}, [10]int{}
.array, .array_fixed, .map {
// we do allow []int{}, [10]int{}, map[string]int{}
}
else {
c.error('alias type name: ${sym.name} is not struct type', node.pos)

View File

@ -1,6 +0,0 @@
vlib/v/checker/tests/direct_map_alias_init_err.vv:4:7: error: direct map alias init is not possible, use `WordSet(map[string]bool{})` instead
2 |
3 | fn main() {
4 | _ := WordSet{}
| ~~~~~~~~~
5 | }

View File

@ -1,5 +0,0 @@
type WordSet = map[string]bool
fn main() {
_ := WordSet{}
}

View File

@ -48,6 +48,9 @@ fn (mut g Gen) struct_init(node ast.StructInit) {
g.write(g.type_default_sumtype(unwrapped_typ, sym))
}
return
} else if sym.kind == .map {
g.write(g.type_default(unwrapped_typ))
return
}
is_amp := g.is_amp
is_multiline := node.init_fields.len > 5

View File

@ -0,0 +1,9 @@
module main
type Dict = map[string]string
fn test_main() {
mut x := Dict{}
x['foo'] = 'bar'
assert '${x}' == "Dict({'foo': 'bar'})"
}