Fwd: Reducing boilerplate

Sylvain Henry hsyl20 at gmail.com
Thu Mar 10 14:53:47 UTC 2016


Hi devs,

I would like to add the support for the following automatic
instance-deriving extension:

module M where

class G a where
    doG :: a -> Int

class P a where
  doP :: a -> Int
  doP _ = 10
  deriving instance G a where -- automatically derived instance
    doG = doP

data X = X
instance P X -- derive G X automatically

print (doG X) -- print 10

See the forwarded mail below for the real context. This extension has
been proposed by someone before as InstanceTemplates:
https://ghc.haskell.org/trac/ghc/wiki/InstanceTemplates

I have modified the parser and the renamer accordingly to get:

class M.G a_awb where
  M.doG :: a_awb -> Int
class M.P a_ap6 where
  M.doP :: a_ap6 -> Int
  M.doP _ = 10
  instance M.G a_ap6 where
    M.doG = M.doP

I am new to the compiler part of GHC, so I have a few questions before
I continue:
1a) does it make sense to store the renamed class instance declaration
in an interface file? (supposing it only uses exported methods/types;
we could check that)
1b) will it be possible to create a new instance declaration in
another module by just doing the substitution [a_ap6 -> X] in it?
(i.e. when we parse "instance P X", do we know that it means [a_ap6 ->
X] in class P (and not [a -> X])?)
2) maybe I should go a different way and store only the derived
instance methods as we store class default methods?

Any insight appreciated!

Thanks,
Sylvain


---------- Forwarded message ----------
From: Sylvain Henry <hsyl20 at gmail.com>
Date: 2016-03-05 14:56 GMT+01:00
Subject: Reducing boilerplate
To: Haskell Cafe <haskell-cafe at haskell.org>


Hi,

To write FFI bindings, I use c-storable-deriving [1] to automatically
derive CStorable instances for many data types (the only difference
between Storable and CStorable is that CStorable provides default
methods for types that have Generic instances):

{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE DeriveAnyClass #-}
...
data X = X
   { fieldStatus           :: Vector 24 Word8
   , fieldPadding         :: Word8
   } deriving (Generic, CStorable)

However I also need a Storable instance, hence I have to write (the
"c*" methods are provided by CStorable):

instance Storable X where
   peek        = cPeek
   poke        = cPoke
   alignment = cAlignment
   sizeOf      = cSizeOf

Is there a way to automatically generate this instance for every data
that has an instance of CStorable? Ideally, I would like to say once
and for all:

instance CStorable a => Storable a where
   peek        = cPeek
   poke        = cPoke
   alignment = cAlignment
   sizeOf      = cSizeOf

As I don't think it is currently possible, would it be sensible to add
the support for automatically derived instances attached to classes
(as a GHC extension)?

Regards,
Sylvain

[1] https://hackage.haskell.org/package/c-storable-deriving


More information about the ghc-devs mailing list