Help with @generated

Apart from what I am asking below, I would really appreciate if someone could point me to some resource that explains the usage of the macro generated.

I want to write a function that will loop through an array and will do something. I try to optimise it, so I looked at the evalpoly function from Base. The code is the following:

function evalpoly(x, p::Tuple)
    if @generated
        N = length(p.parameters::Core.SimpleVector)
        ex = :(p[end])
        for i in N-1:-1:1
            ex = :(muladd(x, $ex, p[$i]))
        end
        ex
    else
        _evalpoly(x, p)
    end
end

I have hard time reading this. First of all I would expect that evalpoly is defined as @generated function, however the macro @generated appears in a conditional. What does this mean exactly?

Then it’s the line N = length(p.parameters::Core.SimpleVector). I undertstand what it evaluates to, but I don’t understand why. What is p.parameters?

Then after that what does the line ex = :(muladd(x, $ex, p[$i])) use a quote?

This is an optionally generated function. The manual explains these quite well: Metaprogramming · The Julia Language

The parameters field contains the type parameters of a DataType, which is stored as a Core.svec (a barebones array type, mainly used by parts of the compiler)., i.e. for Tuple{Int,Float64} it would be Core.svec(Int, Float64). This is only an implementation detail of how types are represented in the compiler though, so it should be used with care.

2 Likes