I think it would be a super helpful addition to the julia ecosystem if we could check whether some function is defined for certain arguments or not.
To be precise, I don’t refer to applicable
or hasmethod
. They only check whether the FIRST LAYER is defined. Introducing an additional wrapper layer wrapper(args...; kwargs...) = original(args...; kwargs)
will let this approach fail very quickly. MethodErrors raised by internal functions won’t be recognized by applicable
or hasmethod
.
What I would really like to have is a method which I call isdef(f, args...)
/ isdef(f, ArgTypes...)
(it should work on types), which checks whether the given function does not return an error for the given args.
This requires typeinference, but maybe, I am not sure on this, it does not require full-fledged typeinference and hence may be easier supported.
Core.Compiler.return_type
is already a function which somehow supports this kind of type-inference, however it does not belong to the stable julia API and also has another goal: It tries to approximate the return type in an unpredictable manner.
For the wishes isdef
feature it would be really nice to implement a similar method which [EDIT: I added some further remarks in the following list, as it was mentioned that this wish-list is not as well-defined as it could be, I hope it is slightly better now]
-
approximate the result in a predictable and documentable manner
(of course in best case can even infer the correct result all the time, but if it would overestimate, e.g. saying some method is defined while it is not, that is also very useful. But it should only overestimate in one direction, either always to restrictive or always too permissive, but not random once these once this) - works on compile time (so that it can be used for dispatch to create specialized method implementations without performance drawback)
- can be made part of a stable API (as part of a package, or even as part of Julia itself, don’t mind, just stable)
My key question is whether something like this is possible to be implemented in Julia.
I tried a couple of approaches:
- Cassette.jl seems quite tedious for this and it seems that with it you need to reimplement almost all of Julia’s standard functions to work on type level. Doesn’t look promising.
- Just define the interface and let everyone implement the interface itself. It is also super tedious and prone to not be adopted because it is very time demanding to implement a type-inference version of your methods for every method.
- Looking into
Core.Compiler._return_type
quickly fails as methods are no longer able to be lookup by IDE (e.g.inf_for_methodinstance
orInferenceResult
), but still my guess is that this is the most promising approach, I only don’t know how to go forward.
Any help is highly appreciated. To add: I also would be willing to spend my free time to implementing it if it is possible.
best,
Stephan