Macro to create a struct with variable number of fields?

My first failed attempt at a macro! I want to be able to generate a struct definition by passing a classname and fields. May code should look something like this?

macro create_class(classname, fields)
    quote
        mutable struct $classname
            $(fields...)
            function $classname($(fields...))
                new($(fields...))
            end
        end
    end
end

A macro is basically a function for syntax. So could you write down the input syntax and the desired output syntax?

Then you can run dump on the input and output syntax and figure out how to do the transformation.

4 Likes

You might be looking for something like this:

macro create_class(classname, fields...)
    quote
        mutable struct $classname
            $(fields...)
            function $classname($(fields...))
                new($(fields...))
            end
        end
    end
end
julia> @macroexpand @create_class foo bar baz
quote
    #= REPL[11]:3 =#
    mutable struct foo
        #= REPL[11]:4 =#
        bar
        baz
        #= REPL[11]:5 =#
        function foo(#3#bar, #4#baz)
            #= REPL[11]:6 =#
            new(#3#bar, #4#baz)
        end
    end
end

or this:

macro create_class2(classname, fields_tuple)
    fields = fields_tuple.args
    quote
        mutable struct $classname
            $(fields...)
            function $classname($(fields...))
                new($(fields...))
            end
        end
    end
end
julia> @macroexpand @create_class2 foo (bar, baz)
quote
    #= REPL[15]:4 =#
    mutable struct foo
        #= REPL[15]:5 =#
        bar
        baz
        #= REPL[15]:6 =#
        function foo(#7#bar, #8#baz)
            #= REPL[15]:7 =#
            new(#7#bar, #8#baz)
        end
    end
end

In any case, I would recommend following kristoffer’s advice, especially the part about dump()ing the macro arguments since I think that was what caused you problems here.

2 Likes