What is the best way to annotate code that is both machine and human readable?

My first thought would be parseable structured docstrings, but this seems too fragile. My second thought is macros that just emit the main expression they take in while ignoring the rest.

We could use these annotations to markup code. This could be useful for code analysis such as checking interfaces.

macro implements(interface, ex)
    return ex

@implements AbstractArrayInterface begin
    struct MyZeroVector <: AbstractVector{Int} end
    Base.size(::MyZeroVector) = (5,)
    Base.getindex(::MyZeroVector, i...) = 0

While the above does nothing by itself, a code analyzer could use the annotating macro to identify if the code within satisfies the interface.

Is there another way to annotate code in this way?


I think this would be the most sensible thing to do. Most likely you’d want to register the contained code in some global place as well so you can access it programmatically whithout having to parse the files again.

I believe this is what the :meta mechanism is all about.

In case you weren’t aware, this is more or less the approach taken by TestItems: the @testitem macro is defined to do nothing in regular package code

but the macro itself is used as an annotation for TestItemRunner to identify test definitions:

So I think this validates the feasibility of such an approach.

1 Like

When you say “human readable”, do you mean users or maintainers? iow, do you mean the code is readable or that it generates relevant documentation?

Showing the implementation of a getindex seems like too much detail for documentation. Showing the InterfaceSpecs of a function seems good.

I’m just trying to add information about my code that can be parsed and that is also intelligible to a human.

The above example has no effect for Julia. However, a static checker could parse my code and see if the code contained within implements the abstract array interface. One could also use this to build documentation as you mentioned.