Skip to content

Fixed methods with self: &Self consuming the object #4178

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 6 commits into from
Oct 12, 2024

Conversation

RunDevelopment
Copy link
Contributor

fixes #3958

Rust allows type annotations for the self parameter, so it can have many forms. E.g. self, &self, &mut self, self: &Self, self: Self, self: Box<Self>, etc. Wasm bindgen needs to know whether a value is consumed (pass by value) or referenced to generate the correct JS shim.

Previously, the parser only looked at whether the self parameter had an & before self. This works for self, &mut self, and &self, but not for self: &Self. So it previously interpreted self: &Self (a reference) as just self (pass by value), because it ignored any and all type annotations, which caused #3958.

This PR fixes the issue by looking at the type of self instead. Helpfully, syn always gives us a type even for &self. See their docs for more details. So instead of checking whether self has an &, it now checks whether the type of self is a reference type. This is the same approach wasm bindgen uses for all other arguments to figure out whether they are passed by referece or by value.

Copy link
Collaborator

@daxpedda daxpedda left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM!
Just missing a changelog entry.

@daxpedda daxpedda added the waiting for author Waiting for author to respond label Oct 12, 2024
Comment on lines +891 to +896
// The tricky part here is that `r` can have many forms. E.g. `self`,
// `&self`, `&mut self`, `self: Self`, `self: &Self`, `self: &mut Self`,
// `self: Box<Self>`, `self: Rc<Self>`, etc.
// Luckily, syn always populates the `ty` field with the type of `self`, so
// e.g. `&self` gets the type `&Self`. So we only have check whether the
// type is a reference or not.
Copy link
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I thought I left a comment about this before:
Excellent! Thank you!

@daxpedda daxpedda merged commit 03c8e2d into rustwasm:main Oct 12, 2024
41 checks passed
@RunDevelopment RunDevelopment deleted the consume-self branch October 12, 2024 21:04
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
waiting for author Waiting for author to respond
Projects
None yet
Development

Successfully merging this pull request may close these issues.

JS Pointer gets nulled if rust method defined as self: &Self instead of &self
2 participants