Skip to content

Conversation

xal-0
Copy link
Member

@xal-0 xal-0 commented May 15, 2025

When we capture a variable without boxing, we always generate a type parameter for the closure. This probably isn't what the user wants if the captured variable is an argument marked @nospecialize.

Before:

julia> K(@nospecialize(x)) = @nospecialize(y) -> x
K (generic function with 1 method)

julia> f, g = K(1), K("a")
(var"#K##0#K##1"{Int64}(1), var"#K##0#K##1"{String}("a"))

julia> f(2), g(2)
(1, "a")

julia> methods(f)[1].specializations
svec(MethodInstance for (::var"#K##0#K##1"{Int64})(::Any), MethodInstance for (::var"#K##0#K##1"{String})(::Any), nothing, nothing, nothing, nothing, nothing)

julia> fieldtypes(typeof(f)), fieldtypes(typeof(g))
((Int64,), (String,))

After:

julia> K(@nospecialize(x)) = @nospecialize(y) -> x
K (generic function with 1 method)

julia> f, g = K(1), K("a")
(var"#K##0#K##1"(1), var"#K##0#K##1"("a"))

julia> f(2), g(2)
(1, "a")

julia> methods(f)[1].specializations
MethodInstance for (::var"#K##0#K##1")(::Any)

julia> fieldtypes(typeof(f)), fieldtypes(typeof(g))
((Any,), (Any,))

@xal-0 xal-0 requested a review from topolarity May 15, 2025 17:39
@xal-0 xal-0 added the compiler:lowering Syntax lowering (compiler front end, 2nd stage) label May 15, 2025
@topolarity topolarity requested a review from mlechu May 15, 2025 17:48
@topolarity
Copy link
Member

Broadly looks good to me (although I really don't know lowering)

I think this is much more expected behavior. Thanks for the tune-up!

@xal-0 xal-0 merged commit 52e14cc into JuliaLang:master May 16, 2025
9 checks passed
@xal-0 xal-0 deleted the nospecialize-captured-variables branch May 16, 2025 00:09
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
compiler:lowering Syntax lowering (compiler front end, 2nd stage)
Projects
None yet
Development

Successfully merging this pull request may close these issues.

3 participants