{-# LANGUAGE DefaultSignatures #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE ScopedTypeVariables #-}
{-# LANGUAGE TypeFamilies #-}
-- | Expression for 'Eq'.
module Language.LOL.Symantic.Expr.Eq where

import Data.Proxy (Proxy(..))
import Data.Type.Equality ((:~:)(Refl))

import Language.LOL.Symantic.Repr.Dup
import Language.LOL.Symantic.Trans.Common
import Language.LOL.Symantic.Type
import Language.LOL.Symantic.Expr.Common
import Language.LOL.Symantic.Expr.Lambda
import Language.LOL.Symantic.Expr.Bool

-- * Class 'Sym_Eq'

class Sym_Eq repr where
	eq :: Eq a => repr a -> repr a -> repr Bool
	default eq :: (Trans t repr, Eq a)
	           => t repr a -> t repr a -> t repr Bool
	eq = trans_map2 eq

instance (Sym_Eq r1, Sym_Eq r2) => Sym_Eq (Dup r1 r2) where
	eq (x1 `Dup` x2) (y1 `Dup` y2) = eq x1 y1 `Dup` eq x2 y2

-- * Type 'Expr_Eq'
-- | Expression.
data Expr_Eq (root:: *)
type instance Root_of_Expr      (Expr_Eq root)      = root
type instance Type_of_Expr      (Expr_Eq root)      = No_Type
type instance Sym_of_Expr       (Expr_Eq root) repr = (Sym_Eq repr)
type instance Error_of_Expr ast (Expr_Eq root)      = No_Error_Expr

eq_from
 :: forall root ty ast hs ret.
 ( ty ~ Type_Root_of_Expr (Expr_Eq root)
 , Type_Root_Lift Type_Bool (Type_Root_of_Expr root)
 , Type_Eq (Type_Root_of_Expr root)
 , Expr_from ast root
 , Error_Expr_Lift (Error_Expr (Error_of_Type ast ty) ty ast)
                   (Error_of_Expr ast root)
 , Root_of_Expr root ~ root
 , Type_Constraint Eq ty
 ) => ast -> ast
 -> Expr_From ast (Expr_Eq root) hs ret
eq_from ast_x ast_y ex ast ctx k =
	expr_from (Proxy::Proxy root) ast_x ctx $
	 \(ty_x::Type_Root_of_Expr root h_x) (Forall_Repr_with_Context x) ->
	expr_from (Proxy::Proxy root) ast_y ctx $
	 \(ty_y::Type_Root_of_Expr root h_y) (Forall_Repr_with_Context y) ->
	when_type_eq ex ast ty_x ty_y $ \Refl ->
	when_type_constraint ex (Proxy::Proxy Eq) ast ty_x $ \Dict ->
		k type_bool $ Forall_Repr_with_Context $
		 \c -> x c `eq` y c

-- ** Type 'Expr_Lambda_Bool_Eq'
-- | Convenient alias.
type Expr_Lambda_Bool_Eq lam
 = Expr_Root (Expr_Alt (Expr_Lambda lam)
             (Expr_Alt Expr_Bool
                       Expr_Eq))

-- | Convenient alias around 'expr_from'.
expr_lambda_bool_eq_from
 :: forall lam ast.
 Expr_from ast (Expr_Lambda_Bool_Eq lam)
 => Proxy lam
 -> ast
 -> Either (Error_of_Expr ast (Expr_Lambda_Bool_Eq lam))
           (Exists_Type_and_Repr (Type_Root_of_Expr (Expr_Lambda_Bool_Eq lam))
                                 (Forall_Repr (Expr_Lambda_Bool_Eq lam)))
expr_lambda_bool_eq_from _lam ast =
	expr_from (Proxy::Proxy (Expr_Lambda_Bool_Eq lam)) ast
	 Context_Empty $ \ty (Forall_Repr_with_Context repr) ->
		Right $ Exists_Type_and_Repr ty $
			Forall_Repr $ repr Context_Empty