on ec85560 help sign in
Idris-dev/src/Idris/Core/CaseTree.hs
673 lines 27 kB history raw
1{-# LANGUAGE PatternGuards, DeriveFunctor, TypeSynonymInstances #-}
3module Idris.Core.CaseTree(CaseDef(..), SC, SC'(..), CaseAlt, CaseAlt'(..),
4 Phase(..), CaseTree,
5 simpleCase, small, namesUsed, findCalls, findUsedArgs) where
7import Idris.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'
25deriving instance NFData SC'
26!-}
28type SC = SC' Term
30data CaseAlt' t = ConCase Name Int [Name] !(SC' t)
31 | FnCase Name [Name] !(SC' t) -- ^ reflection function
32 | ConstCase Const !(SC' t)
33 | SucCase Name !(SC' t)
34 | DefaultCase !(SC' t)
35 deriving (Show, Eq, Ord, Functor)
36{-!
37deriving instance Binary CaseAlt'
38deriving instance NFData CaseAlt'
39!-}
41type CaseAlt = CaseAlt' Term
43instance Show t => Show (SC' t) where
44 show sc = show' 1 sc
45 where
46 show' i (Case n alts) = "case " ++ show n ++ " of\n" ++ indent i ++
47 showSep ("\n" ++ indent i) (map (showA i) alts)
48 show' i (ProjCase tm alt) = "case " ++ show tm ++ " of " ++
49 showSep ("\n" ++ indent i) (map (showA i) [alt])
50 show' i (STerm tm) = show tm
51 show' i (UnmatchedCase str) = "error " ++ show str
52 show' i ImpossibleCase = "impossible"
54 indent i = concat $ take i (repeat " ")
56 showA i (ConCase n t args sc)
57 = show n ++ "(" ++ showSep (", ") (map show args) ++ ") => "
58 ++ show' (i+1) sc
59 showA i (FnCase n args sc)
60 = "FN " ++ show n ++ "(" ++ showSep (", ") (map show args) ++ ") => "
61 ++ show' (i+1) sc
62 showA i (ConstCase t sc)
63 = show t ++ " => " ++ show' (i+1) sc
64 showA i (SucCase n sc)
65 = show n ++ "+1 => " ++ show' (i+1) sc
66 showA i (DefaultCase sc)
67 = "_ => " ++ show' (i+1) sc
70type CaseTree = SC
71type Clause = ([Pat], (Term, Term))
72type CS = ([Term], Int, [(Name, Type)])
74instance TermSize SC where
75 termsize n (Case n' as) = termsize n as
76 termsize n (ProjCase n' as) = termsize n as
77 termsize n (STerm t) = termsize n t
78 termsize n _ = 1
80instance TermSize CaseAlt where
81 termsize n (ConCase _ _ _ s) = termsize n s
82 termsize n (FnCase _ _ s) = termsize n s
83 termsize n (ConstCase _ s) = termsize n s
84 termsize n (SucCase _ s) = termsize n s
85 termsize n (DefaultCase s) = termsize n s
87-- simple terms can be inlined trivially - good for primitives in particular
88-- To avoid duplicating work, don't inline something which uses one
89-- of its arguments in more than one place
91small :: Name -> [Name] -> SC -> Bool
92small n args t = let as = findAllUsedArgs t args in
93 length as == length (nub as) &&
94 termsize n t < 10
96namesUsed :: SC -> [Name]
97namesUsed sc = nub $ nu' [] sc where
98 nu' ps (Case n alts) = nub (concatMap (nua ps) alts) \\ [n]
99 nu' ps (ProjCase t alt) = nub $ nut ps t ++ nua ps alt
100 nu' ps (STerm t) = nub $ nut ps t
101 nu' ps _ = []
103 nua ps (ConCase n i args sc) = nub (nu' (ps ++ args) sc) \\ args
104 nua ps (FnCase n args sc) = nub (nu' (ps ++ args) sc) \\ args
105 nua ps (ConstCase _ sc) = nu' ps sc
106 nua ps (SucCase _ sc) = nu' ps sc
107 nua ps (DefaultCase sc) = nu' ps sc
109 nut ps (P _ n _) | n `elem` ps = []
110 | otherwise = [n]
111 nut ps (App f a) = nut ps f ++ nut ps a
112 nut ps (Proj t _) = nut ps t
113 nut ps (Bind n (Let t v) sc) = nut ps v ++ nut (n:ps) sc
114 nut ps (Bind n b sc) = nut (n:ps) sc
115 nut ps _ = []
117-- Return all called functions, and which arguments are used in each argument position
118-- for the call, in order to help reduce compilation time, and trace all unused
119-- arguments
121findCalls :: SC -> [Name] -> [(Name, [[Name]])]
122findCalls sc topargs = nub $ nu' topargs sc where
123 nu' ps (Case n alts) = nub (concatMap (nua (n : ps)) alts)
124 nu' ps (ProjCase t alt) = nub (nut ps t ++ nua ps alt)
125 nu' ps (STerm t) = nub $ nut ps t
126 nu' ps _ = []
128 nua ps (ConCase n i args sc) = nub (nu' (ps ++ args) sc)
129 nua ps (FnCase n args sc) = nub (nu' (ps ++ args) sc)
130 nua ps (ConstCase _ sc) = nu' ps sc
131 nua ps (SucCase _ sc) = nu' ps sc
132 nua ps (DefaultCase sc) = nu' ps sc
134 nut ps (P Ref n _) | n `elem` ps = []
135 | otherwise = [(n, [])] -- tmp
136 nut ps fn@(App f a)
137 | (P Ref n _, args) <- unApply fn
138 = if n `elem` ps then nut ps f ++ nut ps a
139 else [(n, map argNames args)] ++ concatMap (nut ps) args
140 | (P (TCon _ _) n _, _) <- unApply fn = []
141 | otherwise = nut ps f ++ nut ps a
142 nut ps (Bind n (Let t v) sc) = nut ps v ++ nut (n:ps) sc
143 nut ps (Proj t _) = nut ps t
144 nut ps (Bind n b sc) = nut (n:ps) sc
145 nut ps _ = []
147 argNames tm = let ns = directUse tm in
148 filter (\x -> x `elem` ns) topargs
150-- Find names which are used directly (i.e. not in a function call) in a term
152directUse :: TT Name -> [Name]
153directUse (P _ n _) = [n]
154directUse (Bind n (Let t v) sc) = nub $ directUse v ++ (directUse sc \\ [n])
155 ++ directUse t
156directUse (Bind n b sc) = nub $ directUse (binderTy b) ++ (directUse sc \\ [n])
157directUse fn@(App f a)
158 | (P Ref (UN pfk) _, [App e w]) <- unApply fn,
159 pfk == txt "prim_fork"
160 = directUse e ++ directUse w -- HACK so that fork works
161 | (P Ref (UN fce) _, [_, _, a]) <- unApply fn,
162 fce == txt "Force"
163 = directUse a -- forcing a value counts as a use
164 | (P Ref n _, args) <- unApply fn = [] -- need to know what n does with them
165 | (P (TCon _ _) n _, args) <- unApply fn = [] -- type constructors not used at runtime
166 | otherwise = nub $ directUse f ++ directUse a
167directUse (Proj x i) = nub $ directUse x
168directUse _ = []
170-- Find all directly used arguments (i.e. used but not in function calls)
172findUsedArgs :: SC -> [Name] -> [Name]
173findUsedArgs sc topargs = nub (findAllUsedArgs sc topargs)
175findAllUsedArgs sc topargs = filter (\x -> x `elem` topargs) (nu' sc) where
176 nu' (Case n alts) = n : concatMap nua alts
177 nu' (ProjCase t alt) = directUse t ++ nua alt
178 nu' (STerm t) = directUse t
179 nu' _ = []
181 nua (ConCase n i args sc) = nu' sc
182 nua (FnCase n args sc) = nu' sc
183 nua (ConstCase _ sc) = nu' sc
184 nua (SucCase _ sc) = nu' sc
185 nua (DefaultCase sc) = nu' sc
187data Phase = CompileTime | RunTime
188 deriving (Show, Eq)
190-- Generate a simple case tree
191-- Work Right to Left
193simpleCase :: Bool -> Bool -> Bool ->
194 Phase -> FC -> [Type] ->
195 [([Name], Term, Term)] ->
196 TC CaseDef
197simpleCase tc cover reflect phase fc argtys cs
198 = sc' tc cover phase fc (filter (\(_, _, r) ->
199 case r of
200 Impossible -> False
201 _ -> True) cs)
202 where
203 sc' tc cover phase fc []
204 = return $ CaseDef [] (UnmatchedCase "No pattern clauses") []
205 sc' tc cover phase fc cs
206 = let proj = phase == RunTime
207 vnames = fstT (head cs)
208 pats = map (\ (avs, l, r) ->
209 (avs, toPats reflect tc l, (l, r))) cs
210 chkPats = mapM chkAccessible pats in
211 case chkPats of
212 OK pats ->
213 let numargs = length (fst (head pats))
214 ns = take numargs args
215 (ns', ps') = order ns pats
216 (tree, st) = runState
217 (match ns' ps' (defaultCase cover))
218 ([], numargs, [])
219 t = CaseDef ns (prune proj (depatt ns' tree)) (fstT st) in
220 if proj then return (stripLambdas t)
221 else return t
222-- FIXME: This check is not quite right in some cases, and is breaking
223-- perfectly valid code!
224-- if checkSameTypes (lstT st) tree
225-- then return t
226-- else Error (At fc (Msg "Typecase is not allowed"))
227 Error err -> Error (At fc err)
228 where args = map (\i -> sMN i "e") [0..]
229 defaultCase True = STerm Erased
230 defaultCase False = UnmatchedCase "Error"
231 fstT (x, _, _) = x
232 lstT (_, _, x) = x
234 chkAccessible (avs, l, c)
235 | phase == RunTime || reflect = return (l, c)
236 | otherwise = do mapM_ (acc l) avs
237 return (l, c)
239 acc [] n = Error (Inaccessible n)
240 acc (PV x t : xs) n | x == n = OK ()
241 acc (PCon _ _ ps : xs) n = acc (ps ++ xs) n
242 acc (PSuc p : xs) n = acc (p : xs) n
243 acc (_ : xs) n = acc xs n
245-- For each 'Case', make sure every choice is in the same type family,
246-- as directed by the variable type (i.e. there is no implicit type casing
247-- going on).
249checkSameTypes :: [(Name, Type)] -> SC -> Bool
250checkSameTypes tys (Case n alts)
251 = case lookup n tys of
252 Just t -> and (map (checkAlts t) alts)
253 _ -> and (map ((checkSameTypes tys).getSC) alts)
254 where
255 checkAlts t (ConCase n _ _ sc) = isType n t && checkSameTypes tys sc
256 checkAlts (Constant t) (ConstCase c sc) = isConstType c t && checkSameTypes tys sc
257 checkAlts _ (ConstCase c sc) = False
258 checkAlts _ _ = True
260 getSC (ConCase _ _ _ sc) = sc
261 getSC (FnCase _ _ sc) = sc
262 getSC (ConstCase _ sc) = sc
263 getSC (SucCase _ sc) = sc
264 getSC (DefaultCase sc) = sc
265checkSameTypes _ _ = True
267-- FIXME: All we're actually doing here is checking that we haven't arrived
268-- at a specific constructor for a polymorphic argument. I *think* this
269-- is sufficient, but if it turns out not to be, fix it!
270isType n t | (P (TCon _ _) _ _, _) <- unApply t = True
271isType n t | (P Ref _ _, _) <- unApply t = True
272isType n t = False
274isConstType (I _) (AType (ATInt ITNative)) = True
275isConstType (BI _) (AType (ATInt ITBig)) = True
276isConstType (Fl _) (AType ATFloat) = True
277isConstType (Ch _) (AType (ATInt ITChar)) = True
278isConstType (Str _) StrType = True
279isConstType (B8 _) (AType (ATInt _)) = True
280isConstType (B16 _) (AType (ATInt _)) = True
281isConstType (B32 _) (AType (ATInt _)) = True
282isConstType (B64 _) (AType (ATInt _)) = True
283isConstType (B8V _) (AType (ATInt _)) = True
284isConstType (B16V _) (AType (ATInt _)) = True
285isConstType (B32V _) (AType (ATInt _)) = True
286isConstType (B64V _) (AType (ATInt _)) = True
287isConstType _ _ = False
289data Pat = PCon Name Int [Pat]
290 | PConst Const
291 | PV Name Type
292 | PSuc Pat -- special case for n+1 on Integer
293 | PReflected Name [Pat]
294 | PAny
295 | PTyPat -- typecase, not allowed, inspect last
296 deriving Show
298-- If there are repeated variables, take the *last* one (could be name shadowing
299-- in a where clause, so take the most recent).
301toPats :: Bool -> Bool -> Term -> [Pat]
302toPats reflect tc f = reverse (toPat reflect tc (getArgs f)) where
303 getArgs (App f a) = a : getArgs f
304 getArgs _ = []
306toPat :: Bool -> Bool -> [Term] -> [Pat]
307toPat reflect tc tms = evalState (mapM (\x -> toPat' x []) tms) []
308 where
309 toPat' (P (DCon t a) n _) args = do args' <- mapM (\x -> toPat' x []) args
310 return $ PCon n t args'
311 -- n + 1
312 toPat' (P _ (UN pabi) _)
313 [p, Constant (BI 1)] | pabi == txt "prim__addBigInt"
314 = do p' <- toPat' p []
315 return $ PSuc p'
316 -- Typecase
317-- toPat' (P (TCon t a) n _) args | tc
318-- = do args' <- mapM (\x -> toPat' x []) args
319-- return $ PCon n t args'
320-- toPat' (Constant (AType (ATInt ITNative))) []
321-- | tc = return $ PCon (UN "Int") 1 []
322-- toPat' (Constant (AType ATFloat)) [] | tc = return $ PCon (UN "Float") 2 []
323-- toPat' (Constant (AType (ATInt ITChar))) [] | tc = return $ PCon (UN "Char") 3 []
324-- toPat' (Constant StrType) [] | tc = return $ PCon (UN "String") 4 []
325-- toPat' (Constant PtrType) [] | tc = return $ PCon (UN "Ptr") 5 []
326-- toPat' (Constant (AType (ATInt ITBig))) []
327-- | tc = return $ PCon (UN "Integer") 6 []
328-- toPat' (Constant (AType (ATInt (ITFixed n)))) []
329-- | tc = return $ PCon (UN (fixedN n)) (7 + fromEnum n) [] -- 7-10 inclusive
330 toPat' (P Bound n ty) [] = -- trace (show (n, ty)) $
331 do ns <- get
332 if n `elem` ns
333 then return PAny
334 else do put (n : ns)
335 return (PV n ty)
336 toPat' (App f a) args = toPat' f (a : args)
337 toPat' (Constant (AType _)) [] = return PTyPat
338 toPat' (Constant StrType) [] = return PTyPat
339 toPat' (Constant PtrType) [] = return PTyPat
340 toPat' (Constant VoidType) [] = return PTyPat
341 toPat' (Constant x) [] = return $ PConst x
342 toPat' (Bind n (Pi t) sc) [] | reflect && noOccurrence n sc
343 = do t' <- toPat' t []
344 sc' <- toPat' sc []
345 return $ PReflected (sUN "->") (t':sc':[])
346 toPat' (P _ n _) args | reflect
347 = do args' <- mapM (\x -> toPat' x []) args
348 return $ PReflected n args'
349 toPat' t _ = return PAny
351 fixedN IT8 = "Bits8"
352 fixedN IT16 = "Bits16"
353 fixedN IT32 = "Bits32"
354 fixedN IT64 = "Bits64"
357data Partition = Cons [Clause]
358 | Vars [Clause]
359 deriving Show
361isVarPat (PV _ _ : ps , _) = True
362isVarPat (PAny : ps , _) = True
363isVarPat (PTyPat : ps , _) = True
364isVarPat _ = False
366isConPat (PCon _ _ _ : ps, _) = True
367isConPat (PReflected _ _ : ps, _) = True
368isConPat (PSuc _ : ps, _) = True
369isConPat (PConst _ : ps, _) = True
370isConPat _ = False
372partition :: [Clause] -> [Partition]
373partition [] = []
374partition ms@(m : _)
375 | isVarPat m = let (vars, rest) = span isVarPat ms in
376 Vars vars : partition rest
377 | isConPat m = let (cons, rest) = span isConPat ms in
378 Cons cons : partition rest
379partition xs = error $ "Partition " ++ show xs
381-- reorder the patterns so that the one with most distinct names
382-- comes next. Take rightmost first, otherwise (i.e. pick value rather
383-- than dependency)
385order :: [Name] -> [Clause] -> ([Name], [Clause])
386order [] cs = ([], cs)
387order ns [] = (ns, [])
388order ns cs = let patnames = transpose (map (zip ns) (map fst cs))
389 pats' = transpose (sortBy moreDistinct (reverse patnames)) in
390 (getNOrder pats', zipWith rebuild pats' cs)
391 where
392 getNOrder [] = error $ "Failed order on " ++ show (ns, cs)
393 getNOrder (c : _) = map fst c
395 rebuild patnames clause = (map snd patnames, snd clause)
397 moreDistinct xs ys = compare (numNames [] (map snd ys))
398 (numNames [] (map snd xs))
400 numNames xs (PCon n _ _ : ps)
401 | not (Left n `elem` xs) = numNames (Left n : xs) ps
402 numNames xs (PConst c : ps)
403 | not (Right c `elem` xs) = numNames (Right c : xs) ps
404 numNames xs (_ : ps) = numNames xs ps
405 numNames xs [] = length xs
407match :: [Name] -> [Clause] -> SC -- error case
408 -> State CS SC
409match [] (([], ret) : xs) err
410 = do (ts, v, ntys) <- get
411 put (ts ++ (map (fst.snd) xs), v, ntys)
412 case snd ret of
413 Impossible -> return ImpossibleCase
414 tm -> return $ STerm tm -- run out of arguments
415match vs cs err = do let ps = partition cs
416 mixture vs ps err
418mixture :: [Name] -> [Partition] -> SC -> State CS SC
419mixture vs [] err = return err
420mixture vs (Cons ms : ps) err = do fallthrough <- mixture vs ps err
421 conRule vs ms fallthrough
422mixture vs (Vars ms : ps) err = do fallthrough <- mixture vs ps err
423 varRule vs ms fallthrough
425data ConType = CName Name Int -- named constructor
426 | CFn Name -- reflected function name
427 | CSuc -- n+1
428 | CConst Const -- constant, not implemented yet
429 deriving (Show, Eq)
431data Group = ConGroup ConType -- Constructor
432 [([Pat], Clause)] -- arguments and rest of alternative
433 deriving Show
435conRule :: [Name] -> [Clause] -> SC -> State CS SC
436conRule (v:vs) cs err = do groups <- groupCons cs
437 caseGroups (v:vs) groups err
439caseGroups :: [Name] -> [Group] -> SC -> State CS SC
440caseGroups (v:vs) gs err = do g <- altGroups gs
441 return $ Case v (sort g)
442 where
443 altGroups [] = return [DefaultCase err]
444 altGroups (ConGroup (CName n i) args : cs)
445 = do g <- altGroup n i args
446 rest <- altGroups cs
447 return (g : rest)
448 altGroups (ConGroup (CFn n) args : cs)
449 = do g <- altFnGroup n args
450 rest <- altGroups cs
451 return (g : rest)
452 altGroups (ConGroup CSuc args : cs)
453 = do g <- altSucGroup args
454 rest <- altGroups cs
455 return (g : rest)
456 altGroups (ConGroup (CConst c) args : cs)
457 = do g <- altConstGroup c args
458 rest <- altGroups cs
459 return (g : rest)
461 altGroup n i gs = do (newArgs, nextCs) <- argsToAlt gs
462 matchCs <- match (newArgs ++ vs) nextCs err
463 return $ ConCase n i newArgs matchCs
464 altFnGroup n gs = do (newArgs, nextCs) <- argsToAlt gs
465 matchCs <- match (newArgs ++ vs) nextCs err
466 return $ FnCase n newArgs matchCs
467 altSucGroup gs = do ([newArg], nextCs) <- argsToAlt gs
468 matchCs <- match (newArg:vs) nextCs err
469 return $ SucCase newArg matchCs
470 altConstGroup n gs = do (_, nextCs) <- argsToAlt gs
471 matchCs <- match vs nextCs err
472 return $ ConstCase n matchCs
474argsToAlt :: [([Pat], Clause)] -> State CS ([Name], [Clause])
475argsToAlt [] = return ([], [])
476argsToAlt rs@((r, m) : rest)
477 = do newArgs <- getNewVars r
478 return (newArgs, addRs rs)
479 where
480 getNewVars [] = return []
481 getNewVars ((PV n t) : ns) = do v <- getVar "e"
482 (cs, i, ntys) <- get
483 put (cs, i, (v, t) : ntys)
484 nsv <- getNewVars ns
485 return (v : nsv)
486 getNewVars (PAny : ns) = do v <- getVar "i"
487 nsv <- getNewVars ns
488 return (v : nsv)
489 getNewVars (PTyPat : ns) = do v <- getVar "t"
490 nsv <- getNewVars ns
491 return (v : nsv)
492 getNewVars (_ : ns) = do v <- getVar "e"
493 nsv <- getNewVars ns
494 return (v : nsv)
495 addRs [] = []
496 addRs ((r, (ps, res)) : rs) = ((r++ps, res) : addRs rs)
498 uniq i (UN n) = MN i n
499 uniq i n = n
501getVar :: String -> State CS Name
502getVar b = do (t, v, ntys) <- get; put (t, v+1, ntys); return (sMN v b)
504groupCons :: [Clause] -> State CS [Group]
505groupCons cs = gc [] cs
506 where
507 gc acc [] = return acc
508 gc acc ((p : ps, res) : cs) =
509 do acc' <- addGroup p ps res acc
510 gc acc' cs
511 addGroup p ps res acc = case p of
512 PCon con i args -> return $ addg (CName con i) args (ps, res) acc
513 PConst cval -> return $ addConG cval (ps, res) acc
514 PSuc n -> return $ addg CSuc [n] (ps, res) acc
515 PReflected fn args -> return $ addg (CFn fn) args (ps, res) acc
516 pat -> fail $ show pat ++ " is not a constructor or constant (can't happen)"
518 addg c conargs res []
519 = [ConGroup c [(conargs, res)]]
520 addg c conargs res (g@(ConGroup c' cs):gs)
521 | c == c' = ConGroup c (cs ++ [(conargs, res)]) : gs
522 | otherwise = g : addg c conargs res gs
524 addConG con res [] = [ConGroup (CConst con) [([], res)]]
525 addConG con res (g@(ConGroup (CConst n) cs) : gs)
526 | con == n = ConGroup (CConst n) (cs ++ [([], res)]) : gs
527-- | otherwise = g : addConG con res gs
528 addConG con res (g : gs) = g : addConG con res gs
530varRule :: [Name] -> [Clause] -> SC -> State CS SC
531varRule (v : vs) alts err =
532 do alts' <- mapM (repVar v) alts
533 match vs alts' err
534 where
535 repVar v (PV p ty : ps , (lhs, res))
536 = do (cs, i, ntys) <- get
537 put (cs, i, (v, ty) : ntys)
538 return (ps, (lhs, subst p (P Bound v ty) res))
539 repVar v (PAny : ps , res) = return (ps, res)
540 repVar v (PTyPat : ps , res) = return (ps, res)
542-- fix: case e of S k -> f (S k) ==> case e of S k -> f e
544depatt :: [Name] -> SC -> SC
545depatt ns tm = dp [] tm
546 where
547 dp ms (STerm tm) = STerm (applyMaps ms tm)
548 dp ms (Case x alts) = Case x (map (dpa ms x) alts)
549 dp ms sc = sc
551 dpa ms x (ConCase n i args sc)
552 = ConCase n i args (dp ((x, (n, args)) : ms) sc)
553 dpa ms x (FnCase n args sc)
554 = FnCase n args (dp ((x, (n, args)) : ms) sc)
555 dpa ms x (ConstCase c sc) = ConstCase c (dp ms sc)
556 dpa ms x (SucCase n sc) = SucCase n (dp ms sc)
557 dpa ms x (DefaultCase sc) = DefaultCase (dp ms sc)
559 applyMaps ms f@(App _ _)
560 | (P nt cn pty, args) <- unApply f
561 = let args' = map (applyMaps ms) args in
562 applyMap ms nt cn pty args'
563 where
564 applyMap [] nt cn pty args' = mkApp (P nt cn pty) args'
565 applyMap ((x, (n, args)) : ms) nt cn pty args'
566 | and ((length args == length args') :
567 (n == cn) : zipWith same args args') = P Ref x Erased
568 | otherwise = applyMap ms nt cn pty args'
569 same n (P _ n' _) = n == n'
570 same _ _ = False
572 applyMaps ms (App f a) = App (applyMaps ms f) (applyMaps ms a)
573 applyMaps ms t = t
575-- FIXME: Do this for SucCase too
576prune :: Bool -- ^ Convert single branches to projections (only useful at runtime)
577 -> SC -> SC
578prune proj (Case n alts)
579 = let alts' = filter notErased (map pruneAlt alts) in
580 case alts' of
581 [] -> ImpossibleCase
582 as@(ConCase (UN delay) i [arg] sc : _)
583 | delay == txt "Delay"
584 -> if proj then mkForce n arg sc
585 else Case n as
586 as@[ConCase cn i args sc] -> if proj && False then mkProj n 0 args sc
587 else Case n as
588 as@[SucCase cn sc] -> if proj then mkProj n (-1) [cn] sc
589 else Case n as
590 as@[ConstCase _ sc] -> prune proj sc
591 -- Bit of a hack here! The default case will always be 0, make sure
592 -- it gets caught first.
593 [s@(SucCase _ _), DefaultCase dc]
594 -> Case n [ConstCase (BI 0) dc, s]
595 as -> Case n as
596 where pruneAlt (ConCase cn i ns sc) = ConCase cn i ns (prune proj sc)
597 pruneAlt (FnCase cn ns sc) = FnCase cn ns (prune proj sc)
598 pruneAlt (ConstCase c sc) = ConstCase c (prune proj sc)
599 pruneAlt (SucCase n sc) = SucCase n (prune proj sc)
600 pruneAlt (DefaultCase sc) = DefaultCase (prune proj sc)
602 notErased (DefaultCase (STerm Erased)) = False
603 notErased (DefaultCase ImpossibleCase) = False
604 notErased _ = True
606 mkForce n arg (Case x alts)
607 | x == arg = ProjCase (forceArg n)
608 (map (mkForceAlt n arg) alts)
609 | otherwise = Case x (map (mkForceAlt n arg) alts)
610 mkForce n arg (ProjCase t alts)
611 = ProjCase (forceTm n arg t) (map (mkForceAlt n arg) alts)
612 mkForce n arg (STerm t) = STerm (forceTm n arg t)
613 mkForce n arg c = c
615 mkForceAlt n arg (ConCase cn t args rhs)
616 = ConCase cn t args (mkForce n arg rhs)
617 mkForceAlt n arg (FnCase cn args rhs)
618 = FnCase cn args (mkForce n arg rhs)
619 mkForceAlt n arg (ConstCase t rhs)
620 = ConstCase t (mkForce n arg rhs)
621 mkForceAlt n arg (SucCase sn rhs)
622 = SucCase sn (mkForce n arg rhs)
623 mkForceAlt n arg (DefaultCase rhs)
624 = DefaultCase (mkForce n arg rhs)
626 forceTm n arg t = subst arg (forceArg n) t
628 forceArg n = App (App (App (P Ref (sUN "Force") Erased) Erased) Erased)
629 (P Bound n Erased)
631 mkProj n i [] sc = prune proj sc
632 mkProj n i (x : xs) sc = mkProj n (i + 1) xs (projRep x n i sc)
634 -- Change every 'n' in sc to 'n-1'
635-- mkProjS n cn sc = prune proj (fmap projn sc) where
636-- projn pn@(P _ n' _)
637-- | cn == n' = App (App (P Ref (UN "prim__subBigInt") Erased)
638-- (P Bound n Erased)) (Constant (BI 1))
639-- projn t = t
641 projRep :: Name -> Name -> Int -> SC -> SC
642 projRep arg n i (Case x [alt]) | x == arg
643 = ProjCase (Proj (P Bound n Erased) i) (projRepAlt arg n i alt)
644 projRep arg n i (Case x alts)
645 = Case x (map (projRepAlt arg n i) alts)
646 projRep arg n i (ProjCase t alt)
647 = ProjCase (projRepTm arg n i t) (projRepAlt arg n i alt)
648 projRep arg n i (STerm t) = STerm (projRepTm arg n i t)
649 projRep arg n i c = c -- unmatched
651 projRepAlt arg n i (ConCase cn t args rhs)
652 = ConCase cn t args (projRep arg n i rhs)
653 projRepAlt arg n i (FnCase cn args rhs)
654 = FnCase cn args (projRep arg n i rhs)
655 projRepAlt arg n i (ConstCase t rhs)
656 = ConstCase t (projRep arg n i rhs)
657 projRepAlt arg n i (SucCase sn rhs)
658 = SucCase sn (projRep arg n i rhs)
659 projRepAlt arg n i (DefaultCase rhs)
660 = DefaultCase (projRep arg n i rhs)
662 projRepTm arg n i t = subst arg (Proj (P Bound n Erased) i) t
664prune _ t = t
666stripLambdas :: CaseDef -> CaseDef
667stripLambdas (CaseDef ns (STerm (Bind x (Lam _) sc)) tm)
668 = stripLambdas (CaseDef (ns ++ [x]) (STerm (instantiate (P Bound x Erased) sc)) tm)
669stripLambdas x = x