Skip to content

Commit dcfd14e

Browse files
committed
Prepare for moving methods of closures to top level
1 parent 2a8eb6e commit dcfd14e

File tree

1 file changed

+31
-5
lines changed

1 file changed

+31
-5
lines changed

src/closure_conversion.jl

Lines changed: 31 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@ struct ClosureConversionCtx{GraphType} <: AbstractLoweringContext
33
bindings::Bindings
44
mod::Module
55
lambda_bindings::LambdaBindings
6+
toplevel_stmts::SyntaxList{GraphType}
67
end
78

89
function add_lambda_local!(ctx::ClosureConversionCtx, id)
@@ -164,13 +165,39 @@ function _convert_closures(ctx::ClosureConversionCtx, ex)
164165
children(ex)...
165166
])
166167
elseif k == K"lambda"
167-
ctx2 = ClosureConversionCtx(ctx.graph, ctx.bindings, ctx.mod, ex.lambda_bindings)
168-
mapchildren(e->_convert_closures(ctx2, e), ctx2, ex)
168+
closure_convert_lambda(ctx, ex)
169169
else
170170
mapchildren(e->_convert_closures(ctx, e), ctx, ex)
171171
end
172172
end
173173

174+
function closure_convert_lambda(ctx, ex)
175+
@assert kind(ex) == K"lambda"
176+
body_stmts = SyntaxList(ctx)
177+
toplevel_stmts = ex.is_toplevel_thunk ? body_stmts : ctx.toplevel_stmts
178+
ctx2 = ClosureConversionCtx(ctx.graph, ctx.bindings, ctx.mod,
179+
ex.lambda_bindings, toplevel_stmts)
180+
lambda_children = SyntaxList(ctx)
181+
push!(lambda_children, _convert_closures(ctx2, ex[1]))
182+
push!(lambda_children, _convert_closures(ctx2, ex[2]))
183+
184+
# Convert body. This is done as a special case to allow inner calls to
185+
# _convert_closures to also add to body_stmts in the case that
186+
# ex.is_toplevel_thunk is true.
187+
in_body_stmts = kind(ex[3]) != K"block" ? ex[3:3] : ex[3][1:end]
188+
for e in in_body_stmts
189+
push!(body_stmts, _convert_closures(ctx2, e))
190+
end
191+
push!(lambda_children, @ast ctx2 ex[3] [K"block" body_stmts...])
192+
193+
if numchildren(ex) > 3
194+
@assert numchildren(ex) == 4
195+
push!(lambda_children, _convert_closures(ctx2, ex[4]))
196+
end
197+
198+
makenode(ctx, ex, ex, lambda_children)
199+
end
200+
174201

175202
"""
176203
Closure conversion and lowering of bindings
@@ -186,8 +213,7 @@ Invariants:
186213
* Any new binding IDs must be added to the enclosing lambda locals
187214
"""
188215
function convert_closures(ctx::ScopeResolutionContext, ex)
189-
@assert kind(ex) == K"lambda"
190-
ctx = ClosureConversionCtx(ctx.graph, ctx.bindings, ctx.mod, ex.lambda_bindings)
191-
ex1 = _convert_closures(ctx, ex)
216+
ctx = ClosureConversionCtx(ctx.graph, ctx.bindings, ctx.mod, ex.lambda_bindings, SyntaxList(ctx))
217+
ex1 = closure_convert_lambda(ctx, ex)
192218
ctx, ex1
193219
end

0 commit comments

Comments
 (0)