<p>Consider the following pseudocode:</p>
<pre class="lang-js prettyprint-override"><code>function make_counter(start: i32) {
    let mut count: i32 = start;

    function increase() {
        count += 1;
        print(count);
        return increase
    }

    return increase
}

let counter = make_counter()
counter() // 1
counter() // 2
</code></pre>
<p>How should similar code be compiled into WebAssembly?</p>
<hr />
<p>My main question is, where should the variables be stored? Where should the functions be stored?</p>
<ul>
<li>Should variables be stored in global?</li>
</ul>
<p>But every time <code>make_counter</code> is called, there will be one more variable. Do I need to statically analyze how many times this function is called?</p>
<ul>
<li>Should functions be defined in table?</li>
</ul>
<p>Dynamically called functions need to be defined in the table as element, and there isn't no way to call them through function pointers.
Moreover, tables cannot be dynamically expanded in WebAssembly, and function pointers cannot be returned.</p>

<webassembly><closure>
How can I compile closures in WebAssembly?
CC BY-SA 4.0
2024-03-06T13:20:13.440Z
What an interesting construction! So `let counter = make_counter(); counter(); counter()` is equivalent to `let counter = make_counter(); counter()()` or even just `make_counter()()()`?
OpenAI was the last straw
CC BY-SA 4.0
2024-03-06T14:42:23.553Z
Related: [Can "doubt" sometimes mean "question"?](https://english.stackexchange.com/questions/2429/can-doubt-sometimes-mean-question)
Peter Mortensen
CC BY-SA 4.0
2024-03-06T15:39:56.720Z
@PeterMortensen, sorry, I used Google Translate, my original meaning should be closer to `confuse` than `doubt`.
Aster
CC BY-SA 4.0
2024-03-07T22:04:18.260Z
There's a chapter of SICP on how to implement closures. Do you think there's something about WebAssembly that implies a unique method of implementation?
Barmar
CC BY-SA 4.0
2024-03-10T15:58:21.573Z
@Barmar WebAssembly handles function pointers differently to other assembly languages - essentially they are opaque values, not actual pointers. In particular, you cannot create new functions at runtime and then point to them. This means some methods for implementing closures are not possible in WebAssembly (though others are still possible).
kaya3
CC BY-SA 4.0
2024-03-18T20:24:17.293Z
@A.R. No, `make_counter` is essentially a higher-order function that returns a new function. Calling `counter` twice is not the same as trying to call the return value of  the first call to `counter`.
chepner
CC BY-SA 4.0
2024-03-19T12:40:23.207Z
But `counter` is also a higher-order function that returns itself, since it ends with `return increase();`.
OpenAI was the last straw
<p>The accepted answer illustrates how closures are compiled in general. To supplement with some WebAssembly specific details, I find the following references helpful:</p>
<ol>
<li><p>The WebAssembly's <a href="https://github.com/WebAssembly/gc/blob/main/proposals/gc/Overview.md#closures" rel="nofollow noreferrer">GC proposal</a> has an example similar to the program in your question, and manually translates it to WAT format.</p>
</li>
<li><p>The <a href="https://www.moonbitlang.com/" rel="nofollow noreferrer">MoonBit language</a> is a Rust-like-but-with-GC language that targets WebAssembly. I find it also emits somewhat readable WAT output. It's not on Godbolt yet, but I'd recommend you play with it and study how closures are compiled by it.</p>
</li>
</ol>

CC BY-SA 4.0
2024-03-12T05:04:45.893Z
2024-03-12T05:04:45.893Z
Yu-zh
<p>The typical high-level approach to compiling closures is that they combine <em>both</em> a function pointer and a data value representing all captured variables (e.g. a struct). You need both of those to execute the closure; you can think of this as being essentially the same way you would compile an object.</p>
<p>When the function runs, it is given that data structure as an additional argument, and in its preamble it copies values or pointers out of the data structure. Alternatively, your calling convention might unpack the structure before the function runs.</p>
<p>There is <strong>only ever <em>one</em> copy of the function compiled, and all the closures share it</strong>. This function is compiled statically and you know how many there will be in advance. Each instantiation of the closure is a separate capture structure containing the same function pointer and its own data. This will work the same way as first-class functions that aren’t closures, just using the function index.</p>
<p>For a closure over shared mutable state, you need to store pointers to the long-term storage locations. This may mean sharing these capture structures between multiple closures, or chaining them. You can sort out how this ought to work under your language semantics, or if it’s even possible.</p>
<p>You can do all of this in WebAssembly. The only thing you allocate dynamically is the capture storage structure, which is fine. That can contain the function index within the table to use when you execute it. You do need to know whether something is a closure or not in order to call it, which may require another layer of indirection in some cases, but otherwise there’s no particular complication.</p>

CC BY-SA 4.0
2024-03-06T05:09:54.293Z
2024-03-06T05:09:54.293Z
Michael Homer
# How can I compile closures in WebAssembly?
Posted by: username_0 on 2024-03-06
Consider the following pseudocode:
function make_counter(start: i32) {
    let mut count: i32 = start;

    function increase() {
        count += 1;
        print(count);
        return increase
    }

    return increase
}

let counter = make_counter()
counter() // 1
counter() // 2

How should similar code be compiled into WebAssembly?

My main question is, where should the variables be stored? Where should the functions be stored?

Should variables be stored in global?

But every time make_counter is called, there will be one more variable. Do I need to statically analyze how many times this function is called?

Should functions be defined in table?

Dynamically called functions need to be defined in the table as element, and there isn't no way to call them through function pointers.
Moreover, tables cannot be dynamically expanded in WebAssembly, and function pointers cannot be returned.
**Tags:** webassembly closure
> **Comments:**
> **username_1**: What an interesting construction! So `let counter = make_counter(); counter(); counter()` is equivalent to `let counter = make_counter(); counter()()` or even just `make_counter()()()`?  
> **username_2**: Related: [Can "doubt" sometimes mean "question"?](https://english.stackexchange.com/questions/2429/can-doubt-sometimes-mean-question)  
> **username_0**: @PeterMortensen, sorry, I used Google Translate, my original meaning should be closer to `confuse` than `doubt`.  
> **username_3**: There's a chapter of SICP on how to implement closures. Do you think there's something about WebAssembly that implies a unique method of implementation?  
> **username_4**: @Barmar WebAssembly handles function pointers differently to other assembly languages - essentially they are opaque values, not actual pointers. In particular, you cannot create new functions at runtime and then point to them. This means some methods for implementing closures are not possible in WebAssembly (though others are still possible).  
> **username_5**: @A.R. No, `make_counter` is essentially a higher-order function that returns a new function. Calling `counter` twice is not the same as trying to call the return value of  the first call to `counter`.  
> **username_1**: But `counter` is also a higher-order function that returns itself, since it ends with `return increase();`.  
---
## 2 answers
### Answer by username_7 on 2024-03-06. Score: 5 | Accepted answer
The typical high-level approach to compiling closures is that they combine *both* a function pointer and a data value representing all captured variables (e.g. a struct). You need both of those to execute the closure; you can think of this as being essentially the same way you would compile an object.

When the function runs, it is given that data structure as an additional argument, and in its preamble it copies values or pointers out of the data structure. Alternatively, your calling convention might unpack the structure before the function runs.

There is **only ever *one* copy of the function compiled, and all the closures share it**. This function is compiled statically and you know how many there will be in advance. Each instantiation of the closure is a separate capture structure containing the same function pointer and its own data. This will work the same way as first-class functions that aren’t closures, just using the function index.

For a closure over shared mutable state, you need to store pointers to the long-term storage locations. This may mean sharing these capture structures between multiple closures, or chaining them. You can sort out how this ought to work under your language semantics, or if it’s even possible.

You can do all of this in WebAssembly. The only thing you allocate dynamically is the capture storage structure, which is fine. That can contain the function index within the table to use when you execute it. You do need to know whether something is a closure or not in order to call it, which may require another layer of indirection in some cases, but otherwise there’s no particular complication.
---
### Answer by username_6 on 2024-03-12. Score: 1
The accepted answer illustrates how closures are compiled in general. To supplement with some WebAssembly specific details, I find the following references helpful:

1. The WebAssembly's [GC proposal](https://github.com/WebAssembly/gc/blob/main/proposals/gc/Overview.md#closures) has an example similar to the program in your question, and manually translates it to WAT format.
2. The [MoonBit language](https://www.moonbitlang.com/) is a Rust-like-but-with-GC language that targets WebAssembly. I find it also emits somewhat readable WAT output. It's not on Godbolt yet, but I'd recommend you play with it and study how closures are compiled by it.
---
