Skip to content

The macro kwdef creates invalid code if used with a parametrized struct #60508

@ufechner7

Description

@ufechner7

The code:

using StaticArrays

Base.@kwdef mutable struct SysState{P}
    acc::Float64 = 0
    "vector of particle positions in x [m]"
    X::MVector{P, Float64} = zeros(P)
end

gives the following warning in JETLS.jl:

`KiteUtils.P` is not defined

The code expands to:

julia> ex = @macroexpand Base.@kwdef mutable struct SysState{P}
           acc::Float64 = 0
           "vector of particle positions in x [m]"
           X::Vector{P} = zeros(P)
       end
quote
    #= util.jl:630 =#
    begin
        $(Expr(:meta, :doc))
        mutable struct SysState{P}
            #= REPL[4]:2 =#
            acc::Float64
            #= REPL[4]:3 =#
            "vector of particle positions in x [m]"
            X::Vector{P}
        end
    end
    #= util.jl:631 =#
    begin
        function SysState(; acc = 0, X = zeros(P))
            #= REPL[4]:1 =#
            SysState(acc, X)
        end
        function SysState{P}(; acc = 0, X = zeros(P)) where P
            #= REPL[4]:1 =#
            SysState{P}(acc, X)
        end
    end
end

The problem is the function:

        function SysState(; acc = 0, X = zeros(P))
            #= REPL[4]:1 =#
            SysState(acc, X)
        end

It cannot work and should not be generated.

Workaround:

using Parameters, StaticArrays

@with_kw_noshow mutable struct SysState{P}
    acc::Float64 = 0
    "vector of particle positions in x [m]"
    X::MVector{P, Float64} = zeros(P)
end

This works without creating a warning in JETLS, but the invalid constructor is still generated.

Using Julia 1.12.3 on Ubuntu Linux

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions