Skip to content

Commit

Permalink
Scope self arguments using let block syntax
Browse files Browse the repository at this point in the history
  • Loading branch information
gaurav-arya committed Aug 20, 2023
1 parent 157dacd commit 868bafb
Showing 1 changed file with 11 additions and 10 deletions.
21 changes: 11 additions & 10 deletions src/compact.jl
Original file line number Diff line number Diff line change
Expand Up @@ -129,9 +129,7 @@ macro compact(_exs...)

# edit expressions
vars = map(ex -> ex.args[1], kwexs)
@gensym self
pushfirst!(fex.args[1].args, self)
addprefix!(fex, self, vars)
fex = supportself(fex, vars)

# assemble
return esc(quote
Expand All @@ -141,16 +139,19 @@ macro compact(_exs...)
end)
end

function addprefix!(ex::Expr, self, vars)
for i = 1:length(ex.args)
if ex.args[i] in vars
ex.args[i] = :($self.$(ex.args[i]))
else
addprefix!(ex.args[i], self, vars)
function supportself(fex::Expr, vars)
@gensym self
@gensym curried_fex
# To avoid having to manipulate fex's arguments and body explicitly, we form a curried function first
# that wraps the full fex expression, and then uncurry it programatically rather than syntactically.
let_exprs = map(var -> :($var = $self.$var), vars)
return quote
$curried_fex = ($self) -> let $(let_exprs...)
$fex
end
($self, args...; kwargs...) -> begin $curried_fex($self)(args...; kwargs...) end
end
end
addprefix!(not_ex, self, vars) = nothing

struct CompactLayer{F,NT1<:NamedTuple,NT2<:NamedTuple}
fun::F
Expand Down

0 comments on commit 868bafb

Please sign in to comment.