MacroTools.jl icon indicating copy to clipboard operation
MacroTools.jl copied to clipboard

Reassigning Variables within @capture

Open yurivish opened this issue 7 years ago • 1 comments

@capture introduces assignments to variables indicated in its second argument. When one of these assignments is to a variable with the same name as the first argument, things seem to go wrong — the match fails and the value of that variable is set to nothing. I think the better behavior in this case would be for the match to succeed, and for ex and b in the second example to have the values of a and b in the first.

julia> ex = :(1 + 2)
:(1 + 2)

julia> @capture(ex, a_ + b_)
true

julia> @capture(ex, ex_ + b_)
false

julia> ex

yurivish avatar Aug 26 '18 12:08 yurivish

I agree. This just happens because of the way we expand things –

ex = MacroTools.nothing
b = MacroTools.nothing
llama = (MacroTools.trymatch)($(Expr(:copyast, :($(QuoteNode(:(ex_ + b_)))))), ex)
if llama == MacroTools.nothing
    false
else
    ex = (MacroTools.get)(llama, :ex, MacroTools.nothing)
    b = (MacroTools.get)(llama, :b, MacroTools.nothing)
    true
end

But you could straightforwardly change this to set ex = nothing only in the failure case.

MikeInnes avatar Sep 17 '18 17:09 MikeInnes