mojo icon indicating copy to clipboard operation
mojo copied to clipboard

[BUG] Struct definition with recursive reference crashes

Open ciobaca opened this issue 1 year ago • 2 comments

Bug Description

Mojo crashes on the following input:

struct Node:
    var rec: Node
    fn __init__(self&):
        pass

Steps to Reproduce

  1. Run the above input in the playground.
  2. Watch it crash.

Context

No context needed.

ciobaca avatar May 10 '23 07:05 ciobaca

This was marked as a known issue in the docs:

https://docs.modular.com/mojo/roadmap.html#recursive-structs-dont-work

I presume at a later point it will be changed so that the above functionality just works.

hoxha-saber avatar May 10 '23 13:05 hoxha-saber

Thanks for filing this! Yes this is a known issue.

Mogball avatar May 10 '23 13:05 Mogball

FYI @weiweichen

Mogball avatar Jun 09 '23 07:06 Mogball

This should be fixed in the next release

Mogball avatar Jun 22 '23 18:06 Mogball

new syntax

#crash.mojo
struct Node:
    var rec: Node
    fn __init__(inout self):
        pass

now compiler says:

$🍔  mojo crash.mojo 
crash.mojo:3:5: error: recursive nested struct field, try adding indirection to recursive reference
    var rec: Node
    ^
crash.mojo:2:1: error: struct contains recursive reference to itself
struct Node:
^

weiweichen avatar Jun 22 '23 18:06 weiweichen

nice @weiweichen !

lattner avatar Jun 23 '23 15:06 lattner

Just wanted to say that this works now

@value
struct Node:
    var left: Pointer[Self]
    var right: Pointer[Self]

let n = Node(Pointer[Node].get_null(), Pointer[Node].get_null())

sa- avatar Jul 04 '23 12:07 sa-

A function field in a struct can still segfault (i.e. you don't get the nice error message, assuming it's the same bug) if any argument or the return value is of the "Self" type:

struct Node:
    var rec: fn(Self)->Self
def main():
    var b: Node

Although, even if it's the same bug, this case should be possible

siitron avatar Mar 14 '24 16:03 siitron

A function field in a struct can still segfault (i.e. you don't get the nice error message, assuming it's the same bug) if any argument or the return value is of the "Self" type:

struct Node:
    var rec: fn(Self)->Self
def main():
    var b: Node

Although, even if it's the same bug, this case should be possible

Probably an issue with struct field that is a fn. Could you please file a new bug/issue for this case, and would be great with a bit more error/crash info as well. Let's not recycle this old (closed) issue. Thanks!

weiweichen avatar Mar 14 '24 21:03 weiweichen