How do I programmatically get the documentation for a documented constant?
module MyMod
"""
This is MyAlias
"""
const MyAlias = Val{:Alias}
end
using .MyMod
Docs.doc(MyMod.MyAlias)
....
“…” just gives the documentation for Val
.
UPDATE:
I have a workaround for my particular situation but it doesn’t answer the more general question. I’m creating a constant in a macro so it looks a bit like this (note this is just for proof of concept and I didn’t really do any macro hygiene checking).
macro mymacro(const_name)
const_name_symbol = QuoteNode(const_name)
MyConst = :(const $const_name = Val{$const_name}())
quote
Base.@__doc__($MyConst)
function my_get_doc(::Type{Val{$sym_name}})
return Base.Docs.doc(Base.Docs.Binding($(@__MODULE__()), $(const_name_symbol)))
end
end
end
1 Like
Well, I got as far as using Base.Docs.doc(Base.Docs.Binding(Main, :MyAlias))
. However, I can’t figure out how to make a function that figures out the module and name without using a macro.
That only works if I use a macro. If I use a function it no longer works.
julia> my_get_doc(x) = @doc x
my_get_doc (generic function with 1 method)
julia> my_get_doc(MyMod.MyAlias)
No documentation found.
Binding x does not exist.
Oh I see. I don’t think it’s possible, because docstrings are attached to symbols, not to values.
It’s just a little odd because Docs.doc
works on functions without using a macro to turn it into a symbol.
Hmm interesting. After poking around in the internals, it looks like Base.doc
is a lot smarter than just a symbol lookup, but clearly its not foolproof.
I briefly tried to look into it and I think the problem is that Base.doc
looks at the type but @doc
receives the exact expression and turns it into a symbol. If there were a way to find the name of the exact instance of the variable being passed then I think it would be possible.