packages feed

gongju-dissect-0.1.2.0: src/Gongju/Dissect.hs

{-# LANGUAGE BangPatterns #-}
{-# LANGUAGE DerivingStrategies #-}
{-# LANGUAGE EmptyCase #-}
{-# LANGUAGE EmptyDataDeriving #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE QuantifiedConstraints #-}
{-# LANGUAGE RankNTypes #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeOperators #-}
{-# LANGUAGE UndecidableInstances #-}
-- | Module: Gongju.Dissect
-- Description: Zero-dependency McBride Clown/Joker polynomial dissection and constant-stack traversals
--
-- Implements Conor McBride's /Clowns to the Left of me, Jokers to the Right/ (POPL 2008)
-- over 'GHC.Generics' polynomial functors, paired with an orphan-free 'DissectDict'
-- record for open-row representations (e.g., @Polytropos.Rep@) and tail-recursive
-- @tmap@ / @cataTail@ engines running in O(1) GHC host stack space.
module Gongju.Dissect
  ( -- * Polynomial Bifunctor Building Blocks
    Void2
  , absurd2
  , Unit2(..)
  , Clown(..)
  , Joker(..)
  , Sum2(..)
  , Prod2(..)
    -- * Dissection Class & Orphan-Free Dictionary
  , Dissect(..)
  , DissectDict(..)
  , dictFromDissect
    -- * Fixed Points & Constant-Stack Tail Traversals
  , Fix(..)
  , tmap
  , tmapWith
  , cataTail
  , cataTailWith
  , genericRight
  ) where

import Data.Bifunctor (Bifunctor (..))
import Data.Kind (Type)
import GHC.Generics
  ( Generic1 (..)
  , K1 (..)
  , M1 (..)
  , Par1 (..)
  , U1 (..)
  , (:*:) (..)
  , (:+:) (..)
  )

-- | Empty bifunctor (dissection of constant functors 'U1' and 'K1').
data Void2 c j
  deriving stock (Eq, Ord, Show)

-- | Eliminates an impossible 'Void2' value.
absurd2 :: Void2 c j -> a
absurd2 v = case v of {}

instance Functor (Void2 c) where
  fmap _ = absurd2

instance Bifunctor Void2 where
  bimap _ _ = absurd2

-- | Unit bifunctor (dissection of the identity functor 'Par1').
data Unit2 c j = Unit2
  deriving stock (Eq, Ord, Show)

instance Functor (Unit2 c) where
  fmap _ Unit2 = Unit2

instance Bifunctor Unit2 where
  bimap _ _ Unit2 = Unit2

-- | Evaluated elements to the left of the traversal focus.
newtype Clown f c j = Clown { runClown :: f c }
  deriving stock (Eq, Ord, Show)

instance Functor (Clown f c) where
  fmap _ (Clown x) = Clown x

instance Functor f => Bifunctor (Clown f) where
  bimap f _ (Clown x) = Clown (fmap f x)

-- | Unevaluated elements to the right of the traversal focus.
newtype Joker g c j = Joker { runJoker :: g j }
  deriving stock (Eq, Ord, Show)

instance Functor g => Functor (Joker g c) where
  fmap g (Joker y) = Joker (fmap g y)

instance Functor g => Bifunctor (Joker g) where
  bimap _ g (Joker y) = Joker (fmap g y)

-- | Coproduct of two dissected bifunctors.
data Sum2 p q c j
  = L2 !(p c j)
  | R2 !(q c j)
  deriving stock (Eq, Ord, Show)

instance (Bifunctor p, Bifunctor q) => Functor (Sum2 p q c) where
  fmap g (L2 x) = L2 (second g x)
  fmap g (R2 y) = R2 (second g y)

instance (Bifunctor p, Bifunctor q) => Bifunctor (Sum2 p q) where
  bimap f g (L2 x) = L2 (bimap f g x)
  bimap f g (R2 y) = R2 (bimap f g y)

-- | Product of two dissected bifunctors.
data Prod2 p q c j = Prod2 !(p c j) !(q c j)
  deriving stock (Eq, Ord, Show)

instance (Bifunctor p, Bifunctor q) => Functor (Prod2 p q c) where
  fmap g (Prod2 x y) = Prod2 (second g x) (second g y)

instance (Bifunctor p, Bifunctor q) => Bifunctor (Prod2 p q) where
  bimap f g (Prod2 x y) = Prod2 (bimap f g x) (bimap f g y)

-- | Polynomial functors supporting single-step left-to-right dissection.
--
-- @'right' (Left pj)@ enters a fresh container of unevaluated jokers @j@.
-- @'right' (Right (d, c))@ plugs an evaluated clown @c@ into the hole @d@
-- and advances to either the next joker @(j, d')@ or the finished container @p c@.
class (Functor p, Bifunctor (D p)) => Dissect p where
  type D p :: Type -> Type -> Type
  right :: Either (p j) (D p c j, c) -> Either (j, D p c j) (p c)

instance Dissect U1 where
  type D U1 = Void2
  right (Left U1) = Right U1
  right (Right (v, _)) = absurd2 v

instance Dissect (K1 i a) where
  type D (K1 i a) = Void2
  right (Left (K1 a)) = Right (K1 a)
  right (Right (v, _)) = absurd2 v

instance Dissect Par1 where
  type D Par1 = Unit2
  right (Left (Par1 j)) = Left (j, Unit2)
  right (Right (Unit2, c)) = Right (Par1 c)

instance (Dissect f, Dissect g) => Dissect (f :+: g) where
  type D (f :+: g) = Sum2 (D f) (D g)
  right (Left (L1 fj)) =
    case right (Left fj) of
      Left (j, df) -> Left (j, L2 df)
      Right fc     -> Right (L1 fc)
  right (Left (R1 gj)) =
    case right (Left gj) of
      Left (j, dg) -> Left (j, R2 dg)
      Right gc     -> Right (R1 gc)
  right (Right (L2 df, c)) =
    case right (Right (df, c)) of
      Left (j, df') -> Left (j, L2 df')
      Right fc      -> Right (L1 fc)
  right (Right (R2 dg, c)) =
    case right (Right (dg, c)) of
      Left (j, dg') -> Left (j, R2 dg')
      Right gc      -> Right (R1 gc)

instance (Dissect f, Dissect g) => Dissect (f :*: g) where
  type D (f :*: g) = Sum2 (Prod2 (D f) (Joker g)) (Prod2 (Clown f) (D g))
  right (Left (fj :*: gj)) =
    case right (Left fj) of
      Left (j, df) -> Left (j, L2 (Prod2 df (Joker gj)))
      Right fc     -> enterRight fc gj
  right (Right (L2 (Prod2 df (Joker gj)), c)) =
    case right (Right (df, c)) of
      Left (j, df') -> Left (j, L2 (Prod2 df' (Joker gj)))
      Right fc      -> enterRight fc gj
  right (Right (R2 (Prod2 (Clown fc) dg), c)) =
    case right (Right (dg, c)) of
      Left (j, dg') -> Left (j, R2 (Prod2 (Clown fc) dg'))
      Right gc      -> Right (fc :*: gc)

enterRight
  :: Dissect g
  => f c
  -> g j
  -> Either (j, Sum2 (Prod2 (D f) (Joker g)) (Prod2 (Clown f) (D g)) c j) ((f :*: g) c)
enterRight fc gj =
  case right (Left gj) of
    Left (j, dg) -> Left (j, R2 (Prod2 (Clown fc) dg))
    Right gc     -> Right (fc :*: gc)

instance Dissect f => Dissect (M1 i t f) where
  type D (M1 i t f) = D f
  right (Left (M1 fj)) =
    case right (Left fj) of
      Left (j, df) -> Left (j, df)
      Right fc     -> Right (M1 fc)
  right (Right (df, c)) =
    case right (Right (df, c)) of
      Left (j, df') -> Left (j, df')
      Right fc      -> Right (M1 fc)

-- | Generic 'right' implementation for any 'Generic1' functor whose 'Rep1' is 'Dissect'.
genericRight
  :: (Generic1 p, Dissect (Rep1 p))
  => Either (p j) (D (Rep1 p) c j, c)
  -> Either (j, D (Rep1 p) c j) (p c)
genericRight (Left pj) =
  case right (Left (from1 pj)) of
    Left (j, d) -> Left (j, d)
    Right repC  -> Right (to1 repC)
genericRight (Right (d, c)) =
  case right (Right (d, c)) of
    Left (j, d') -> Left (j, d')
    Right repC   -> Right (to1 repC)

-- | First-class dissection dictionary avoiding orphan instances for external representations
-- such as @Polytropos.Rep@ or row-indexed syntax functors.
newtype DissectDict p d = DissectDict
  { runDissectStep :: forall c j. Either (p j) (d c j, c) -> Either (j, d c j) (p c)
  }

-- | Lifts any 'Dissect' typeclass instance into a 'DissectDict'.
dictFromDissect :: Dissect p => DissectDict p (D p)
dictFromDissect = DissectDict right

-- | Recursive fixed point of a syntax functor.
newtype Fix p = Fix { unFix :: p (Fix p) }

-- | Strictly tail-recursive 'fmap' driven by an explicit 'DissectDict'.
tmapWith :: DissectDict p d -> (a -> b) -> p a -> p b
tmapWith dict f = go . runDissectStep dict . Left
  where
    go (Right pb)     = pb
    go (Left (a, d))  =
      let !b = f a
      in go (runDissectStep dict (Right (d, b)))

-- | Tail-recursive 'fmap' via 'Dissect'.
tmap :: Dissect p => (a -> b) -> p a -> p b
tmap = tmapWith dictFromDissect

-- | Strictly tail-recursive catamorphism running in O(1) GHC host stack space,
-- using an explicit heap-allocated stack of dissected continuation frames @[d v (Fix p)]@.
cataTailWith :: DissectDict p d -> (p v -> v) -> Fix p -> v
cataTailWith dict alg = load []
  where
    load stk (Fix pt) = next stk (runDissectStep dict (Left pt))
    unload [] !v      = v
    unload (d : stk) !v = next stk (runDissectStep dict (Right (d, v)))
    next stk (Left (t, d)) = load (d : stk) t
    next stk (Right pv)    =
      let !v = alg pv
      in unload stk v

-- | Tail-recursive catamorphism via 'Dissect'.
cataTail :: Dissect p => (p v -> v) -> Fix p -> v
cataTail = cataTailWith dictFromDissect