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
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
|
{-
Pattern match compilation + exhaustiveness check
Ideas came mainly from the following sources:
- "GADTs meet their match"
- "The implementation of functional programming languages", Chapter 5, "Efficient compilation of pattern matching"
-}
{-# LANGUAGE NoMonomorphismRestriction #-}
{-# LANGUAGE PatternSynonyms #-}
{-# LANGUAGE ViewPatterns #-}
{-# LANGUAGE FlexibleContexts #-}
{-# LANGUAGE LambdaCase #-}
import Data.List
import Data.Map (Map)
import qualified Data.Map as Map
import Data.Maybe
import Data.Either
import Control.Arrow ((***))
import Control.Monad.Identity
import Control.Monad.State
import Control.Monad.Writer hiding (Alt)
import Text.Show.Pretty (ppShow)
-------------------------------------------------------------------------------- Name generator monad
type NewName = StateT Int
newName :: Monad m => NewName m String
newName = state $ \i -> ("v" ++ show i, i + 1)
-------------------------------------------------------------------------------- data types
type Loc = Int -- location info
type VarName = String
type ConName = String
------------------------------- source data structure
{-
match a b c with
(x:y) (f x -> Just ((>3) -> True)) v@(_:_)@v'@(g -> True)
| x > 4 -> ...
| Just (z: v) <- h y, Nothing <- h' z, h'' v -> ...
| ...
where
...
...
-}
{-
match a with
x: y | [] <- a -> ... x ... y ... z ... v ...
-}
data Match = Match [VarName] [Clause] -- match expression (generalized case expression)
data Clause = Clause Loc [ParPat] GuardTree
type ParPat = [Pat] -- parallel patterns like v@(f -> [])@(Just x)
data Pat
= PVar VarName
| Con ConName [ParPat]
| ViewPat Exp ParPat
deriving Show
data GuardTree
= GuardNode Loc Exp ConName [ParPat] GuardTree
| Where Binds GuardTree
| Alts [GuardTree]
| GuardLeaf Loc Exp
deriving Show
type Binds = [(VarName, Exp)]
unWhereAlts :: GuardTree -> Maybe (Binds, [GuardTree])
unWhereAlts = f [] where
f acc = \case
Where bs t -> f (acc ++ bs) t
Alts xs -> g acc xs
x -> Just (acc, [x])
g acc [] = Nothing
g acc (x: xs) = case unWhereAlts x of
Nothing -> g acc xs
Just (wh, ts) -> Just (acc ++ wh, ts ++ xs)
guardNode :: Loc -> Exp -> ParPat -> GuardTree -> GuardTree
guardNode i v [] e = e
guardNode i v (w: ws) e = case w of
PVar x -> guardNode i v (subst x v ws) $ subst x v e -- don't use let instead
ViewPat f p -> guardNode i (ViewApp f v) p $ guardNode i v ws e
Con s ps' -> GuardNode i v s ps' $ guardNode i v ws e
guardNodes :: Loc -> [(Exp, ParPat)] -> GuardTree -> GuardTree
guardNodes _ [] l = l
guardNodes i ((v, ws): vs) e = guardNode i v ws $ guardNodes i vs e
type CasesInfo = [(Exp, Either (String, [String]) (Exp, Exp))]
type InfoWriter = Writer ([Loc], [Loc], [CasesInfo])
------------------------------- target data structures
data Exp
= IdExp (Map VarName Exp) Loc -- arbitrary expression
| Undefined
| Otherwise
| Case Exp [Alt]
| Var VarName
| ViewApp Exp Exp
| Let Binds Exp
deriving (Show, Eq)
where_ [] = id
where_ bs = Let bs
data Alt = Alt ConName [VarName] Exp
deriving (Show, Eq)
getId = \case
IdExp _ i -> i
data Info
= Uncovered [ParPat]
| Inaccessible Int
| Removable Int
| Shared Int Int
deriving Show
-------------------------------------------------------------------------------- conversions between data structures
matchToGuardTree :: Match -> GuardTree
matchToGuardTree (Match vs cs)
= Alts $ flip map cs $ \(Clause i ps rhs) ->
guardNodes i (zip (map Var vs) ps) rhs
guardTreeToCases :: CasesInfo -> GuardTree -> NewName InfoWriter Exp
guardTreeToCases seq t = case unWhereAlts t of
Nothing -> tell ([], [], [seq]) >> return Undefined
Just (wh, GuardLeaf i e: _) -> tell ([i], [], []) >> return (where_ wh e)
Just (wh, cs@(GuardNode i f s _ _: _)) -> do
tell ([], [i], [])
where_ wh . Case f <$> sequence
[ do
ns <- replicateM cv newName
fmap (Alt cn ns) $ guardTreeToCases ((f, Left (cn, ns)): appAdd f seq) $ Alts $ map (filterGuardTree f cn ns) cs
| (cn, cv) <- fromJust $ find ((s `elem`) . map fst) contable
]
e -> error $ "gtc: " ++ show e
where
appAdd (ViewApp f v) x = (v, Right (f, ViewApp f v)): appAdd v x
appAdd _ x = x
filterGuardTree :: Exp -> ConName -> [VarName] -> GuardTree -> GuardTree
filterGuardTree f s ns = \case
Where bs t -> Where bs $ filterGuardTree f s ns t -- TODO: shadowing
Alts ts -> Alts $ map (filterGuardTree f s ns) ts
GuardLeaf i e -> GuardLeaf i e
GuardNode i f' s' ps gs
| f /= f' -> GuardNode i f' s' ps $ filterGuardTree f s ns gs
| s == s' -> filterGuardTree f s ns $ guardNodes i (zip (map Var ns) ps) gs
| otherwise -> Alts []
mkInfo :: Int -> InfoWriter ([VarName], Exp) -> (Exp, [Info])
mkInfo i (runWriter -> ((ns, e'), (is, nub -> js, us)))
= ( e'
, [ (if n > 1 then Shared n else if j `elem` js then Inaccessible else Removable) j
| j <- [1..i], let n = length $ filter (==j) is, n /= 1
] ++ map (Uncovered . mkPat (map Var ns)) us
)
where
mkPat :: [Exp] -> CasesInfo -> [ParPat]
mkPat ns ls = map f ns
where
f v' = mconcat [either (\(s, vs) -> [Con s $ map (f . Var) vs]) (\(s, v) -> [ViewPat s $ f v]) ps | (v, ps) <- ls, v == v']
tester :: [[ParPat]] -> IO ()
tester cs@(ps: _) = putStrLn . ppShow . mkInfo (length cs) . flip evalStateT 1 $ do
vs <- replicateM (length ps) newName
let gs = matchToGuardTree $ Match vs $ zipWith (\a i -> Clause i a $ GuardLeaf i $ IdExp mempty i) cs [1..]
(,) vs <$> guardTreeToCases [] gs
-------------------------------------------------------------------------------- substitution
class Subst a where subst :: VarName -> Exp -> a -> a
substs :: (Subst b) => Binds -> b -> b
substs rs g = foldr (uncurry subst) g rs
instance Subst a => Subst [a] where subst a b = map (subst a b)
instance (Subst a, Subst b) => Subst (a, b) where subst a b (c, d) = (subst a b c, subst a b d)
instance Subst Exp where
subst a b = \case
Var v | v == a -> b
| otherwise -> Var v
ViewApp f x -> ViewApp (subst a b f) (subst a b x)
IdExp m i -> IdExp (Map.insert a b $ subst a b <$> m) i
instance Subst Pat where
subst as v = \case
Con s ps -> Con s $ map (subst as v) ps
ViewPat f p -> ViewPat (subst as v f) $ subst as v p
PVar x -> PVar x
instance Subst GuardTree where
subst a b = \case
Alts ts -> Alts $ subst a b ts
Where bs e -> Where (map (id *** subst a b) bs) $ subst a b e
GuardNode i e y z x -> GuardNode i (subst a b e) y (subst a b z) $ subst a b x
GuardLeaf i e -> GuardLeaf i (subst a b e)
-------------------------------------------------------------------------------- constructors
contable =
[ ["Nil" # 0, "Cons" # 2]
, ["False" # 0, "True" # 0]
, ["Nothing" # 0, "Just" # 1]
] where (#) = (,)
pattern Nil = Con' "Nil" []
pattern Cons a b = Con' "Cons" [a, b]
pattern T = Con' "True" []
pattern F = Con' "False" []
pattern No = Con' "Nothing" []
pattern Ju a = Con' "Just" [a]
pattern W = []
pattern V v = [PVar v]
pattern Con' s ps = [Con s ps]
pattern Vi f p = [ViewPat (Var f) p]
pattern Guard e = (e, T)
-------------------------------------------------------------------------------- test cases
diagonal_test = tester
[ [W, T, F]
, [F, W, T]
, [T, F, W]
]
seq_test = tester
[ [W, F]
, [T, F]
, [W, W]
]
reverseTwo_test = tester
[ [Cons (V "x") (Cons (V "y") Nil)]
, [V "xs"]
]
xor_test = tester
[ [V "x", F]
, [F, T]
, [T, T]
]
unwieldy_test = tester
[ [Nil, Nil]
, [V "xs", V "ys"]
]
last_test = tester
[ [Cons (V "x") Nil]
, [Cons (V "y") (V "xs")]
]
last_test' = tester
[ [Cons (V "x") Nil]
, [Cons (V "y") (Cons (V "x") (V "xs"))]
]
zipWith_test = tester
[ [V "g", Nil, W]
, [V "f", W, Nil]
, [V "f", Cons (V "x") (V "xs"), Cons (V "y") (V "ys")]
]
zipWith_test' = tester
[ [V "f", Cons (V "x") (V "xs"), Cons (V "y") (V "ys")]
, [V "g", W, W]
]
zipWith_test'' = tester
[ [V "f", Cons (V "x") (V "xs"), Cons (V "y") (V "ys")]
, [V "g", Nil, Nil]
]
uncovered_test = tester
[ [Cons (V "x") $ Cons (V "y") $ Cons (V "z") (V "v")] ]
view_test = tester
[ [Vi "f" (Cons (V "y") (V "s"))] ]
view_test' = tester
[ [Vi "f" (Cons (Vi "g" $ Ju (V "y")) (V "s"))]
, [Vi "h" T]
]
view_test'' = tester
[ [V "x", [ViewPat (ViewApp (Var "f") (Var "x")) (T `mappend` V "q")] `mappend` V "z"] ] -- TODO: prevent V "q" expansion
guard_test = tester
[ [V "x" `mappend` Vi "graterThan5" T]
, [V "x"]
]
|