Skip to content
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

Clarify the encoding of closures #194

Open
Nadrieril opened this issue May 22, 2024 · 2 comments
Open

Clarify the encoding of closures #194

Nadrieril opened this issue May 22, 2024 · 2 comments
Assignees

Comments

@Nadrieril
Copy link
Member

Nadrieril commented May 22, 2024

As of #186, closures are implemented by letting the consumer of llbc track which function pointer goes with which closure, and the Call terminator mentions a built-in trait implementation for Fn/FnMut/FnOnce that the consumer of llbc must deduce corresponds to the aforementioned function pointer.

I propose that we instead encode this:

pub fn test_closure_capture(x: u32, y: u32) -> u32 {
    let f = &|z| x + y + z;
    (f)(0)
}

as follows:

struct {test_closure_capture::closure#0} {
    x: u32,
    y: u32,
}

impl Fn<(u32,)> for {test_closure_capture::closure#0} {
    type Output = u32;
    fn call(&self, arg: (u32,)) -> u32 {
        self.x + self.y + arg.0
    }
}

pub fn test_closure_capture(x: u32, y: u32) -> u32 {
    let state = {test_closure_capture::closure#0} { x, y };
    state.call(0)
}

This is pretty much exactly how rustc represents closures internally, and has the benefit that consumers of llbc don't need to do anything special to support closures.

@sonmarcho
Copy link
Member

Small update: after a discussion I think we came up with a different solution, where the function pointer is not stored in the state but in the instance of Fn<(u32,)> (maybe it is actually what you mean above, but it is slightly unclear).

@Nadrieril
Copy link
Member Author

Nadrieril commented May 29, 2024

That is indeed what I meant above; as you can see, there is no function pointer stored anywhere in the desugared output; the special closure type is just the name for a struct.

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

No branches or pull requests

2 participants