Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

WIP: static_hasmethod kwargs #28

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 25 additions & 3 deletions src/Tricks.jl
Original file line number Diff line number Diff line change
Expand Up @@ -14,13 +14,20 @@ _hasmethod_true(@nospecialize(f), @nospecialize(t)) = true

Like `hasmethod` but runs at compile-time (and does not accept a worldage argument).
"""
@generated function static_hasmethod(@nospecialize(f), @nospecialize(t::Type{T}),) where {T<:Tuple}
@generated function static_hasmethod(
@nospecialize(f),
@nospecialize(t::Type{T}),
@nospecialize(kwnames_type_tuple::Type{<:Tuple})=Type{Tuple{}},
) where {T<:Tuple}
# The signature type:
world = typemax(UInt)
method_insts = Core.Compiler.method_instances(f.instance, T, world)

ftype = Tuple{f, fieldtypes(T)...}
covering_method_insts = [mi for mi in method_insts if ftype <: mi.def.sig]
kwnames = only(kwnames_type_tuple.parameters).parameters
covering_method_insts = filter(method_insts) do mi
ftype <: mi.def.sig && has_kwargs(mi.def, kwnames)
end

method_doesnot_exist = isempty(covering_method_insts)
ret_func = method_doesnot_exist ? _hasmethod_false : _hasmethod_true
Expand All @@ -39,6 +46,21 @@ Like `hasmethod` but runs at compile-time (and does not accept a worldage argume
return ci
end

"checks if the method `m` accepts keyword arguments with the names `kwnames`"
function has_kwargs(m::Method, kwnames)
isempty(kwnames) && return true # no kwargs means any method matches

mt = Base.get_methodtable(m)
!isdefined(mt, :kwsorter) && return false # no kwsorter means no keywords for sure.

kws = Base.kwarg_decl(m, typeof(mt.kwsorter))
isempty(kws) && return false # no keyword args means doesn't accept these

# if accepts kwargs... then definately accepts these names
endswith(string(kws[end]), "...") && return true

return kwnames ⊆ kws
end


function create_codeinfo_with_returnvalue(argnames, spnames, sp, value)
Expand Down Expand Up @@ -73,7 +95,7 @@ static_methods(@nospecialize(f)) = static_methods(f, Tuple{Vararg{Any}})
ci.edges = Core.Compiler.vect(mt, Tuple{Vararg{Any}})
return ci
end

@static if VERSION < v"1.3"
const compat_hasmethod = hasmethod
else
Expand Down