Skip to content

Commit 34ac326

Browse files
authored
cgen: fix initialising a map, using option type as value (#18540)
1 parent 752e4c2 commit 34ac326

File tree

3 files changed

+33
-2
lines changed

3 files changed

+33
-2
lines changed

vlib/v/gen/c/cgen.v

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1888,7 +1888,11 @@ fn (mut g Gen) expr_with_tmp_var(expr ast.Expr, expr_typ ast.Type, ret_typ ast.T
18881888
g.writeln('${g.typ(ret_typ)} ${tmp_var};')
18891889
if ret_typ.has_flag(.option) {
18901890
if expr_typ.has_flag(.option) && expr in [ast.StructInit, ast.ArrayInit, ast.MapInit] {
1891-
g.write('_option_none(&(${styp}[]) { ')
1891+
if expr is ast.StructInit && (expr as ast.StructInit).init_fields.len > 0 {
1892+
g.write('_option_ok(&(${styp}[]) { ')
1893+
} else {
1894+
g.write('_option_none(&(${styp}[]) { ')
1895+
}
18921896
} else {
18931897
is_ptr_to_ptr_assign = (expr is ast.SelectorExpr
18941898
|| (expr is ast.Ident && !(expr as ast.Ident).is_auto_heap()))
@@ -3989,6 +3993,8 @@ fn (mut g Gen) map_init(node ast.MapInit) {
39893993
}
39903994
if value_sym.kind == .sum_type {
39913995
g.expr_with_cast(expr, node.val_types[i], unwrap_val_typ)
3996+
} else if node.val_types[i].has_flag(.option) {
3997+
g.expr_with_opt(expr, node.val_types[i], unwrap_val_typ)
39923998
} else {
39933999
g.expr(expr)
39944000
}

vlib/v/gen/c/index.v

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -404,7 +404,7 @@ fn (mut g Gen) index_of_map(node ast.IndexExpr, sym ast.TypeSymbol) {
404404
if g.inside_return {
405405
g.typ(val_type)
406406
} else {
407-
g.typ(val_type.clear_flags(.option, .result))
407+
g.typ(val_type.clear_flags(.result))
408408
}
409409
}
410410
get_and_set_types := val_sym.kind in [.struct_, .map, .array]

vlib/v/tests/option_map_init_test.v

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

0 commit comments

Comments
 (0)