cgen: fix interface unsafe {nil} comparison and initialization (fix #24374) (#24411)

This commit is contained in:
Felipe Pena 2025-05-06 06:48:55 -03:00 committed by GitHub
parent a412f53e62
commit dd859eae55
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
5 changed files with 24 additions and 2 deletions

View File

@ -258,7 +258,13 @@ fn (mut g Gen) gen_struct_equality_fn(left_type ast.Type) string {
&& (!field.typ.has_flag(.option) || !field.typ.is_ptr()) {
ptr := if field.typ.is_ptr() { '*'.repeat(field.typ.nr_muls()) } else { '' }
eq_fn := g.gen_interface_equality_fn(field.typ)
if ptr != '' {
fn_builder.write_string('((${left_arg} == (void*)0 && ${right_arg} == (void*)0) || (${left_arg} != (void*)0 && ${right_arg} != (void*)0 && ')
}
fn_builder.write_string('${eq_fn}_interface_eq(${ptr}${left_arg}, ${ptr}${right_arg})')
if ptr != '' {
fn_builder.write_string('))')
}
} else if field.typ.has_flag(.option) {
fn_builder.write_string('!memcmp(&${left_arg}.data, &${right_arg}.data, sizeof(${g.base_type(field.typ)}))')
} else {

View File

@ -2786,6 +2786,9 @@ fn (mut g Gen) call_cfn_for_casting_expr(fname string, expr ast.Expr, exp ast.Ty
g.write('&(${exp_styp.trim_right('*')}){._${got_styp.trim_right('*')}=')
rparen_n = 0
mutable_idx = got.idx()
} else if expr is ast.UnsafeExpr && expr.expr is ast.Nil {
g.write('(void*)0')
return
} else {
g.write('HEAP(${exp_styp}, ${fname}(')
rparen_n++

View File

@ -23,5 +23,5 @@ fn test_fn_returning_voidptr_casted_as_interface_works() {
// TODO: understand the root reason why msvc and
// `-cc clang-11 -cflags -fsanitize=memory` produce
// something like `&IAbc(e42aff650)` here
assert f(pi).contains('&IAbc(')
assert f(pi) == '&nil'
}

View File

@ -0,0 +1,13 @@
interface Cfg {
id string
}
struct XX {
cfg &Cfg = unsafe { nil }
}
fn test_main() {
xx := XX{}
assert xx.cfg == unsafe { nil }
assert unsafe { nil } == xx.cfg
}

View File

@ -24,6 +24,6 @@ fn test_struct_with_both_an_embed_and_a_pointer_to_interface_value_fields__initi
assert si.contains('Embed: Embed{')
assert si.contains('foo: 0')
assert si.contains('id: 0')
assert si.contains('parent: &Node(0x0)')
assert si.contains('parent: &nil')
assert si.contains('}')
}