on fa526e4 help sign in
Idris-dev/src/Core/CaseTree.hs
486 lines 19 kB history raw
1{-# LANGUAGE PatternGuards, DeriveFunctor, TypeSynonymInstances #-}
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 (ProjCase n' as) = termsize n as
68 termsize n (STerm t) = termsize n t
69 termsize n _ = 1
71instance TermSize CaseAlt where
72 termsize n (ConCase _ _ _ s) = termsize n s
73 termsize n (ConstCase _ s) = termsize n s
74 termsize n (DefaultCase s) = termsize n s
76-- simple terms can be inlined trivially - good for primitives in particular
77-- To avoid duplicating work, don't inline something which uses one
78-- of its arguments in more than one place
80small :: Name -> [Name] -> SC -> Bool
81small n args t = let as = findAllUsedArgs t args in
82 length as == length (nub as) &&
83 termsize n t < 10
85namesUsed :: SC -> [Name]
86namesUsed sc = nub $ nu' [] sc where
87 nu' ps (Case n alts) = nub (concatMap (nua ps) alts) \\ [n]
88 nu' ps (ProjCase t alts) = nub $ (nut ps t ++
89 (concatMap (nua ps) alts))
90 nu' ps (STerm t) = nub $ nut ps t
91 nu' ps _ = []
93 nua ps (ConCase n i args sc) = nub (nu' (ps ++ args) sc) \\ args
94 nua ps (ConstCase _ sc) = nu' ps sc
95 nua ps (DefaultCase sc) = nu' ps sc
97 nut ps (P _ n _) | n `elem` ps = []
98 | otherwise = [n]
99 nut ps (App f a) = nut ps f ++ nut ps a
100 nut ps (Proj t _) = nut ps t
101 nut ps (Bind n (Let t v) sc) = nut ps v ++ nut (n:ps) sc
102 nut ps (Bind n b sc) = nut (n:ps) sc
103 nut ps _ = []
105-- Return all called functions, and which arguments are used in each argument position
106-- for the call, in order to help reduce compilation time, and trace all unused
107-- arguments
109findCalls :: SC -> [Name] -> [(Name, [[Name]])]
110findCalls sc topargs = nub $ nu' topargs sc where
111 nu' ps (Case n alts) = nub (concatMap (nua (n : ps)) alts)
112 nu' ps (ProjCase t alts) = nub (nut ps t ++ concatMap (nua ps) alts)
113 nu' ps (STerm t) = nub $ nut ps t
114 nu' ps _ = []
116 nua ps (ConCase n i args sc) = nub (nu' (ps ++ args) sc)
117 nua ps (ConstCase _ sc) = nu' ps sc
118 nua ps (DefaultCase sc) = nu' ps sc
120 nut ps (P Ref n _) | n `elem` ps = []
121 | otherwise = [(n, [])] -- tmp
122 nut ps fn@(App f a)
123 | (P Ref n _, args) <- unApply fn
124 = if n `elem` ps then nut ps f ++ nut ps a
125 else [(n, map argNames args)] ++ concatMap (nut ps) args
126 | otherwise = nut ps f ++ nut ps a
127 nut ps (Bind n (Let t v) sc) = nut ps v ++ nut (n:ps) sc
128 nut ps (Proj t _) = nut ps t
129 nut ps (Bind n b sc) = nut (n:ps) sc
130 nut ps _ = []
132 argNames tm = let ns = directUse tm in
133 filter (\x -> x `elem` ns) topargs
135-- Find names which are used directly (i.e. not in a function call) in a term
137directUse :: Eq n => TT n -> [n]
138directUse (P _ n _) = [n]
139directUse (Bind n (Let t v) sc) = nub $ directUse v ++ (directUse sc \\ [n])
140 ++ directUse t
141directUse (Bind n b sc) = nub $ directUse (binderTy b) ++ (directUse sc \\ [n])
142directUse fn@(App f a)
143 | (P Ref n _, args) <- unApply fn = [] -- need to know what n does with them
144 | otherwise = nub $ directUse f ++ directUse a
145directUse (Proj x i) = nub $ directUse x
146directUse _ = []
148-- Find all directly used arguments (i.e. used but not in function calls)
150findUsedArgs :: SC -> [Name] -> [Name]
151findUsedArgs sc topargs = nub (findAllUsedArgs sc topargs)
153findAllUsedArgs sc topargs = filter (\x -> x `elem` topargs) (nu' sc) where
154 nu' (Case n alts) = n : concatMap nua alts
155 nu' (ProjCase t alts) = directUse t ++ concatMap nua alts
156 nu' (STerm t) = directUse t
157 nu' _ = []
159 nua (ConCase n i args sc) = nu' sc
160 nua (ConstCase _ sc) = nu' sc
161 nua (DefaultCase sc) = nu' sc
163data Phase = CompileTime | RunTime
164 deriving (Show, Eq)
166-- Generate a simple case tree
167-- Work Right to Left
169simpleCase :: Bool -> Bool -> Phase -> FC -> [([Name], Term, Term)] ->
170 TC CaseDef
171simpleCase tc cover phase fc cs
172 = sc' tc cover phase fc (filter (\(_, _, r) ->
173 case r of
174 Impossible -> False
175 _ -> True) cs)
176 where
177 sc' tc cover phase fc []
178 = return $ CaseDef [] (UnmatchedCase "No pattern clauses") []
179 sc' tc cover phase fc cs
180 = let proj = phase == RunTime
181 pats = map (\ (avs, l, r) ->
182 (avs, toPats tc l, (l, r))) cs
183 chkPats = mapM chkAccessible pats in
184 case chkPats of
185 OK pats ->
186 let numargs = length (fst (head pats))
187 ns = take numargs args
188 (ns', ps') = order ns pats
189 (tree, st) = runState
190 (match ns' ps' (defaultCase cover)) ([], numargs)
191 t = CaseDef ns (prune proj (depatt ns' tree)) (fst st) in
192 if proj then return (stripLambdas t) else return t
193 Error err -> Error (At fc err)
194 where args = map (\i -> MN i "e") [0..]
195 defaultCase True = STerm Erased
196 defaultCase False = UnmatchedCase "Error"
198 chkAccessible (avs, l, c)
199 | phase == RunTime = return (l, c)
200 | otherwise = do mapM_ (acc l) avs
201 return (l, c)
203 acc [] n = Error (Inaccessible n)
204 acc (PV x : xs) n | x == n = OK ()
205 acc (PCon _ _ ps : xs) n = acc (ps ++ xs) n
206 acc (_ : xs) n = acc xs n
208data Pat = PCon Name Int [Pat]
209 | PConst Const
210 | PV Name
211 | PAny
212 deriving Show
214-- If there are repeated variables, take the *last* one (could be name shadowing
215-- in a where clause, so take the most recent).
217toPats :: Bool -> Term -> [Pat]
218toPats tc f = reverse (toPat tc (getArgs f)) where
219 getArgs (App f a) = a : getArgs f
220 getArgs _ = []
222toPat :: Bool -> [Term] -> [Pat]
223toPat tc tms = evalState (mapM (\x -> toPat' x []) tms) []
224 where
225 toPat' (P (DCon t a) n _) args = do args' <- mapM (\x -> toPat' x []) args
226 return $ PCon n t args'
227 -- Typecase
228 toPat' (P (TCon t a) n _) args | tc
229 = do args' <- mapM (\x -> toPat' x []) args
230 return $ PCon n t args'
231 toPat' (Constant (AType (ATInt ITNative))) []
232 | tc = return $ PCon (UN "Int") 1 []
233 toPat' (Constant (AType ATFloat)) [] | tc = return $ PCon (UN "Float") 2 []
234 toPat' (Constant (AType (ATInt ITChar))) [] | tc = return $ PCon (UN "Char") 3 []
235 toPat' (Constant StrType) [] | tc = return $ PCon (UN "String") 4 []
236 toPat' (Constant PtrType) [] | tc = return $ PCon (UN "Ptr") 5 []
237 toPat' (Constant (AType (ATInt ITBig))) []
238 | tc = return $ PCon (UN "Integer") 6 []
239 toPat' (Constant (AType (ATInt (ITFixed n)))) []
240 | tc = return $ PCon (UN (fixedN n)) (7 + fromEnum n) [] -- 7-10 inclusive
241 toPat' (P Bound n _) [] = do ns <- get
242 if n `elem` ns
243 then return PAny
244 else do put (n : ns)
245 return (PV n)
246 toPat' (App f a) args = toPat' f (a : args)
247 toPat' (Constant x) [] = return $ PConst x
248 toPat' _ _ = return PAny
250 fixedN IT8 = "Bits8"
251 fixedN IT16 = "Bits16"
252 fixedN IT32 = "Bits32"
253 fixedN IT64 = "Bits64"
256data Partition = Cons [Clause]
257 | Vars [Clause]
258 deriving Show
260isVarPat (PV _ : ps , _) = True
261isVarPat (PAny : ps , _) = True
262isVarPat _ = False
264isConPat (PCon _ _ _ : ps, _) = True
265isConPat (PConst _ : ps, _) = True
266isConPat _ = False
268partition :: [Clause] -> [Partition]
269partition [] = []
270partition ms@(m : _)
271 | isVarPat m = let (vars, rest) = span isVarPat ms in
272 Vars vars : partition rest
273 | isConPat m = let (cons, rest) = span isConPat ms in
274 Cons cons : partition rest
275partition xs = error $ "Partition " ++ show xs
277-- reorder the patterns so that the one with most distinct names
278-- comes next. Take rightmost first, otherwise (i.e. pick value rather
279-- than dependency)
281order :: [Name] -> [Clause] -> ([Name], [Clause])
282order [] cs = ([], cs)
283order ns [] = (ns, [])
284order ns cs = let patnames = transpose (map (zip ns) (map fst cs))
285 pats' = transpose (sortBy moreDistinct (reverse patnames)) in
286 (getNOrder pats', zipWith rebuild pats' cs)
287 where
288 getNOrder [] = error $ "Failed order on " ++ show (ns, cs)
289 getNOrder (c : _) = map fst c
291 rebuild patnames clause = (map snd patnames, snd clause)
293 moreDistinct xs ys = compare (numNames [] (map snd ys))
294 (numNames [] (map snd xs))
296 numNames xs (PCon n _ _ : ps)
297 | not (Left n `elem` xs) = numNames (Left n : xs) ps
298 numNames xs (PConst c : ps)
299 | not (Right c `elem` xs) = numNames (Right c : xs) ps
300 numNames xs (_ : ps) = numNames xs ps
301 numNames xs [] = length xs
303match :: [Name] -> [Clause] -> SC -- error case
304 -> State CS SC
305match [] (([], ret) : xs) err
306 = do (ts, v) <- get
307 put (ts ++ (map (fst.snd) xs), v)
308 case snd ret of
309 Impossible -> return ImpossibleCase
310 tm -> return $ STerm tm -- run out of arguments
311match vs cs err = do let ps = partition cs
312 mixture vs ps err
314mixture :: [Name] -> [Partition] -> SC -> State CS SC
315mixture vs [] err = return err
316mixture vs (Cons ms : ps) err = do fallthrough <- mixture vs ps err
317 conRule vs ms fallthrough
318mixture vs (Vars ms : ps) err = do fallthrough <- mixture vs ps err
319 varRule vs ms fallthrough
321data ConType = CName Name Int -- named constructor
322 | CConst Const -- constant, not implemented yet
324data Group = ConGroup ConType -- Constructor
325 [([Pat], Clause)] -- arguments and rest of alternative
327conRule :: [Name] -> [Clause] -> SC -> State CS SC
328conRule (v:vs) cs err = do groups <- groupCons cs
329 caseGroups (v:vs) groups err
331caseGroups :: [Name] -> [Group] -> SC -> State CS SC
332caseGroups (v:vs) gs err = do g <- altGroups gs
333 return $ Case v (sort g)
334 where
335 altGroups [] = return [DefaultCase err]
336 altGroups (ConGroup (CName n i) args : cs)
337 = do g <- altGroup n i args
338 rest <- altGroups cs
339 return (g : rest)
340 altGroups (ConGroup (CConst c) args : cs)
341 = do g <- altConstGroup c args
342 rest <- altGroups cs
343 return (g : rest)
345 altGroup n i gs = do (newArgs, nextCs) <- argsToAlt gs
346 matchCs <- match (newArgs ++ vs) nextCs err
347 return $ ConCase n i newArgs matchCs
348 altConstGroup n gs = do (_, nextCs) <- argsToAlt gs
349 matchCs <- match vs nextCs err
350 return $ ConstCase n matchCs
352argsToAlt :: [([Pat], Clause)] -> State CS ([Name], [Clause])
353argsToAlt [] = return ([], [])
354argsToAlt rs@((r, m) : rest)
355 = do newArgs <- getNewVars r
356 return (newArgs, addRs rs)
357 where
358 getNewVars [] = return []
359 getNewVars ((PV n) : ns) = do v <- getVar "e"
360 nsv <- getNewVars ns
361 return (v : nsv)
362 getNewVars (PAny : ns) = do v <- getVar "i"
363 nsv <- getNewVars ns
364 return (v : nsv)
365 getNewVars (_ : ns) = do v <- getVar "e"
366 nsv <- getNewVars ns
367 return (v : nsv)
368 addRs [] = []
369 addRs ((r, (ps, res)) : rs) = ((r++ps, res) : addRs rs)
371 uniq i (UN n) = MN i n
372 uniq i n = n
374getVar :: String -> State CS Name
375getVar b = do (t, v) <- get; put (t, v+1); return (MN v b)
377groupCons :: [Clause] -> State CS [Group]
378groupCons cs = gc [] cs
379 where
380 gc acc [] = return acc
381 gc acc ((p : ps, res) : cs) =
382 do acc' <- addGroup p ps res acc
383 gc acc' cs
384 addGroup p ps res acc = case p of
385 PCon con i args -> return $ addg con i args (ps, res) acc
386 PConst cval -> return $ addConG cval (ps, res) acc
387 pat -> fail $ show pat ++ " is not a constructor or constant (can't happen)"
389 addg con i conargs res [] = [ConGroup (CName con i) [(conargs, res)]]
390 addg con i conargs res (g@(ConGroup (CName n j) cs):gs)
391 | i == j = ConGroup (CName n i) (cs ++ [(conargs, res)]) : gs
392 | otherwise = g : addg con i conargs res gs
394 addConG con res [] = [ConGroup (CConst con) [([], res)]]
395 addConG con res (g@(ConGroup (CConst n) cs) : gs)
396 | con == n = ConGroup (CConst n) (cs ++ [([], res)]) : gs
397 | otherwise = g : addConG con res gs
399varRule :: [Name] -> [Clause] -> SC -> State CS SC
400varRule (v : vs) alts err =
401 do let alts' = map (repVar v) alts
402 match vs alts' err
403 where
404 repVar v (PV p : ps , (lhs, res))
405 = (ps, (lhs, subst p (P Bound v Erased) res))
406 repVar v (PAny : ps , res) = (ps, res)
408-- fix: case e of S k -> f (S k) ==> case e of S k -> f e
410depatt :: [Name] -> SC -> SC
411depatt ns tm = dp [] tm
412 where
413 dp ms (STerm tm) = STerm (applyMaps ms tm)
414 dp ms (Case x alts) = Case x (map (dpa ms x) alts)
415 dp ms sc = sc
417 dpa ms x (ConCase n i args sc)
418 = ConCase n i args (dp ((x, (n, args)) : ms) sc)
419 dpa ms x (ConstCase c sc) = ConstCase c (dp ms sc)
420 dpa ms x (DefaultCase sc) = DefaultCase (dp ms sc)
422 applyMaps ms f@(App _ _)
423 | (P nt cn pty, args) <- unApply f
424 = let args' = map (applyMaps ms) args in
425 applyMap ms nt cn pty args'
426 where
427 applyMap [] nt cn pty args' = mkApp (P nt cn pty) args'
428 applyMap ((x, (n, args)) : ms) nt cn pty args'
429 | and ((length args == length args') :
430 (n == cn) : zipWith same args args') = P Ref x Erased
431 | otherwise = applyMap ms nt cn pty args'
432 same n (P _ n' _) = n == n'
433 same _ _ = False
435 applyMaps ms (App f a) = App (applyMaps ms f) (applyMaps ms a)
436 applyMaps ms t = t
438prune :: Bool -- ^ Convert single branches to projections (only useful at runtime)
439 -> SC -> SC
440prune proj (Case n alts)
441 = let alts' = filter notErased (map pruneAlt alts) in
442 case alts' of
443 [] -> ImpossibleCase
444 as@[ConCase cn i args sc] -> if proj then mkProj n 0 args sc
445 else Case n as
446 as -> Case n as
447 where pruneAlt (ConCase cn i ns sc) = ConCase cn i ns (prune proj sc)
448 pruneAlt (ConstCase c sc) = ConstCase c (prune proj sc)
449 pruneAlt (DefaultCase sc) = DefaultCase (prune proj sc)
451 notErased (DefaultCase (STerm Erased)) = False
452 notErased (DefaultCase ImpossibleCase) = False
453 notErased _ = True
455 mkProj n i [] sc = sc
456 mkProj n i (x : xs) sc = mkProj n (i + 1) xs (projRep x n i sc)
458 projRep :: Name -> Name -> Int -> SC -> SC
459 projRep arg n i (Case x alts)
460 | x == arg = ProjCase (Proj (P Bound n Erased) i)
461 (map (projRepAlt arg n i) alts)
462 | otherwise = Case x (map (projRepAlt arg n i) alts)
463 projRep arg n i (ProjCase t alts)
464 = ProjCase (projRepTm arg n i t) (map (projRepAlt arg n i) alts)
465 projRep arg n i (STerm t) = STerm (projRepTm arg n i t)
466 projRep arg n i c = c -- unmatched
468 projRepAlt arg n i (ConCase cn t args rhs)
469 = ConCase cn t args (projRep arg n i rhs)
470 projRepAlt arg n i (ConstCase t rhs)
471 = ConstCase t (projRep arg n i rhs)
472 projRepAlt arg n i (DefaultCase rhs)
473 = DefaultCase (projRep arg n i rhs)
475 projRepTm arg n i t = subst arg (Proj (P Bound n Erased) i) t
477prune _ t = t
479stripLambdas :: CaseDef -> CaseDef
480stripLambdas (CaseDef ns (STerm (Bind x (Lam _) sc)) tm)
481 = stripLambdas (CaseDef (ns ++ [x]) (STerm (instantiate (P Bound x Erased) sc)) tm)
482stripLambdas x = x