JuliaData / StructTypes.jl

Abstract definitions and convenience methods for describing, processing, and constructing Julia objects
https://juliadata.github.io/StructTypes.jl/stable/
MIT License
80 stars 22 forks source link

Add `@auto` macro to automatically provide StructTypes definitions for a type tree #97

Open joshday opened 1 year ago

joshday commented 1 year ago

The goal here is to remove a lot of the boilerplate necessary for dealing with abstract types:

abstract type Vehicle end

StructTypes.@auto Vehicle  # Can be called *before* the concrete type definitions

struct Car <: Vehicle
    make::String
    model::String
    seatingCapacity::Int
    topSpeed::Float64
end

struct Truck <: Vehicle
    make::String
    model::String
    payloadCapacity::Float64
end

c = Car("Mercedes-Benz", "S500", 5, 250.1)

s = JSON3.write(c)

JSON3.read(s, Vehicle) == c

Under the hood:

  1. A __type__ key is added to the serialized JSON (configurable via @auto MyType mysubtypekey.
  2. I rely on eval to get the deserialized type from the __type__. I examine the Meta.parse-ed Expr to order to determine whether it's safe to eval. I typically don't mess with eval, so I may have missed something that makes this unsafe.
codecov[bot] commented 1 year ago

Codecov Report

Patch coverage: 34.78% and project coverage change: -1.97% :warning:

Comparison is base (9cca137) 75.31% compared to head (6e1b9f4) 73.34%.

Additional details and impacted files ```diff @@ Coverage Diff @@ ## main #97 +/- ## ========================================== - Coverage 75.31% 73.34% -1.97% ========================================== Files 2 2 Lines 401 424 +23 ========================================== + Hits 302 311 +9 - Misses 99 113 +14 ``` | [Files Changed](https://app.codecov.io/gh/JuliaData/StructTypes.jl/pull/97?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=JuliaData) | Coverage Δ | | |---|---|---| | [src/macros.jl](https://app.codecov.io/gh/JuliaData/StructTypes.jl/pull/97?src=pr&el=tree&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=JuliaData#diff-c3JjL21hY3Jvcy5qbA==) | `65.21% <34.78%> (-30.44%)` | :arrow_down: | ... and [1 file with indirect coverage changes](https://app.codecov.io/gh/JuliaData/StructTypes.jl/pull/97/indirect-changes?src=pr&el=tree-more&utm_medium=referral&utm_source=github&utm_content=comment&utm_campaign=pr+comments&utm_term=JuliaData)

:umbrella: View full report in Codecov by Sentry.
:loudspeaker: Have feedback on the report? Share it here.