BriefCase

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
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
{-# LANGUAGE Haskell2010 #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE FlexibleInstances #-}
{-# LANGUAGE MultiParamTypeClasses #-}
{-# LANGUAGE TypeFamilies #-}
{-# LANGUAGE TypeSynonymInstances #-}
module BriefCase
    ( CaseTable (..), CaseRow (..), CaseCell (..), AltTree (..)
    , BriefCaseM (..)
    , CaseTree (..), Alts (..), Alt (..)
    , briefCase
    ) where

import Prelude hiding (all, foldr, sequence)
import Control.Applicative
import Control.Monad hiding (sequence)
import Control.Monad.Trans.Fresh.Stream
import Data.Foldable
import Data.Fresh
import Data.Functor.Identity
import Data.Traversable
import Data.List (genericLength, genericReplicate)
import qualified Data.Map as M

data CaseTable    f c = CT  (f (Expr c))      [CaseRow f c]

data CaseRow      f c = CR  (f (CaseCell c))  (AltTree c)

data CaseCell c
    =  PName     (Name c)    (CaseCell c)
    |  PMatch    (Constr c)  [CaseCell c]
    |  PBang
    |  PWildCard

data AltTree c
    =  AltLeaf    (Expr c)
    |  AltBranch  [AltTree c]
    |  AltMatch   (CaseCell c) (Expr c)  (AltTree c)
    |  AltBind0   (Name c) (Name c)      (AltTree c)
    |  AltBind2   (Binding c)            (AltTree c)

class (Applicative m, Monad m) => BriefCaseM m where
    type Binding  m :: *
    type Constr   m :: *
    type Expr     m :: *
    type Name     m :: *

    freshName :: m (Name m, Expr m)
    warnOverlapped :: (worklist ~ []) => [CaseRow worklist m] -> m ()

data Alts  c = Alts  [Alt c] (Maybe (CaseTree c))
data Alt   c = Alt   (Constr c) [Name c] (CaseTree c)
data CaseTree c
    =  CaseNode (Expr c) (Alts c)
    |  LeafExpr (Expr c)
    |  Let0 (Name c) (Name c)      (CaseTree c)
    |  Let1 (Name c) (CaseTree c)  (CaseTree c)
    |  Let2 (Binding c)            (CaseTree c)

briefCase
    :: (BriefCaseM m, worklist ~ [], Ord (Constr m))
    => CaseTable worklist m -> CaseTree m -> m (CaseTree m)

briefCase (CT _ []) d = return d

briefCase (CT [] (CR [] aa_ : alts')) d = case aa_ of
    AltLeaf e
        | null alts' -> return (LeafExpr e)
        | otherwise  -> warnOverlapped alts' >> return (LeafExpr e)

    AltBranch [] -> briefCase (CT [] alts') d
    AltBranch (aa:aas) -> do
        (fn, e') <- freshName

        d1 <- briefCase (CT [] [CR [] aa]) (LeafExpr e')
        d2 <- briefCase (CT [] (CR [] (AltBranch aas) : alts')) d

        return $ Let1 fn d2 d1

    AltMatch p2 e2 aa -> do
        (fn, e') <- freshName

        d1 <- briefCase (CT [e2] [CR [p2] aa]) (LeafExpr e')
        d2 <- briefCase (CT [] alts') d

        return $ Let1 fn d2 d1

    AltBind0 n1 n2  aa -> Let0 n1 n2  <$> briefCase (CT [] (CR [] aa : alts')) d
    AltBind2 bnd    aa -> Let2 bnd    <$> briefCase (CT [] (CR [] aa : alts')) d


briefCase (CT (e:es) alts) d = do
    (nScrutinee,  eScrutinee)  <- freshName
    (nTailRef,    eTailRef)    <- freshName

    eTail <- briefCase (CT (eScrutinee:es) tailRs) d
    let wrap  =  Let1 nScrutinee (LeafExpr e)
              .  Let1 nTailRef eTail

    let d' = LeafExpr eTailRef
    let e' = eScrutinee

    let (conRs, bangRs, wildRs) = wipeAllAliases nScrutinee

    varRs2 <- briefCase (CT es (map getCaseRow (bangRs ++ wildRs))) d'

    if null conRs && null bangRs
        then return . wrap $ varRs2
        else do
            (nVarRsRef, eVarRsRef) <- freshName

            conRs2  <-  traverse (mapEntryToAlt (LeafExpr eVarRsRef))
                    .   M.toAscList . M.fromListWith (++)
                    .   map conAltToMapEntry
                    $   conRs

            return  .   wrap
                    .   Let1 nVarRsRef varRs2
                    .   CaseNode e'
                    $   Alts conRs2 (Just (LeafExpr eVarRsRef))

  where
    (conRs', bangRs', wildRs', tailRs) = zebraStep alts
    wipeAllAliases n =   ( map (wipeAliases n) conRs'
                         , map (wipeAliases n) bangRs'
                         , map (wipeAliases n) wildRs'
                         )

    conAltToMapEntry
        :: (worklist ~ [])
        => Zalt (Consy c) worklist c -> ((Constr c, Integer), [CaseRow worklist c])
    conAltToMapEntry Zalt { getPayload = Consy n ps, getCaseRow = CR ps2 aa}
        = ((n, genericLength ps), [CR (ps ++ ps2) aa])

    mapEntryToAlt defAlt ((cName, cArity), alts') = do
        cvs <- genericReplicateM cArity freshName
        tree <- briefCase (CT (map snd cvs ++ es) alts') defAlt
        return $ Alt cName (map fst cvs) tree


zebraStep
    ::  (worklist ~ [], poppedWL ~ [])
    =>  [CaseRow worklist c]
    ->  ( [Zalt (Consy c) poppedWL c]
        , [Zalt Varsy poppedWL c]
        , [Zalt Varsy poppedWL c]
        , [CaseRow worklist c])
zebraStep alts = (conAlts, bangAlts, wildAlts, tailAlts)
  where
    (conAlts,   notConAlts) = splitMaybe eatConAlt          alts
    (bangAlts,  irrAlts)    = splitMaybe (eatVarAlt True)   notConAlts
    (wildAlts,  tailAlts)   = splitMaybe (eatVarAlt False)  irrAlts



eatConAlt
    :: (worklist ~ [])
    => CaseRow worklist c -> Maybe (Zalt (Consy c) worklist c)
eatConAlt (CR (p_ : ps) aa) = case p_ of
    PName   n p -> fmap (addAlias n) $ eatConAlt (CR (p:ps) aa)
    PMatch  n p -> Just $ Zalt [] (Consy n p) (CR ps aa)
    _ -> Nothing
eatConAlt _ = Nothing

eatVarAlt
    :: (worklist ~ [])
    => Bool -> CaseRow worklist c -> Maybe (Zalt Varsy worklist c)
eatVarAlt bang (CR (p_ : ps) aa) = case p_ of
    PName n np -> fmap (addAlias n) $ eatVarAlt bang (CR (np:ps) aa)
    PWildCard  | not bang  -> Just $ Zalt [] Varsy (CR ps aa)
    PBang      | bang      -> Just $ Zalt [] Varsy (CR ps aa)
    _ -> Nothing
eatVarAlt _ _ = Nothing

data Zalt t worklist c = Zalt
    { getAliases :: [Name c]
    , getPayload :: t
    , getCaseRow :: CaseRow worklist c
    }
data Consy c = Consy (Constr c) [CaseCell c]
data Varsy = Varsy

addAlias :: Name c -> Zalt t worklist c -> Zalt t worklist c
addAlias n z = z {getAliases = n : getAliases z}

wipeAliases
    :: (Foldable worklist)
    => Name c -> Zalt t worklist c -> Zalt t worklist c
wipeAliases n (Zalt aliases opaque (CR x3 tr)) = Zalt [] opaque (CR x3 tr')
  where
    tr' = foldr (\an t -> AltBind0 an n t) tr aliases


splitMaybe :: (a -> Maybe r) -> [a] -> ([r], [a])
splitMaybe f = (\(x, y) -> (reverse x, y)) . go []
  where
    go acc [] = (acc, [])
    go acc (x:xs) = case f x of
        Just y -> go (y:acc) xs
        Nothing -> (acc, (x:xs))

genericReplicateM :: (Integral i, Monad m) => i -> m a -> m [a]
genericReplicateM n a = sequence (genericReplicate n a)
195:17: Warning: Use first
Found:
\ (x, y) -> (reverse x, y)
Why not:
Control.Arrow.first reverse
200:20: Warning: Redundant bracket
Found:
(acc, (x : xs))
Why not:
(acc, x : xs)