Skip to content

How to write a template type? #161

Open
@singularitti

Description

I have several types, they have the same fieldnames, but different names & tags in an XML file, i.e.,

@aml struct R "PP_R"
    type::String, att"type"
    size::UInt, att"size"
    columns::UN{UInt}, att"columns"
    text::String, txt""
end

@aml struct Rab "PP_RAB"
    type::String, att"type"
    size::UInt, att"size"
    columns::UN{UInt}, att"columns"
    text::String, txt""
end

where the only differences between R & Rab are their name & tags. I want to define a template type DataSection so that the following code

@aml struct DataSection{T} "tag"
    type::String, att"type"
    size::UInt, att"size"
    columns::UN{UInt}, att"columns"
    text::String, txt""
end

@aml struct DataSection{:R} "PP_R"
    type::String, att"type"
    size::UInt, att"size"
    columns::UN{UInt}, att"columns"
    text::String, txt""
end

@aml struct DataSection{:Rab} "PP_RAB"
    type::String, att"type"
    size::UInt, att"size"
    columns::UN{UInt}, att"columns"
    text::String, txt""
end

is automatically generated.

I tried to write an @amltag macro but it doesn't work:

macro amltag(T, t)
    return quote
        @aml struct DataSection{$T} $$t
            type::String, att"type"
            size::UInt, att"size"
            columns::UN{UInt}, att"columns"
            text::String, txt""
        end
    end
end

julia> @macroexpand1 @amltag(:R, "PP_R")
quote
    #= REPL[67]:3 =#
    #= REPL[67]:3 =# @aml struct DataSection{:R} $ "PP_R"
            #= REPL[67]:4 =#
            (type::String, att"type")
            #= REPL[67]:5 =#
            (size::UInt, att"size")
            #= REPL[67]:6 =#
            (columns::UN{UInt}, att"columns")
            #= REPL[67]:7 =#
            (text::String, txt"")
        end
end

As you see, there is an extra $ before "PP_R". I don't know if it is Julia's parsing mechanism causes this. If I put $$t the next line, it reduces to "PP_R" immediately

macro amltag(T, t)
     return quote
         @aml struct DataSection{$T}
             $t
             type::String, att"type"
             size::UInt, att"size"
             columns::UN{UInt}, att"columns"
             text::String, txt""
         end
     end
end

julia> @macroexpand1 @amltag(:R, "PP_R")
quote
    #= REPL[5]:3 =#
    #= REPL[5]:3 =# @aml struct DataSection{:R}
            #= REPL[5]:4 =#
            "PP_R"
            #= REPL[5]:5 =#
            (type::String, att"type")
            #= REPL[5]:6 =#
            (size::UInt, att"size")
            #= REPL[5]:7 =#
            (columns::UN{UInt}, att"columns")
            #= REPL[5]:8 =#
            (text::String, txt"")
        end
end

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions