Precompile function for types defined in other modules

Assume that I have a module Foo that defines a function foo, and another module Bars (note the final s) that depends on Foo and defines a new type Bar. Is it possible to precompile function foo for arguments of type Bar ??

Source code to clarify what I am talking about:

# File Foo.jl
module Foo
export foo

@generated function foo(x::T) where T
  println("Compiling foo function for type $T")
  quote
    x
  end
end

precompile(foo,(Int,))

end #module

# File Bars.jl
module Bars
using Foo
export Bar

struct Bar{T}
  x::T
end

precompile(foo,(Bar{Int},))

end # module

Checking what gets precompiled:

julia> push!(LOAD_PATH, pwd());

julia> using Foo
[ Info: Recompiling stale cache file /home/verdugo/.julia/compiled/v1.1/Foo.ji for Foo [top-level]
Compiling foo function for type Int64

julia> using Bars
[ Info: Recompiling stale cache file /home/verdugo/.julia/compiled/v1.1/Bars.ji for Bars [top-level]
Compiling foo function for type Bars.Bar{Int64}

julia> foo(1) # This statement is using the precompiled cache. As expected.
1

julia> bar = Bar(1)
Bar{Int64}(1)

julia> foo(bar) # This statement is not using the precompiled cache, why??
Compiling foo function for type Bar{Int64}
Bar{Int64}(1)

julia> foo(bar) # Now, it does not compile. As expected.
Bar{Int64}(1)

I think the problem is that foo function can only be precompiled by the Foo module. But, how to precompile it for type Bar? Is it possible?

My guess is that when Bars does the precompile it’s only compiling the function in Bars, so that if the Bars module were to call foo() it would use the precompiled version. Maybe if you exported foo in the Bars module?

I have tried to export foo in Bars, but, it does not work unfortunately

Looks like it’s related to this issue?

1 Like

Yes! I hope it is fixed soon