mkloczko / derive-storable

Deriving Storable instances using GHC.Generics
https://hackage.haskell.org/package/derive-storable
MIT License
15 stars 2 forks source link

Alternative to the overlapping instance #7

Open expipiplus1 opened 3 years ago

expipiplus1 commented 3 years ago

Not sure if this is of interest:

newtype GStored a = GStored a
instance (Generic a, GStorable' (Rep a), KnownNat (NoFields (Rep a)))
  => GStorable (GStored a) where
  gsizeOf _ = internalSizeOf (undefined :: Rep a p)
  galignment _ = internalAlignment (undefined :: Rep a p)
  gpeekByteOff ptr offset = GStored . G.to <$> internalPeekByteOff ptr offset
  gpokeByteOff ptr offset (GStored x) =
    internalPokeByteOff ptr offset (G.from x)

One can use -XDerivingStrategies to derive using this newtype

For example:

data Sphere = Sphere
  { spherePos   :: V4 Float
  , sphereColor :: V4 Float
  }
  deriving stock Generic
  deriving Storable via GStored Sphere
mkloczko commented 3 years ago

Sure, was mentioned in #4 too. it's just that would probably require the plugin to be reworked (which should be really done, but... that might require a few weeks of delving into GHC).

expipiplus1 commented 3 years ago

Yeah, it would be super to have that instead of it languishing on some branch!

mkloczko commented 3 years ago

Yeah, it's just performance is one of the requirements for having these. Plugin is grabbing the correct identifiers and correct types from GHC Core - and while this could be changed to find other types of bindings it's kind of a arms race against GHC.

Given enough time maybe one could generalise the idea of rewriting and recompiling GHC Core bindings - there's this hscCompileCoreExpression which compiles a Core expression into Any type. One could pass an annotation to a class/instance method that could hint the compiler to rewrite what's inside. There could be some GHC Core type checking involved using GADTs, or perhaps some existing machinery could be reused. That kind of plugin could be used for other things than this project.

There was also the type fun approach, but for the 20 test cases it ran out of memory on 8GB machine. But maybe that will change with GHC 9.0, or did already change for 8.10

expipiplus1 commented 3 years ago

There was also the type fun approach, but for the 20 test cases it ran out of memory on 8GB machine. But maybe that will change with GHC 9.0, or did already change for 8.10

Sounds very slow too!

Yeah, it's just performance is one of the requirements for having these. Plugin is grabbing the correct identifiers and correct types from GHC Core - and while this could be changed to find other types of bindings it's kind of a arms race against GHC.

Very understandable.