Open uniment opened 8 months ago
Duplicate of https://github.com/JuliaLang/julia/issues/40990
This is not a duplicate of #40990: whereas that issue presents a problem, this issue presents a solution.
Additionally, #40990 actually exhibits two simultaneous problems: that described here, and also that described in #53338.
I will close #40990 in favor of this, as it has more detail and along with #53338 splits it into two more specific issues.
Consider the function:
This is approximately equivalent to:
The fact that the recursive function boxes its reference to itself here is obviously inefficient and undesirable.
My understanding is that
fib
's reference to itself must be boxed because of the rule that whenever a capture is or can be assigned after its closure's instantiation, then that capture must be boxed: obviously this is usually a good rule, since the capture's new value could otherwise be unknown to the closure during the closure's lifetime. Here, lowering detects that the localfib
identifier's first and only assignment occurs after the local functor object's instantiation, so following this rule, it boxesfib
.However, I propose we carve an exception to this rule for the function's own identifier: if the function's local identifier is only ever assigned to the functor object itself and has no other syntactical assignments anywhere, then it is obvious that the value this identifier is assigned to is always known to the closure throughout its lifetime—it is itself! Thus, with such an exception made, I would hope that lowering could be changed such that the code above would instead become approximately equivalent to:
(this proposal solves #47760 but more elegantly so I'm closing that issue)