on d2cec77 help sign in
Idris-dev/src/Core/CaseTree.hs
475 lines 18 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 (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
76-- To avoid duplicating work, don't inline something which uses one
77-- of its arguments in more than one place
79small :: Name -> [Name] -> SC -> Bool
80small n args t = let as = findAllUsedArgs t args in
81 length as == length (nub as) &&
82 termsize n t < 5
84namesUsed :: SC -> [Name]
85namesUsed sc = nub $ nu' [] sc where
86 nu' ps (Case n alts) = nub (concatMap (nua ps) alts) \\ [n]
87 nu' ps (ProjCase t alts) = nub $ (nut ps t ++
88 (concatMap (nua ps) alts))
89 nu' ps (STerm t) = nub $ nut ps t
90 nu' ps _ = []
92 nua ps (ConCase n i args sc) = nub (nu' (ps ++ args) sc) \\ args
93 nua ps (ConstCase _ sc) = nu' ps sc
94 nua ps (DefaultCase sc) = nu' ps sc
96 nut ps (P _ n _) | n `elem` ps = []
97 | otherwise = [n]
98 nut ps (App f a) = nut ps f ++ nut ps a
99 nut ps (Proj t _) = nut ps t
100 nut ps (Bind n (Let t v) sc) = nut ps v ++ nut (n:ps) sc
101 nut ps (Bind n b sc) = nut (n:ps) sc
102 nut ps _ = []
104-- Return all called functions, and which arguments are used in each argument position
105-- for the call, in order to help reduce compilation time, and trace all unused
106-- arguments
108findCalls :: SC -> [Name] -> [(Name, [[Name]])]
109findCalls sc topargs = nub $ nu' topargs sc where
110 nu' ps (Case n alts) = nub (concatMap (nua (n : ps)) alts)
111 nu' ps (ProjCase t alts) = nub (nut ps t ++ concatMap (nua ps) alts)
112 nu' ps (STerm t) = nub $ nut ps t
113 nu' ps _ = []
115 nua ps (ConCase n i args sc) = nub (nu' (ps ++ args) sc)
116 nua ps (ConstCase _ sc) = nu' ps sc
117 nua ps (DefaultCase sc) = nu' ps sc
119 nut ps (P Ref n _) | n `elem` ps = []
120 | otherwise = [(n, [])] -- tmp
121 nut ps fn@(App f a)
122 | (P Ref n _, args) <- unApply fn
123 = if n `elem` ps then nut ps f ++ nut ps a
124 else [(n, map argNames args)] ++ concatMap (nut ps) args
125 | otherwise = nut ps f ++ nut ps a
126 nut ps (Bind n (Let t v) sc) = nut ps v ++ nut (n:ps) sc
127 nut ps (Proj t _) = nut ps t
128 nut ps (Bind n b sc) = nut (n:ps) sc
129 nut ps _ = []
131 argNames tm = let ns = directUse tm in
132 filter (\x -> x `elem` ns) topargs
134-- Find names which are used directly (i.e. not in a function call) in a term
136directUse :: Eq n => TT n -> [n]
137directUse (P _ n _) = [n]
138directUse (Bind n (Let t v) sc) = nub $ directUse v ++ (directUse sc \\ [n])
139 ++ directUse t
140directUse (Bind n b sc) = nub $ directUse (binderTy b) ++ (directUse sc \\ [n])
141directUse fn@(App f a)
142 | (P Ref n _, args) <- unApply fn = [] -- need to know what n does with them
143 | otherwise = nub $ directUse f ++ directUse a
144directUse (Proj x i) = nub $ directUse x
145directUse _ = []
147-- Find all directly used arguments (i.e. used but not in function calls)
149findUsedArgs :: SC -> [Name] -> [Name]
150findUsedArgs sc topargs = nub (findAllUsedArgs sc topargs)
152findAllUsedArgs sc topargs = filter (\x -> x `elem` topargs) (nu' sc) where
153 nu' (Case n alts) = n : concatMap nua alts
154 nu' (ProjCase t alts) = directUse t ++ concatMap nua alts
155 nu' (STerm t) = directUse t
156 nu' _ = []
158 nua (ConCase n i args sc) = nu' sc
159 nua (ConstCase _ sc) = nu' sc
160 nua (DefaultCase sc) = nu' sc
162data Phase = CompileTime | RunTime
163 deriving (Show, Eq)
165-- Generate a simple case tree
166-- Work Right to Left
168simpleCase :: Bool -> Bool -> Phase -> FC -> [([Name], Term, Term)] ->
169 TC CaseDef
170simpleCase tc cover phase fc cs
171 = sc' tc cover phase fc (filter (\(_, _, r) ->
172 case r of
173 Impossible -> False
174 _ -> True) cs)
175 where
176 sc' tc cover phase fc []
177 = return $ CaseDef [] (UnmatchedCase "No pattern clauses") []
178 sc' tc cover phase fc cs
179 = let proj = phase == RunTime
180 pats = map (\ (avs, l, r) ->
181 (avs, toPats tc l, (l, r))) cs
182 chkPats = mapM chkAccessible pats in
183 case chkPats of
184 OK pats ->
185 let numargs = length (fst (head pats))
186 ns = take numargs args
187 (ns', ps') = order ns pats
188 (tree, st) = runState
189 (match ns' ps' (defaultCase cover)) ([], numargs)
190 t = CaseDef ns (prune proj (depatt ns' tree)) (fst st) in
191 if proj then return (stripLambdas t) else return t
192 Error err -> Error (At fc err)
193 where args = map (\i -> MN i "e") [0..]
194 defaultCase True = STerm Erased
195 defaultCase False = UnmatchedCase "Error"
197 chkAccessible (avs, l, c)
198 | phase == RunTime = return (l, c)
199 | otherwise = do mapM_ (acc l) avs
200 return (l, c)
202 acc [] n = Error (Inaccessible n)
203 acc (PV x : xs) n | x == n = OK ()
204 acc (PCon _ _ ps : xs) n = acc (ps ++ xs) n
205 acc (_ : xs) n = acc xs n
207data Pat = PCon Name Int [Pat]
208 | PConst Const
209 | PV Name
210 | PAny
211 deriving Show
213-- If there are repeated variables, take the *last* one (could be name shadowing
214-- in a where clause, so take the most recent).
216toPats :: Bool -> Term -> [Pat]
217toPats tc f = reverse (toPat tc (getArgs f)) where
218 getArgs (App f a) = a : getArgs f
219 getArgs _ = []
221toPat :: Bool -> [Term] -> [Pat]
222toPat tc tms = evalState (mapM (\x -> toPat' x []) tms) []
223 where
224 toPat' (P (DCon t a) n _) args = do args' <- mapM (\x -> toPat' x []) args
225 return $ PCon n t args'
226 -- Typecase
227 toPat' (P (TCon t a) n _) args | tc
228 = do args' <- mapM (\x -> toPat' x []) args
229 return $ PCon n t args'
230 toPat' (Constant IType) [] | tc = return $ PCon (UN "Int") 1 []
231 toPat' (Constant FlType) [] | tc = return $ PCon (UN "Float") 2 []
232 toPat' (Constant ChType) [] | tc = return $ PCon (UN "Char") 3 []
233 toPat' (Constant StrType) [] | tc = return $ PCon (UN "String") 4 []
234 toPat' (Constant PtrType) [] | tc = return $ PCon (UN "Ptr") 5 []
235 toPat' (Constant BIType) [] | tc = return $ PCon (UN "Integer") 6 []
236 toPat' (Constant B8Type) [] | tc = return $ PCon (UN "Bits8") 7 []
237 toPat' (Constant B16Type) [] | tc = return $ PCon (UN "Bits16") 8 []
238 toPat' (Constant B32Type) [] | tc = return $ PCon (UN "Bits32") 9 []
239 toPat' (Constant B64Type) [] | tc = return $ PCon (UN "Bits64") 10 []
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
251data Partition = Cons [Clause]
252 | Vars [Clause]
253 deriving Show
255isVarPat (PV _ : ps , _) = True
256isVarPat (PAny : ps , _) = True
257isVarPat _ = False
259isConPat (PCon _ _ _ : ps, _) = True
260isConPat (PConst _ : ps, _) = True
261isConPat _ = False
263partition :: [Clause] -> [Partition]
264partition [] = []
265partition ms@(m : _)
266 | isVarPat m = let (vars, rest) = span isVarPat ms in
267 Vars vars : partition rest
268 | isConPat m = let (cons, rest) = span isConPat ms in
269 Cons cons : partition rest
270partition xs = error $ "Partition " ++ show xs
272-- reorder the patterns so that the one with most distinct names
273-- comes next. Take rightmost first, otherwise (i.e. pick value rather
274-- than dependency)
276order :: [Name] -> [Clause] -> ([Name], [Clause])
277order [] cs = ([], cs)
278order ns [] = (ns, [])
279order ns cs = let patnames = transpose (map (zip ns) (map fst cs))
280 pats' = transpose (sortBy moreDistinct (reverse patnames)) in
281 (getNOrder pats', zipWith rebuild pats' cs)
282 where
283 getNOrder [] = error $ "Failed order on " ++ show (ns, cs)
284 getNOrder (c : _) = map fst c
286 rebuild patnames clause = (map snd patnames, snd clause)
288 moreDistinct xs ys = compare (numNames [] (map snd ys))
289 (numNames [] (map snd xs))
291 numNames xs (PCon n _ _ : ps)
292 | not (Left n `elem` xs) = numNames (Left n : xs) ps
293 numNames xs (PConst c : ps)
294 | not (Right c `elem` xs) = numNames (Right c : xs) ps
295 numNames xs (_ : ps) = numNames xs ps
296 numNames xs [] = length xs
298match :: [Name] -> [Clause] -> SC -- error case
299 -> State CS SC
300match [] (([], ret) : xs) err
301 = do (ts, v) <- get
302 put (ts ++ (map (fst.snd) xs), v)
303 case snd ret of
304 Impossible -> return ImpossibleCase
305 tm -> return $ STerm tm -- run out of arguments
306match vs cs err = do let ps = partition cs
307 mixture vs ps err
309mixture :: [Name] -> [Partition] -> SC -> State CS SC
310mixture vs [] err = return err
311mixture vs (Cons ms : ps) err = do fallthrough <- mixture vs ps err
312 conRule vs ms fallthrough
313mixture vs (Vars ms : ps) err = do fallthrough <- mixture vs ps err
314 varRule vs ms fallthrough
316data ConType = CName Name Int -- named constructor
317 | CConst Const -- constant, not implemented yet
319data Group = ConGroup ConType -- Constructor
320 [([Pat], Clause)] -- arguments and rest of alternative
322conRule :: [Name] -> [Clause] -> SC -> State CS SC
323conRule (v:vs) cs err = do groups <- groupCons cs
324 caseGroups (v:vs) groups err
326caseGroups :: [Name] -> [Group] -> SC -> State CS SC
327caseGroups (v:vs) gs err = do g <- altGroups gs
328 return $ Case v (sort g)
329 where
330 altGroups [] = return [DefaultCase err]
331 altGroups (ConGroup (CName n i) args : cs)
332 = do g <- altGroup n i args
333 rest <- altGroups cs
334 return (g : rest)
335 altGroups (ConGroup (CConst c) args : cs)
336 = do g <- altConstGroup c args
337 rest <- altGroups cs
338 return (g : rest)
340 altGroup n i gs = do (newArgs, nextCs) <- argsToAlt gs
341 matchCs <- match (newArgs ++ vs) nextCs err
342 return $ ConCase n i newArgs matchCs
343 altConstGroup n gs = do (_, nextCs) <- argsToAlt gs
344 matchCs <- match vs nextCs err
345 return $ ConstCase n matchCs
347argsToAlt :: [([Pat], Clause)] -> State CS ([Name], [Clause])
348argsToAlt [] = return ([], [])
349argsToAlt rs@((r, m) : rest)
350 = do newArgs <- getNewVars r
351 return (newArgs, addRs rs)
352 where
353 getNewVars [] = return []
354 getNewVars ((PV n) : ns) = do v <- getVar
355 nsv <- getNewVars ns
356 return (v : nsv)
357 getNewVars (_ : ns) = do v <- getVar
358 nsv <- getNewVars ns
359 return (v : nsv)
360 addRs [] = []
361 addRs ((r, (ps, res)) : rs) = ((r++ps, res) : addRs rs)
363 uniq i (UN n) = MN i n
364 uniq i n = n
366getVar :: State CS Name
367getVar = do (t, v) <- get; put (t, v+1); return (MN v "e")
369groupCons :: [Clause] -> State CS [Group]
370groupCons cs = gc [] cs
371 where
372 gc acc [] = return acc
373 gc acc ((p : ps, res) : cs) =
374 do acc' <- addGroup p ps res acc
375 gc acc' cs
376 addGroup p ps res acc = case p of
377 PCon con i args -> return $ addg con i args (ps, res) acc
378 PConst cval -> return $ addConG cval (ps, res) acc
379 pat -> fail $ show pat ++ " is not a constructor or constant (can't happen)"
381 addg con i conargs res [] = [ConGroup (CName con i) [(conargs, res)]]
382 addg con i conargs res (g@(ConGroup (CName n j) cs):gs)
383 | i == j = ConGroup (CName n i) (cs ++ [(conargs, res)]) : gs
384 | otherwise = g : addg con i conargs res gs
386 addConG con res [] = [ConGroup (CConst con) [([], res)]]
387 addConG con res (g@(ConGroup (CConst n) cs) : gs)
388 | con == n = ConGroup (CConst n) (cs ++ [([], res)]) : gs
389 | otherwise = g : addConG con res gs
391varRule :: [Name] -> [Clause] -> SC -> State CS SC
392varRule (v : vs) alts err =
393 do let alts' = map (repVar v) alts
394 match vs alts' err
395 where
396 repVar v (PV p : ps , (lhs, res)) = (ps, (lhs, subst p (P Bound v Erased) res))
397 repVar v (PAny : ps , res) = (ps, res)
399-- fix: case e of S k -> f (S k) ==> case e of S k -> f e
400depatt :: [Name] -> SC -> SC
401depatt ns tm = dp [] tm
402 where
403 dp ms (STerm tm) = STerm (applyMaps ms tm)
404 dp ms (Case x alts) = Case x (map (dpa ms x) alts)
405 dp ms sc = sc
407 dpa ms x (ConCase n i args sc)
408 = ConCase n i args (dp ((x, (n, args)) : ms) sc)
409 dpa ms x (ConstCase c sc) = ConstCase c (dp ms sc)
410 dpa ms x (DefaultCase sc) = DefaultCase (dp ms sc)
412 applyMaps ms f@(App _ _)
413 | (P nt cn pty, args) <- unApply f
414 = let args' = map (applyMaps ms) args in
415 applyMap ms nt cn pty args'
416 where
417 applyMap [] nt cn pty args' = mkApp (P nt cn pty) args'
418 applyMap ((x, (n, args)) : ms) nt cn pty args'
419 | and ((length args == length args') :
420 (n == cn) : zipWith same args args') = P Ref x Erased
421 | otherwise = applyMap ms nt cn pty args'
422 same n (P _ n' _) = n == n'
423 same _ _ = False
424 applyMaps ms (App f a) = App (applyMaps ms f) (applyMaps ms a)
425 applyMaps ms t = t
427prune :: Bool -- ^ Convert single branches to projections (only useful at runtime)
428 -> SC -> SC
429prune proj (Case n alts)
430 = let alts' = filter notErased (map pruneAlt alts) in
431 case alts' of
432 [] -> ImpossibleCase
433 as@[ConCase cn i args sc] -> if proj then mkProj n 0 args sc
434 else Case n as
435 as -> Case n as
436 where pruneAlt (ConCase cn i ns sc) = ConCase cn i ns (prune proj sc)
437 pruneAlt (ConstCase c sc) = ConstCase c (prune proj sc)
438 pruneAlt (DefaultCase sc) = DefaultCase (prune proj sc)
440 notErased (DefaultCase (STerm Erased)) = False
441 notErased (DefaultCase ImpossibleCase) = False
442 notErased _ = True
444 mkProj n i [] sc = sc
445 mkProj n i (x : xs) sc = mkProj n (i + 1) xs (projRep x n i sc)
447 projRep :: Name -> Name -> Int -> SC -> SC
448 projRep arg n i (Case x alts)
449 | x == arg = ProjCase (Proj (P Bound n Erased) i)
450 (map (projRepAlt arg n i) alts)
451 | otherwise = Case x (map (projRepAlt arg n i) alts)
452 projRep arg n i (ProjCase t alts)
453 = ProjCase (projRepTm arg n i t) (map (projRepAlt arg n i) alts)
454 projRep arg n i (STerm t) = STerm (projRepTm arg n i t)
455 projRep arg n i c = c -- unmatched
457 projRepAlt arg n i (ConCase cn t args rhs)
458 = ConCase cn t args (projRep arg n i rhs)
459 projRepAlt arg n i (ConstCase t rhs)
460 = ConstCase t (projRep arg n i rhs)
461 projRepAlt arg n i (DefaultCase rhs)
462 = DefaultCase (projRep arg n i rhs)
464 projRepTm arg n i t = subst arg (Proj (P Bound n Erased) i) t
466prune _ t = t
468stripLambdas :: CaseDef -> CaseDef
469stripLambdas (CaseDef ns (STerm (Bind x (Lam _) sc)) tm)
470 = stripLambdas (CaseDef (ns ++ [x]) (STerm (instantiate (P Bound x Erased) sc)) tm)
471stripLambdas x = x