Skip to content

Commit 5eb331e

Browse files
authored
cgen: fix option ptr printing (#17651)
1 parent 7e8723d commit 5eb331e

File tree

3 files changed

+28
-3
lines changed

3 files changed

+28
-3
lines changed

vlib/v/gen/c/auto_str_methods.v

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -56,7 +56,11 @@ fn (mut g Gen) get_str_fn(typ ast.Type) string {
5656
$if trace_autostr ? {
5757
eprintln('> get_str_fn: ${typ.debug()}')
5858
}
59-
mut unwrapped := g.unwrap_generic(typ).set_nr_muls(0).clear_flag(.variadic)
59+
mut unwrapped := if typ.has_flag(.option) {
60+
g.unwrap_generic(typ).clear_flag(.variadic)
61+
} else {
62+
g.unwrap_generic(typ).set_nr_muls(0).clear_flag(.variadic)
63+
}
6064
if g.pref.nofloat {
6165
if typ == ast.f32_type {
6266
unwrapped = ast.u32_type
@@ -515,6 +519,9 @@ fn styp_to_str_fn_name(styp string) string {
515519

516520
// deref_kind returns deref, deref_label
517521
fn deref_kind(str_method_expects_ptr bool, is_elem_ptr bool, typ ast.Type) (string, string) {
522+
if typ.has_flag(.option) {
523+
return '', ''
524+
}
518525
if str_method_expects_ptr != is_elem_ptr {
519526
if is_elem_ptr {
520527
return '*'.repeat(typ.nr_muls()), '&'.repeat(typ.nr_muls())
@@ -936,7 +943,11 @@ fn (mut g Gen) gen_str_for_struct(info ast.Struct, styp string, typ_str string,
936943
caller_should_free = false
937944
} else if ftyp_noshared.is_ptr() {
938945
// reference types can be "nil"
939-
funcprefix += 'isnil(it.${c_name(field.name)})'
946+
if ftyp_noshared.has_flag(.option) {
947+
funcprefix += 'isnil(&it.${c_name(field.name)})'
948+
} else {
949+
funcprefix += 'isnil(it.${c_name(field.name)})'
950+
}
940951
funcprefix += ' ? _SLIT("nil") : '
941952
// struct, floats and ints have a special case through the _str function
942953
if sym.kind !in [.struct_, .alias, .enum_, .sum_type, .map, .interface_]

vlib/v/gen/c/str.v

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -125,7 +125,7 @@ fn (mut g Gen) gen_expr_to_string(expr ast.Expr, etype ast.Type) {
125125
if str_method_expects_ptr && !is_ptr {
126126
g.write('&')
127127
} else if is_ptr && typ.has_flag(.option) {
128-
g.write('*(${g.typ(typ.set_nr_muls(0))}*)&')
128+
g.write('*(${g.typ(typ)}*)&')
129129
} else if !str_method_expects_ptr && !is_shared && (is_ptr || is_var_mut) {
130130
g.write('*'.repeat(typ.nr_muls()))
131131
}

vlib/v/tests/option_print_ptr_test.v

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,14 @@
1+
struct One {
2+
thing string = 'thing 1'
3+
}
4+
5+
struct Two {
6+
maybe_one ?&One
7+
}
8+
9+
fn test_dump_option_ptr() {
10+
a := Two{}
11+
println(a)
12+
println(Two{})
13+
dump(Two{})
14+
}

0 commit comments

Comments
 (0)