JuliaServices / Match.jl

Advanced Pattern Matching for Julia
https://juliaservices.github.io/Match.jl/latest/
Other
240 stars 22 forks source link

Matching Exprs (vararg constructor) #85

Open gafter opened 1 year ago

gafter commented 1 year ago

From the Match.jl documentation we have:

The following function is a nice example of matching expressions. It is used in VideoIO.jl to extract the names of expressions generated by Clang.jl, for later filtering and rewriting.:

extract_name(x) = string(x)
function extract_name(e::Expr)
    @match e begin
        Expr(:type,      [_, name, _], _)     => name
        Expr(:typealias, [name, _], _)        => name
        Expr(:call,      [name, _...], _)     => name
        Expr(:function,  [sig, _...], _)      => extract_name(sig)
        Expr(:const,     [assn, _...], _)     => extract_name(assn)
        Expr(:(=),       [fn, body, _...], _) => extract_name(fn)
        Expr(expr_type,  _...)                => error("Can't extract name from ",
                                                        expr_type, " expression:\n",
                                                        "    $e\n")
    end
end

However, this doesn't work in Match, Rematch, or Rematch2. It would be nice if it did. Doing so would require recognizing treating Expr specially:

julia> methods(Expr)
# 1 method for type constructor:
[1] Expr(args...) in Core at boot.jl:263

julia> fieldnames(Expr)
(:head, :args)

julia> fieldtypes(Expr)
(Symbol, Vector{Any})