summaryrefslogtreecommitdiff
path: root/tests/examples/ghc80/overloadedrecflds_generics.hs
blob: c2b4bd61201aa33673cc0d2cfe28aee176d4a1c4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
-- Test that DuplicateRecordFields doesn't affect the metadata
-- generated by GHC.Generics or Data.Data

-- Based on a Stack Overflow post by bennofs
-- (http://stackoverflow.com/questions/24474581)
-- licensed under cc by-sa 3.0

{-# LANGUAGE DuplicateRecordFields #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE DeriveDataTypeable #-}
{-# LANGUAGE DeriveGeneric #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE TypeFamilies #-}

import GHC.Generics
import Data.Data
import Data.Proxy

type family FirstSelector (f :: * -> *) :: Meta
type instance FirstSelector (M1 D x f) = FirstSelector f
type instance FirstSelector (M1 C x f) = FirstSelector f
type instance FirstSelector (a :*: b)  = FirstSelector a
type instance FirstSelector (M1 S s f) = s

data SelectorProxy (s :: Meta) (f :: * -> *) a = SelectorProxy
type SelectorProxy' (s :: Meta) = SelectorProxy s Proxy ()

-- Extract the first selector name using GHC.Generics
firstSelectorName :: forall a. Selector (FirstSelector (Rep a))
                  => Proxy a -> String
firstSelectorName _ =
    selName (SelectorProxy :: SelectorProxy' (FirstSelector (Rep a)))

-- Extract the list of selector names for a constructor using Data.Data
selectorNames :: Data a => a -> [String]
selectorNames = constrFields . toConstr

data T = MkT { foo :: Int } deriving (Data, Generic)
data U = MkU { foo :: Int, bar :: Bool } deriving (Data, Generic)

main = do -- This should yield "foo", not "$sel:foo:MkT"
          print (firstSelectorName (Proxy :: Proxy T))
          -- Similarly this should yield "foo"
          print (firstSelectorName (Proxy :: Proxy U))
          -- This should yield ["foo"]
          print (selectorNames (MkT 3))
          -- And this should yield ["foo","bar"]
          print (selectorNames (MkU 3 True))