on 64fc043 help sign in
Idris-dev/src/Core/CaseTree.hs
433 lines 16 kB history raw
1{-# LANGUAGE PatternGuards, DeriveFunctor #-}
3module Core.CaseTree(CaseDef(..), SC, SC'(..), CaseAlt, CaseAlt'(..),
4 Phase(..), CaseTree,
5 simpleCase, small, namesUsed, findCalls, findUsedArgs) where
7import Core.TT
9import Control.Monad.State
10import Data.Maybe
11import Data.List hiding (partition)
12import Debug.Trace
14data CaseDef = CaseDef [Name] SC [Term]
15 deriving Show
17data SC' t = Case Name [CaseAlt' t] -- invariant: lowest tags first
18 | ProjCase t [CaseAlt' t] -- special case for projections
19 | STerm t
20 | UnmatchedCase String -- error message
21 | ImpossibleCase -- already checked to be impossible
22 deriving (Eq, Ord, Functor)
23{-!
24deriving instance Binary SC
25!-}
27type SC = SC' Term
29data CaseAlt' t = ConCase Name Int [Name] (SC' t)
30 | ConstCase Const (SC' t)
31 | DefaultCase (SC' t)
32 deriving (Show, Eq, Ord, Functor)
33{-!
34deriving instance Binary CaseAlt
35!-}
37type CaseAlt = CaseAlt' Term
39instance Show t => Show (SC' t) where
40 show sc = show' 1 sc
41 where
42 show' i (Case n alts) = "case " ++ show n ++ " of\n" ++ indent i ++
43 showSep ("\n" ++ indent i) (map (showA i) alts)
44 show' i (ProjCase tm alts) = "case " ++ show tm ++ " of " ++
45 showSep ("\n" ++ indent i) (map (showA i) alts)
46 show' i (STerm tm) = show tm
47 show' i (UnmatchedCase str) = "error " ++ show str
48 show' i ImpossibleCase = "impossible"
50 indent i = concat $ take i (repeat " ")
52 showA i (ConCase n t args sc)
53 = show n ++ "(" ++ showSep (", ") (map show args) ++ ") => "
54 ++ show' (i+1) sc
55 showA i (ConstCase t sc)
56 = show t ++ " => " ++ show' (i+1) sc
57 showA i (DefaultCase sc)
58 = "_ => " ++ show' (i+1) sc
61type CaseTree = SC
62type Clause = ([Pat], (Term, Term))
63type CS = ([Term], Int)
65instance TermSize SC where
66 termsize n (Case n' as) = termsize n as
67 termsize n (STerm t) = termsize n t
68 termsize n _ = 1
70instance TermSize CaseAlt where
71 termsize n (ConCase _ _ _ s) = termsize n s
72 termsize n (ConstCase _ s) = termsize n s
73 termsize n (DefaultCase s) = termsize n s
75-- simple terms can be inlined trivially - good for primitives in particular
76small :: Name -> SC -> Bool
77small n t = termsize n t < 50
79namesUsed :: SC -> [Name]
80namesUsed sc = nub $ nu' [] sc where
81 nu' ps (Case n alts) = nub (concatMap (nua ps) alts) \\ [n]
82 nu' ps (ProjCase t alts) = nub $ (nut ps t ++
83 (concatMap (nua ps) alts))
84 nu' ps (STerm t) = nub $ nut ps t
85 nu' ps _ = []
87 nua ps (ConCase n i args sc) = nub (nu' (ps ++ args) sc) \\ args
88 nua ps (ConstCase _ sc) = nu' ps sc
89 nua ps (DefaultCase sc) = nu' ps sc
91 nut ps (P _ n _) | n `elem` ps = []
92 | otherwise = [n]
93 nut ps (App f a) = nut ps f ++ nut ps a
94 nut ps (Proj t _) = nut ps t
95 nut ps (Bind n (Let t v) sc) = nut ps v ++ nut (n:ps) sc
96 nut ps (Bind n b sc) = nut (n:ps) sc
97 nut ps _ = []
99-- Return all called functions, and which arguments are used in each argument position
100-- for the call, in order to help reduce compilation time, and trace all unused
101-- arguments
103findCalls :: SC -> [Name] -> [(Name, [[Name]])]
104findCalls sc topargs = nub $ nu' topargs sc where
105 nu' ps (Case n alts) = nub (concatMap (nua (n : ps)) alts)
106 nu' ps (ProjCase t alts) = nub (nut ps t ++ concatMap (nua ps) alts)
107 nu' ps (STerm t) = nub $ nut ps t
108 nu' ps _ = []
110 nua ps (ConCase n i args sc) = nub (nu' (ps ++ args) sc)
111 nua ps (ConstCase _ sc) = nu' ps sc
112 nua ps (DefaultCase sc) = nu' ps sc
114 nut ps (P Ref n _) | n `elem` ps = []
115 | otherwise = [(n, [])] -- tmp
116 nut ps fn@(App f a)
117 | (P Ref n _, args) <- unApply fn
118 = if n `elem` ps then nut ps f ++ nut ps a
119 else [(n, map argNames args)] ++ concatMap (nut ps) args
120 | otherwise = nut ps f ++ nut ps a
121 nut ps (Bind n (Let t v) sc) = nut ps v ++ nut (n:ps) sc
122 nut ps (Proj t _) = nut ps t
123 nut ps (Bind n b sc) = nut (n:ps) sc
124 nut ps _ = []
126 argNames tm = let ns = directUse tm in
127 filter (\x -> x `elem` ns) topargs
129-- Find names which are used directly (i.e. not in a function call) in a term
131directUse :: Eq n => TT n -> [n]
132directUse (P _ n _) = [n]
133directUse (Bind n (Let t v) sc) = nub $ directUse v ++ (directUse sc \\ [n])
134 ++ directUse t
135directUse (Bind n b sc) = nub $ directUse (binderTy b) ++ (directUse sc \\ [n])
136directUse fn@(App f a)
137 | (P Ref n _, args) <- unApply fn = [] -- need to know what n does with them
138 | otherwise = nub $ directUse f ++ directUse a
139directUse (Proj x i) = nub $ directUse x
140directUse _ = []
142-- Find all directly used arguments (i.e. used but not in function calls)
144findUsedArgs :: SC -> [Name] -> [Name]
145findUsedArgs sc topargs = filter (\x -> x `elem` topargs) (nub $ nu' sc) where
146 nu' (Case n alts) = n : concatMap nua alts
147 nu' (ProjCase t alts) = directUse t ++ concatMap nua alts
148 nu' (STerm t) = directUse t
149 nu' _ = []
151 nua (ConCase n i args sc) = nu' sc
152 nua (ConstCase _ sc) = nu' sc
153 nua (DefaultCase sc) = nu' sc
155data Phase = CompileTime | RunTime
156 deriving (Show, Eq)
158-- Generate a simple case tree
159-- Work Left to Right at Compile Time
161simpleCase :: Bool -> Bool -> Phase -> FC -> [([Name], Term, Term)] -> TC CaseDef
162simpleCase tc cover phase fc []
163 = return $ CaseDef [] (UnmatchedCase "No pattern clauses") []
164simpleCase tc cover phase fc cs
165 = let proj = phase == RunTime
166 pats = map (\ (avs, l, r) ->
167 (avs, rev phase (toPats tc l), (l, r))) cs
168 chkPats = mapM chkAccessible pats in
169 case chkPats of
170 OK pats ->
171 let numargs = length (fst (head pats))
172 ns = take numargs args
173 (tree, st) = runState
174 (match (rev phase ns) pats (defaultCase cover)) ([], numargs)
175 t = CaseDef ns (prune proj (depatt ns tree)) (fst st) in
176 if proj then return (stripLambdas t) else return t
177 Error err -> Error (At fc err)
178 where args = map (\i -> MN i "e") [0..]
179 defaultCase True = STerm Erased
180 defaultCase False = UnmatchedCase "Error"
182 chkAccessible (avs, l, c)
183 | phase == RunTime = return (l, c)
184 | otherwise = do mapM_ (acc l) avs
185 return (l, c)
187 acc [] n = Error (Inaccessible n)
188 acc (PV x : xs) n | x == n = OK ()
189 acc (PCon _ _ ps : xs) n = acc (ps ++ xs) n
190 acc (_ : xs) n = acc xs n
192rev CompileTime = id
193rev _ = reverse
195data Pat = PCon Name Int [Pat]
196 | PConst Const
197 | PV Name
198 | PAny
199 deriving Show
201-- If there are repeated variables, take the *last* one (could be name shadowing
202-- in a where clause, so take the most recent).
204toPats :: Bool -> Term -> [Pat]
205toPats tc f = reverse (toPat tc (getArgs f)) where
206 getArgs (App f a) = a : getArgs f
207 getArgs _ = []
209toPat :: Bool -> [Term] -> [Pat]
210toPat tc tms = evalState (mapM (\x -> toPat' x []) tms) []
211 where
212 toPat' (P (DCon t a) n _) args = do args' <- mapM (\x -> toPat' x []) args
213 return $ PCon n t args'
214 -- Typecase
215 toPat' (P (TCon t a) n _) args | tc
216 = do args' <- mapM (\x -> toPat' x []) args
217 return $ PCon n t args'
218 toPat' (Constant IType) [] | tc = return $ PCon (UN "Int") 1 []
219 toPat' (Constant FlType) [] | tc = return $ PCon (UN "Float") 2 []
220 toPat' (Constant ChType) [] | tc = return $ PCon (UN "Char") 3 []
221 toPat' (Constant StrType) [] | tc = return $ PCon (UN "String") 4 []
222 toPat' (Constant PtrType) [] | tc = return $ PCon (UN "Ptr") 5 []
223 toPat' (Constant BIType) [] | tc = return $ PCon (UN "Integer") 6 []
225 toPat' (P Bound n _) [] = do ns <- get
226 if n `elem` ns
227 then return PAny
228 else do put (n : ns)
229 return (PV n)
230 toPat' (App f a) args = toPat' f (a : args)
231 toPat' (Constant x) [] = return $ PConst x
232 toPat' _ _ = return PAny
235data Partition = Cons [Clause]
236 | Vars [Clause]
237 deriving Show
239isVarPat (PV _ : ps , _) = True
240isVarPat (PAny : ps , _) = True
241isVarPat _ = False
243isConPat (PCon _ _ _ : ps, _) = True
244isConPat (PConst _ : ps, _) = True
245isConPat _ = False
247partition :: [Clause] -> [Partition]
248partition [] = []
249partition ms@(m : _)
250 | isVarPat m = let (vars, rest) = span isVarPat ms in
251 Vars vars : partition rest
252 | isConPat m = let (cons, rest) = span isConPat ms in
253 Cons cons : partition rest
254partition xs = error $ "Partition " ++ show xs
256match :: [Name] -> [Clause] -> SC -- error case
257 -> State CS SC
258match [] (([], ret) : xs) err
259 = do (ts, v) <- get
260 put (ts ++ (map (fst.snd) xs), v)
261 case snd ret of
262 Impossible -> return ImpossibleCase
263 tm -> return $ STerm tm -- run out of arguments
264match vs cs err = do let ps = partition cs
265 cs <- mixture vs ps err
266 return cs
268mixture :: [Name] -> [Partition] -> SC -> State CS SC
269mixture vs [] err = return err
270mixture vs (Cons ms : ps) err = do fallthrough <- mixture vs ps err
271 conRule vs ms fallthrough
272mixture vs (Vars ms : ps) err = do fallthrough <- mixture vs ps err
273 varRule vs ms fallthrough
275data ConType = CName Name Int -- named constructor
276 | CConst Const -- constant, not implemented yet
278data Group = ConGroup ConType -- Constructor
279 [([Pat], Clause)] -- arguments and rest of alternative
281conRule :: [Name] -> [Clause] -> SC -> State CS SC
282conRule (v:vs) cs err = do groups <- groupCons cs
283 caseGroups (v:vs) groups err
285caseGroups :: [Name] -> [Group] -> SC -> State CS SC
286caseGroups (v:vs) gs err = do g <- altGroups gs
287 return $ Case v (sort g)
288 where
289 altGroups [] = return [DefaultCase err]
290 altGroups (ConGroup (CName n i) args : cs)
291 = do g <- altGroup n i args
292 rest <- altGroups cs
293 return (g : rest)
294 altGroups (ConGroup (CConst c) args : cs)
295 = do g <- altConstGroup c args
296 rest <- altGroups cs
297 return (g : rest)
299 altGroup n i gs = do (newArgs, nextCs) <- argsToAlt gs
300 matchCs <- match (newArgs ++ vs) nextCs err
301 return $ ConCase n i newArgs matchCs
302 altConstGroup n gs = do (_, nextCs) <- argsToAlt gs
303 matchCs <- match vs nextCs err
304 return $ ConstCase n matchCs
306argsToAlt :: [([Pat], Clause)] -> State CS ([Name], [Clause])
307argsToAlt [] = return ([], [])
308argsToAlt rs@((r, m) : rest)
309 = do newArgs <- getNewVars r
310 return (newArgs, addRs rs)
311 where
312 getNewVars [] = return []
313 getNewVars ((PV n) : ns) = do v <- getVar
314 nsv <- getNewVars ns
315 return (v : nsv)
316 getNewVars (_ : ns) = do v <- getVar
317 nsv <- getNewVars ns
318 return (v : nsv)
319 addRs [] = []
320 addRs ((r, (ps, res)) : rs) = ((r++ps, res) : addRs rs)
322 uniq i (UN n) = MN i n
323 uniq i n = n
325getVar :: State CS Name
326getVar = do (t, v) <- get; put (t, v+1); return (MN v "e")
328groupCons :: [Clause] -> State CS [Group]
329groupCons cs = gc [] cs
330 where
331 gc acc [] = return acc
332 gc acc ((p : ps, res) : cs) =
333 do acc' <- addGroup p ps res acc
334 gc acc' cs
335 addGroup p ps res acc = case p of
336 PCon con i args -> return $ addg con i args (ps, res) acc
337 PConst cval -> return $ addConG cval (ps, res) acc
338 pat -> fail $ show pat ++ " is not a constructor or constant (can't happen)"
340 addg con i conargs res [] = [ConGroup (CName con i) [(conargs, res)]]
341 addg con i conargs res (g@(ConGroup (CName n j) cs):gs)
342 | i == j = ConGroup (CName n i) (cs ++ [(conargs, res)]) : gs
343 | otherwise = g : addg con i conargs res gs
345 addConG con res [] = [ConGroup (CConst con) [([], res)]]
346 addConG con res (g@(ConGroup (CConst n) cs) : gs)
347 | con == n = ConGroup (CConst n) (cs ++ [([], res)]) : gs
348 | otherwise = g : addConG con res gs
350varRule :: [Name] -> [Clause] -> SC -> State CS SC
351varRule (v : vs) alts err =
352 do let alts' = map (repVar v) alts
353 match vs alts' err
354 where
355 repVar v (PV p : ps , (lhs, res)) = (ps, (lhs, subst p (P Bound v Erased) res))
356 repVar v (PAny : ps , res) = (ps, res)
358-- fix: case e of S k -> f (S k) ==> case e of S k -. f e
359depatt :: [Name] -> SC -> SC
360depatt ns tm = dp [] tm
361 where
362 dp ms (STerm tm) = STerm (applyMaps ms tm)
363 dp ms (Case x alts) = Case x (map (dpa ms x) alts)
364 dp ms sc = sc
366 dpa ms x (ConCase n i args sc)
367 = ConCase n i args (dp ((x, (n, args)) : ms) sc)
368 dpa ms x (ConstCase c sc) = ConstCase c (dp ms sc)
369 dpa ms x (DefaultCase sc) = DefaultCase (dp ms sc)
371 applyMaps ms f@(App _ _)
372 | (P nt cn pty, args) <- unApply f
373 = let args' = map (applyMaps ms) args in
374 applyMap ms nt cn pty args'
375 where
376 applyMap [] nt cn pty args' = mkApp (P nt cn pty) args'
377 applyMap ((x, (n, args)) : ms) nt cn pty args'
378 | and ((n == cn) : zipWith same args args') = P Ref x Erased
379 | otherwise = applyMap ms nt cn pty args'
380 same n (P _ n' _) = n == n'
381 same _ _ = False
382 applyMaps ms (App f a) = App (applyMaps ms f) (applyMaps ms a)
383 applyMaps ms t = t
385prune :: Bool -> -- ^ Convert single branches to projections (only useful at runtime)
386 SC -> SC
387prune proj (Case n alts)
388 = let alts' = filter notErased (map pruneAlt alts) in
389 case alts' of
390 [] -> ImpossibleCase
391 as@[ConCase cn i args sc] -> if proj then mkProj n 0 args sc
392 else Case n as
393 as -> Case n as
394 where pruneAlt (ConCase cn i ns sc) = ConCase cn i ns (prune proj sc)
395 pruneAlt (ConstCase c sc) = ConstCase c (prune proj sc)
396 pruneAlt (DefaultCase sc) = DefaultCase (prune proj sc)
398 notErased (DefaultCase (STerm Erased)) = False
399 notErased (DefaultCase ImpossibleCase) = False
400 notErased _ = True
402 mkProj n i [] sc = sc
403 mkProj n i (x : xs) sc = mkProj n (i + 1) xs (projRep x n i sc)
405 projRep :: Name -> Name -> Int -> SC -> SC
406 projRep arg n i (Case x alts)
407 | x == arg = ProjCase (Proj (P Bound n Erased) i)
408 (map (projRepAlt arg n i) alts)
409 | otherwise = Case x (map (projRepAlt arg n i) alts)
410 projRep arg n i (ProjCase t alts)
411 = ProjCase (projRepTm arg n i t) (map (projRepAlt arg n i) alts)
412 projRep arg n i (STerm t) = STerm (projRepTm arg n i t)
413 projRep arg n i c = c -- unmatched
415 projRepAlt arg n i (ConCase cn t args rhs)
416 = ConCase cn t args (projRep arg n i rhs)
417 projRepAlt arg n i (ConstCase t rhs)
418 = ConstCase t (projRep arg n i rhs)
419 projRepAlt arg n i (DefaultCase rhs)
420 = DefaultCase (projRep arg n i rhs)
422 projRepTm arg n i t = subst arg (Proj (P Bound n Erased) i) t
424prune _ t = t
426stripLambdas :: CaseDef -> CaseDef
427stripLambdas (CaseDef ns (STerm (Bind x (Lam _) sc)) tm)
428 = stripLambdas (CaseDef (ns ++ [x]) (STerm (instantiate (P Bound x Erased) sc)) tm)
429stripLambdas x = x