{-# LANGUAGE AllowAmbiguousTypes #-}
{-# LANGUAGE DataKinds #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE KindSignatures #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeApplications #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}

module Prolog.Programming.TypeHelper (
  FieldNames,
  recordFieldNames,
  typeName,
) where

import Data.Data (Typeable)
import Data.Kind (Type)
import Data.Proxy (Proxy (..))
import GHC.Generics (
  C,
  D,
  Generic (Rep),
  K1,
  M1,
  Meta (..),
  S,
  U1,
  type (:*:),
 )
import GHC.TypeLits (KnownSymbol, symbolVal)
import Type.Reflection (tyConName, typeRep, typeRepTyCon)

class FieldNames (f :: Type -> Type) where
  fieldNames :: [String]

instance FieldNames U1 where
  fieldNames :: [String]
fieldNames = []

instance
  KnownSymbol name
  => FieldNames (M1 S ('MetaSel ('Just name) su ss ds) (K1 i c))
  where
  fieldNames :: [String]
fieldNames = [Proxy name -> String
forall (n :: Symbol) (proxy :: Symbol -> *).
KnownSymbol n =>
proxy n -> String
symbolVal (forall {k} (t :: k). Proxy t
forall (t :: Symbol). Proxy t
Proxy @name)]

instance (FieldNames l, FieldNames r) => FieldNames (l :*: r) where
  fieldNames :: [String]
fieldNames = forall (f :: * -> *). FieldNames f => [String]
fieldNames @l [String] -> [String] -> [String]
forall a. [a] -> [a] -> [a]
++ forall (f :: * -> *). FieldNames f => [String]
fieldNames @r

instance FieldNames f => FieldNames (M1 C c f) where
  fieldNames :: [String]
fieldNames = forall (f :: * -> *). FieldNames f => [String]
fieldNames @f

instance FieldNames f => FieldNames (M1 D d f) where
  fieldNames :: [String]
fieldNames = forall (f :: * -> *). FieldNames f => [String]
fieldNames @f

recordFieldNames
  :: forall a. FieldNames (Rep a) => [String]
recordFieldNames :: forall a. FieldNames (Rep a) => [String]
recordFieldNames = forall (f :: * -> *). FieldNames f => [String]
fieldNames @(Rep a)

typeName :: forall a. Typeable a => String
typeName :: forall a. Typeable a => String
typeName = TyCon -> String
tyConName (TyCon -> String) -> (TypeRep a -> TyCon) -> TypeRep a -> String
forall b c a. (b -> c) -> (a -> b) -> a -> c
. TypeRep a -> TyCon
forall {k} (a :: k). TypeRep a -> TyCon
typeRepTyCon (TypeRep a -> String) -> TypeRep a -> String
forall a b. (a -> b) -> a -> b
$ forall a. Typeable a => TypeRep a
forall {k} (a :: k). Typeable a => TypeRep a
typeRep @a