Skip to content

Instantly share code, notes, and snippets.

@tknopp
Last active August 29, 2015 14:01
Show Gist options
  • Save tknopp/ed53dc22b61062a2b283 to your computer and use it in GitHub Desktop.
Save tknopp/ed53dc22b61062a2b283 to your computer and use it in GitHub Desktop.
Julia Interfaces
_interfaces_func_key = Dict{Symbol,Vector{DataType}}()
# The values of the following dict are either nothing or a Vector of
# type tuples
_interfaces_signatures = Dict{(Symbol,DataType),Any}()
function addInterface(d::DataType, f::Symbol, signature=nothing)
if haskey(_interfaces_func_key, f)
push!(_interfaces_func_key[f], d)
else
_interfaces_func_key[f] = DataType[d]
end
if haskey(_interfaces_signatures, (f,d))
if _interfaces_signatures[(f,d)] != nothing
push!(_interfaces_signatures[(f,d)], signature)
end
else
if signature == nothing # now the signature will not be checked anymore
_interfaces_signatures[(f,d)] = nothing
else
_interfaces_signatures[(f,d)] = [signature]
end
end
end
function checkInterface(d::DataType)
for (f,itypes) in _interfaces_func_key
isInInterfaceTable = false
for it in itypes
if d <: it
isInMethodTable = false
if !isdefined(f)
error("Interface not implemented! $d has to implement ", string(f), " in order to be subtype of $it !")
end
mt = methods(eval(f))
if _interfaces_signatures[(f,it)] == nothing
for m in mt
if d <: m.sig[1]
isInMethodTable = true
end
end
if !isInMethodTable
error("Interface not implemented! $d has to implement ", string(f), " in order to be subtype of $it !")
end
else
for typeargs in _interfaces_signatures[(f,it)]
isInMethodTable = false
for m in mt
if length(m.sig) == length(typeargs)
same_signature = true
if !( d <: m.sig[1] )
same_signature = false
end
for i=2:length(m.sig)
if !( typeargs[i] <: m.sig[i] )
same_signature = false
end
end
if same_signature
isInMethodTable = true
end
end
end
if !isInMethodTable
error("Interface not implemented! $d has to implement ", string(f), " in order to be subtype of $it !")
end
end
end
end
end
end
return true
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment