Add lines of code in a struct definition

Actually, I ended up seeing something similar to that which helped me. Basically the macro that inserted the lines used the form

macro add_some_fields()
    return esc(:(A::Int64; B::Float64))
end

Which worked as expected. The only problem is that my macro produced the fields and the types by looking at a parent object that was an input. Now let us say I wanted to create a pump type CentrifugalPump_Type and inherit all the fields from GenericPump_Type some exceptions (such as specifications). I would have to generate a string representing that code and then parse it. When I used the following command:

InnerExp = :(
    A::Int64;
    B::Float64; )

I would get

quote
    A::Int64
    #= none:1 =#
    B::Float64
end

I tried using

CodeLines = "A::Int64; B::Float64"
InnerExp = Meta.parse("quote $CodeLines end")
>>
:($(Expr(:quote, quote
    #= none:1 =#
    A::Int64
    #= none:1 =#
    B::Float64
end)))

This was not the result I expected, but buried somewhere in the internet, I found someone suggesting a begin … end statement. So I tried this

InnerExp = Meta.parse("begin $CodeLines end")
quote
    #= none:1 =#
    A::Int64
    #= none:1 =#
    B::Float64
end

Which yielded the same result as :( A::Int64; B::Float64; ). So I guess putting multiple lines in an expression is implicitly assuming a “begin…end” statement. This is what ended up working in the simple macro.

macro add_some_fields()
    CodeLines = "A::Int64; B::Float64"
    return esc(Meta.parse("begin $CodeLines end"))
end

Now that CodeLines are strings, I can very easily generate any kind of code that I want.

1 Like