Skip to content

Translate self referencing initialiser - #498

Merged
nunoplopes merged 5 commits into
Cpp2Rust:masterfrom
lucic71:self-referencing
Oct 9, 2026
Merged

nunoplopes merged 5 commits into
Cpp2Rust:masterfrom
lucic71:self-referencing

Conversation

@lucic71

@lucic71 lucic71 commented Oct 8, 2026

Copy link
Copy Markdown
Contributor

Fixes the original issue reported in #248. Self-refrencing in constructors is not handled here.

It translates:

struct list_head list = { &list };

to:

   let list: Value<list_head> = <Value<list_head>>::default();
    *list.borrow_mut() = list_head {
        next: (list.as_pointer()),
    };

That is, first create a default value, then assign it the self-referencing initialiser. Types that have defaults with side-effects are not supported.

@nunoplopes

Copy link
Copy Markdown
Contributor

This is not a good nor generic solution. We should try to use Rc::new_cyclic.

@lucic71

lucic71 commented Oct 8, 2026

Copy link
Copy Markdown
Contributor Author

This is not a good nor generic solution. We should try to use Rc::new_cyclic.

I already thought about Rc::new_cyclic and it's not a good solution. It does not work for list_head called = {init(&called)};, i.e. initialiser writes the self-referenced variable.

Inside the Rc::new_cycle closure we only have a Weak without a constructed T. This mean that we can convert called to Ptr, but we cannot do read/write on the Ptr because Weak::upgrade will panic.

I think the generic solution (for self-referencing variables and for self-referencing constructors, see #248) is:

  1. Initialize the variable in an empty-but-valid state, for example all fields zeroed. Default is not a good empty-but-valid state because it might have side effects
  2. For self-referencing variables, write the initialiser in the storage from 1, basically the solution in this PR. For self-referencing constructors, pass the storage from 1 to the constructor call: T::new(&storage, arg1, arg2, ...)

@nunoplopes
nunoplopes merged commit 2bb3063 into Cpp2Rust:master Oct 9, 2026
9 checks passed
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants