Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added support for generation of mutable structs #259

Open
wants to merge 1 commit into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
8 changes: 6 additions & 2 deletions src/codegen/CodeGenerators.jl
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ end
ResolvedProtoFile(rel_path, p) = ResolvedProtoFile(rel_path, p, Set{String}(), Set{String}())

Base.@kwdef struct Options
with_mutable_structs::Bool = false
include_vendored_wellknown_types::Bool = true
always_use_modules::Bool = true
force_required::Union{Nothing,Dict{String,Set{String}}} = nothing
Expand Down Expand Up @@ -59,6 +60,7 @@ include("utils.jl")
relative_paths::Union{String,Vector{String}},
search_directories::Union{String,Vector{String},Nothing}=nothing,
output_directory::Union{String,Nothing}=nothing;
with_mutable_structs::Bool=false,
include_vendored_wellknown_types::Bool=true,
always_use_modules::Bool=true,
force_required::Union{Nothing,Dict{String,Set{String}}}=nothing,
Expand Down Expand Up @@ -88,6 +90,7 @@ All imported `.proto` files are compiled as well; an error is thrown if they can
- `output_directory::Union{String,Nothing}=nothing`: Path to store the generated Julia source code. When omitted, the translated code is saved to temp directory, the path is shown as a @info log.

# Keywords
- `with_mutable_structs::Bool=false`: If set to `true`, generate structs that are mutable in nature.
- `include_vendored_wellknown_types::Bool=true`: Append `ProtoBuf.VENDORED_WELLKNOWN_TYPES_PARENT_PATH` to `search_directories`, making the "well-known" message definitions available.
- `always_use_modules::Bool=true`: Generate julia code in a module even if the `.proto` file doesn't contain a `package` specifier. The module name of `{file_name}.proto` file is `{file_name}_pb`.
- `force_required::Union{Nothing,Dict{String,Set{String}}}=nothing`: Assume `message` and `oneof` fields to be aleways send over the wire -- then we woudln't need to `Union` their respective types with `Nothing`. E.g:
Expand Down Expand Up @@ -127,14 +130,15 @@ function protojl(
relative_paths::Union{<:AbstractString,<:AbstractVector{<:AbstractString}},
search_directories::Union{<:AbstractString,<:AbstractVector{<:AbstractString},Nothing}=nothing,
output_directory::Union{<:AbstractString,Nothing}=nothing;
with_mutable_structs::Bool=false,
include_vendored_wellknown_types::Bool=true,
always_use_modules::Bool=true,
force_required::Union{Nothing,<:Dict{<:AbstractString,<:Set{<:AbstractString}}}=nothing,
add_kwarg_constructors::Bool=false,
parametrize_oneofs::Bool=false,
common_abstract_type::Bool = false,
)
options = Options(include_vendored_wellknown_types, always_use_modules, force_required, add_kwarg_constructors, parametrize_oneofs, common_abstract_type)
options = Options(with_mutable_structs, include_vendored_wellknown_types, always_use_modules, force_required, add_kwarg_constructors, parametrize_oneofs, common_abstract_type)
return _protojl(relative_paths, search_directories, output_directory, options)
end

Expand Down Expand Up @@ -176,7 +180,7 @@ function _protojl(
foreach(p->get_all_transitive_imports!(p, parsed_files), values(parsed_files))
# Files within the same package could use definitions from different files
# without fully qualifying their name -- on Julia side, we need to make sure
# the files are read in order that respect these implicit dependencies.
# the files are read in order that respect these implicit dependencies.codegen
resolve_inter_package_references!(parsed_files, options)
sorted_files, cyclical_imports = _topological_sort(parsed_files)
!isempty(cyclical_imports) && throw(error(string(
Expand Down
3 changes: 2 additions & 1 deletion src/codegen/toplevel_definitions.jl
Original file line number Diff line number Diff line change
Expand Up @@ -85,8 +85,9 @@ function generate_struct(io, t::MessageType, ctx::Context)
abstract_base_name = pop!(ctx._curr_cyclic_defs, t.name, "")
type_params = get_type_params(t, ctx)
params_string = get_type_param_string(type_params)
struct_definition = ctx.options.with_mutable_structs ? "mutable struct " : "struct "

print(io, "struct ", struct_name, length(t.fields) > 0 ? params_string : ' ', _maybe_subtype(abstract_base_name, ctx.options))
print(io, struct_definition, struct_name, length(t.fields) > 0 ? params_string : ' ', _maybe_subtype(abstract_base_name, ctx.options))
# new line if there are fields, otherwise ensure that we have space before `end`
length(t.fields) > 0 ? println(io) : print(io, ' ')
for field in t.fields
Expand Down
32 changes: 32 additions & 0 deletions test/test_codegen.jl
Original file line number Diff line number Diff line change
Expand Up @@ -148,6 +148,28 @@ end
@test CodeGenerators.jl_init_value(p.definitions["B"].fields[1], ctx) == "Ref{A}()"
end

@testset "`with_mutable_structs` option makes the generated struct mutable" begin
s, p, ctx = translate_simple_proto("message A {} message B { optional A a = 1; }", Options(with_mutable_structs=true))
ctx._toplevel_name[] = "B"
@test generate_struct_str(p.definitions["B"], ctx) == """
mutable struct B
a::Union{Nothing,A}
end
"""
@test CodeGenerators.jl_default_value(p.definitions["B"].fields[1], ctx) === "nothing"
@test CodeGenerators.jl_init_value(p.definitions["B"].fields[1], ctx) == "Ref{Union{Nothing,A}}(nothing)"

s, p, ctx = translate_simple_proto("message A {} message B { optional A a = 1; }", Options(with_mutable_structs=true))
ctx._toplevel_name[] = "B"
@test generate_struct_str(p.definitions["B"], ctx) == """
mutable struct B
a::Union{Nothing,A}
end
"""
@test CodeGenerators.jl_default_value(p.definitions["B"].fields[1], ctx) === "nothing"
@test CodeGenerators.jl_init_value(p.definitions["B"].fields[1], ctx) == "Ref{Union{Nothing,A}}(nothing)"
end

@testset "Struct fields are optional when not marked required" begin
s, p, ctx = translate_simple_proto("syntax = \"proto3\"; message A {} message B { A a = 1; }")
ctx._toplevel_name[] = "B"
Expand Down Expand Up @@ -178,6 +200,16 @@ end
"""
@test CodeGenerators.jl_default_value(p.definitions["B"].fields[1], ctx) === nothing
@test CodeGenerators.jl_init_value(p.definitions["B"].fields[1], ctx) == "Ref{A}()"

s, p, ctx = translate_simple_proto("message A {} message B { required A a = 1; }", Options(with_mutable_structs=true))
ctx._toplevel_name[] = "B"
@test generate_struct_str(p.definitions["B"], ctx) == """
mutable struct B
a::A
end
"""
@test CodeGenerators.jl_default_value(p.definitions["B"].fields[1], ctx) === nothing
@test CodeGenerators.jl_init_value(p.definitions["B"].fields[1], ctx) == "Ref{A}()"
end

@testset "Struct fields are optional when the type is self referential" begin
Expand Down
Loading