I’m again struggling with correct macro syntax. I have a macro that is doing it’s job as required but relies on eval()
, which I understand is not ideal.
The macro should insert fields of an existing struct
into a new struct
that is constructed with Base.@kwdef
. For testing purposes, I rely on the @kwredef
macro from
RedefStructs
.
using RedefStructs
macro mixin(expr)
x = eval(expr)
T = typeof(x)
values = [getfield(x, f) for f in fieldnames(T)]
output = Expr(:block)
for (f, type, v) in zip(fieldnames(T), fieldtypes(T), values)
push!(output.args, :($(esc(f))::$type = $v) )
end
:($output)
end
@kwredef mutable struct TabMixin
tab::String = "mail"
animate::Bool = false
end
@kwredef mutable struct Example
name::String = "Me"
button::Bool = true
@mixin TabMixin()
end
ex = Example()
propertynames(ex)
I tried to move all into the quote
part, but I failed…
macro mixin(expr)
quote
local x = $expr
local T = typeof(x)
local values = [Stipple.Observables.to_value(getfield(x, f)) for f in fieldnames(T)]
local output = Expr(:block)
for (f, type, v) in zip(fieldnames(T), fieldtypes(T), values)
push!(output.args, :( ($(esc(f)))::$type = $v) )
end
output
end
end
Can anyone help me here?