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