StructTypes.jl icon indicating copy to clipboard operation
StructTypes.jl copied to clipboard

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

Open joshday opened this issue 2 years ago • 1 comments

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.

joshday avatar Aug 30 '23 21:08 joshday

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
@@            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 Coverage Δ
src/macros.jl 65.21% <34.78%> (-30.44%) :arrow_down:

... and 1 file with indirect coverage changes

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

codecov[bot] avatar Aug 30 '23 21:08 codecov[bot]