v icon indicating copy to clipboard operation
v copied to clipboard

v: allow recursive struct with option

Open felipensp opened this issue 1 year ago • 1 comments

Fix #14185

struct Node {
mut:
  next ?Node
}

fn main() {
	mut a := Node{}
	a.next = Node{}
	println(a)
	println(a.next?)
	println(a.next?.next)
}
Node{
    next: Option(Node{
        next: Option(error: none)
    })
}
Node{
    next: Option(error: none)
}
Option(error: none)

felipensp avatar Mar 16 '23 14:03 felipensp

just one test failing!

Failed command 1:    '/home/runner/work/v/v/v' -cflags -fsanitize=address   -o '/tmp/v_1001/tsession_7f337d74f740_349323323640/option_nested_struct_test' '/home/runner/work/v/v/vlib/v/tests/option_nested_struct_test.v'

medvednikov avatar Mar 26 '23 12:03 medvednikov

@medvednikov I ran the specs locally and they seem to pass, do you know what runner that failed on? The logs have been cleaned up now. It would be really helpful for a project I'm working on if this got merged.

watzon avatar Apr 10 '23 21:04 watzon

The problem is that it failed the sanitize-address tests. That generally points to memory leaks, array access problems, etc. Those need to be addressed, first.

JalonSolov avatar Apr 10 '23 21:04 JalonSolov

Can confirm. I tried a real world test and got a segfault.

watzon avatar Apr 10 '23 22:04 watzon

Yes, It points memory issue when doing a.next = Node{}.

felipensp avatar Apr 11 '23 12:04 felipensp

Yes, It points memory issue when doing a.next = Node{}.

Since makes no sense a recursive struct using stack, I've changed this PR plan to allow recursive struct using ?&Node. What do you think @medvednikov? In this way we do not have memory issues.

felipensp avatar Apr 14 '23 03:04 felipensp

Hm I thought ?Node would imply ?&Node.

@spytheman what do you think?

medvednikov avatar Apr 16 '23 21:04 medvednikov

Hm I thought ?Node would imply ?&Node.

I think, that it is still too early (opened bugs concerning option values), to change the representation of Option, which will be needed to make struct Node { next ?Node } work.

This PR enables the compilation of:

struct Node { next ?&Node }
a := Node{}

which currently leads to segfault in cgen on master (stack overflow due to Gen_struct_init -> Gen_zero_struct_field -> Gen_expr_with_tmp_var -> Gen_expr_with_cast -> Gen_expr -> Gen_struct_init etc).

That is still valuable and enables more and safer programs, compared to just next &Node which we do support.

spytheman avatar Apr 17 '23 15:04 spytheman

Ok, makes sense.

But I think in the future, it'd be okay to have just ?Node, instead of always requiring ?&Node.

Feels a lot more readable and simple.

medvednikov avatar Apr 18 '23 08:04 medvednikov