on 751a6ee help sign in
Idris-dev/src/Idris/Core/CaseTree.hs
674 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 alts) = "case " ++ show tm ++ " of " ++
49 showSep ("\n" ++ indent i) (map (showA i) alts)
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 alts) = nub $ (nut ps t ++
100 (concatMap (nua ps) alts))
101 nu' ps (STerm t) = nub $ nut ps t
102 nu' ps _ = []
104 nua ps (ConCase n i args sc) = nub (nu' (ps ++ args) sc) \\ args
105 nua ps (FnCase n args sc) = nub (nu' (ps ++ args) sc) \\ args
106 nua ps (ConstCase _ sc) = nu' ps sc
107 nua ps (SucCase _ sc) = nu' ps sc
108 nua ps (DefaultCase sc) = nu' ps sc
110 nut ps (P _ n _) | n `elem` ps = []
111 | otherwise = [n]
112 nut ps (App f a) = nut ps f ++ nut ps a
113 nut ps (Proj t _) = nut ps t
114 nut ps (Bind n (Let t v) sc) = nut ps v ++ nut (n:ps) sc
115 nut ps (Bind n b sc) = nut (n:ps) sc
116 nut ps _ = []
118-- Return all called functions, and which arguments are used in each argument position
119-- for the call, in order to help reduce compilation time, and trace all unused
120-- arguments
122findCalls :: SC -> [Name] -> [(Name, [[Name]])]
123findCalls sc topargs = nub $ nu' topargs sc where
124 nu' ps (Case n alts) = nub (concatMap (nua (n : ps)) alts)
125 nu' ps (ProjCase t alts) = nub (nut ps t ++ concatMap (nua ps) alts)
126 nu' ps (STerm t) = nub $ nut ps t
127 nu' ps _ = []
129 nua ps (ConCase n i args sc) = nub (nu' (ps ++ args) sc)
130 nua ps (FnCase n args sc) = nub (nu' (ps ++ args) sc)
131 nua ps (ConstCase _ sc) = nu' ps sc
132 nua ps (SucCase _ sc) = nu' ps sc
133 nua ps (DefaultCase sc) = nu' ps sc
135 nut ps (P Ref n _) | n `elem` ps = []
136 | otherwise = [(n, [])] -- tmp
137 nut ps fn@(App f a)
138 | (P Ref n _, args) <- unApply fn
139 = if n `elem` ps then nut ps f ++ nut ps a
140 else [(n, map argNames args)] ++ concatMap (nut ps) args
141 | (P (TCon _ _) n _, _) <- unApply fn = []
142 | otherwise = nut ps f ++ nut ps a
143 nut ps (Bind n (Let t v) sc) = nut ps v ++ nut (n:ps) sc
144 nut ps (Proj t _) = nut ps t
145 nut ps (Bind n b sc) = nut (n:ps) sc
146 nut ps _ = []
148 argNames tm = let ns = directUse tm in
149 filter (\x -> x `elem` ns) topargs
151-- Find names which are used directly (i.e. not in a function call) in a term
153directUse :: TT Name -> [Name]
154directUse (P _ n _) = [n]
155directUse (Bind n (Let t v) sc) = nub $ directUse v ++ (directUse sc \\ [n])
156 ++ directUse t
157directUse (Bind n b sc) = nub $ directUse (binderTy b) ++ (directUse sc \\ [n])
158directUse fn@(App f a)
159 | (P Ref (UN pfk) _, [App e w]) <- unApply fn,
160 pfk == txt "prim_fork"
161 = directUse e ++ directUse w -- HACK so that fork works
162 | (P Ref (UN fce) _, [_, _, a]) <- unApply fn,
163 fce == txt "Force"
164 = directUse a -- forcing a value counts as a use
165 | (P Ref n _, args) <- unApply fn = [] -- need to know what n does with them
166 | (P (TCon _ _) n _, args) <- unApply fn = [] -- type constructors not used at runtime
167 | otherwise = nub $ directUse f ++ directUse a
168directUse (Proj x i) = nub $ directUse x
169directUse _ = []
171-- Find all directly used arguments (i.e. used but not in function calls)
173findUsedArgs :: SC -> [Name] -> [Name]
174findUsedArgs sc topargs = nub (findAllUsedArgs sc topargs)
176findAllUsedArgs sc topargs = filter (\x -> x `elem` topargs) (nu' sc) where
177 nu' (Case n alts) = n : concatMap nua alts
178 nu' (ProjCase t alts) = directUse t ++ concatMap nua alts
179 nu' (STerm t) = directUse t
180 nu' _ = []
182 nua (ConCase n i args sc) = nu' sc
183 nua (FnCase n args sc) = nu' sc
184 nua (ConstCase _ sc) = nu' sc
185 nua (SucCase _ sc) = nu' sc
186 nua (DefaultCase sc) = nu' sc
188data Phase = CompileTime | RunTime
189 deriving (Show, Eq)
191-- Generate a simple case tree
192-- Work Right to Left
194simpleCase :: Bool -> Bool -> Bool ->
195 Phase -> FC -> [Type] ->
196 [([Name], Term, Term)] ->
197 TC CaseDef
198simpleCase tc cover reflect phase fc argtys cs
199 = sc' tc cover phase fc (filter (\(_, _, r) ->
200 case r of
201 Impossible -> False
202 _ -> True) cs)
203 where
204 sc' tc cover phase fc []
205 = return $ CaseDef [] (UnmatchedCase "No pattern clauses") []
206 sc' tc cover phase fc cs
207 = let proj = phase == RunTime
208 vnames = fstT (head cs)
209 pats = map (\ (avs, l, r) ->
210 (avs, toPats reflect tc l, (l, r))) cs
211 chkPats = mapM chkAccessible pats in
212 case chkPats of
213 OK pats ->
214 let numargs = length (fst (head pats))
215 ns = take numargs args
216 (ns', ps') = order ns pats
217 (tree, st) = runState
218 (match ns' ps' (defaultCase cover))
219 ([], numargs, [])
220 t = CaseDef ns (prune proj (depatt ns' tree)) (fstT st) in
221 if proj then return (stripLambdas t)
222 else return t
223-- FIXME: This check is not quite right in some cases, and is breaking
224-- perfectly valid code!
225-- if checkSameTypes (lstT st) tree
226-- then return t
227-- else Error (At fc (Msg "Typecase is not allowed"))
228 Error err -> Error (At fc err)
229 where args = map (\i -> sMN i "e") [0..]
230 defaultCase True = STerm Erased
231 defaultCase False = UnmatchedCase "Error"
232 fstT (x, _, _) = x
233 lstT (_, _, x) = x
235 chkAccessible (avs, l, c)
236 | phase == RunTime || reflect = return (l, c)
237 | otherwise = do mapM_ (acc l) avs
238 return (l, c)
240 acc [] n = Error (Inaccessible n)
241 acc (PV x t : xs) n | x == n = OK ()
242 acc (PCon _ _ ps : xs) n = acc (ps ++ xs) n
243 acc (PSuc p : xs) n = acc (p : xs) n
244 acc (_ : xs) n = acc xs n
246-- For each 'Case', make sure every choice is in the same type family,
247-- as directed by the variable type (i.e. there is no implicit type casing
248-- going on).
250checkSameTypes :: [(Name, Type)] -> SC -> Bool
251checkSameTypes tys (Case n alts)
252 = case lookup n tys of
253 Just t -> and (map (checkAlts t) alts)
254 _ -> and (map ((checkSameTypes tys).getSC) alts)
255 where
256 checkAlts t (ConCase n _ _ sc) = isType n t && checkSameTypes tys sc
257 checkAlts (Constant t) (ConstCase c sc) = isConstType c t && checkSameTypes tys sc
258 checkAlts _ (ConstCase c sc) = False
259 checkAlts _ _ = True
261 getSC (ConCase _ _ _ sc) = sc
262 getSC (FnCase _ _ sc) = sc
263 getSC (ConstCase _ sc) = sc
264 getSC (SucCase _ sc) = sc
265 getSC (DefaultCase sc) = sc
266checkSameTypes _ _ = True
268-- FIXME: All we're actually doing here is checking that we haven't arrived
269-- at a specific constructor for a polymorphic argument. I *think* this
270-- is sufficient, but if it turns out not to be, fix it!
271isType n t | (P (TCon _ _) _ _, _) <- unApply t = True
272isType n t | (P Ref _ _, _) <- unApply t = True
273isType n t = False
275isConstType (I _) (AType (ATInt ITNative)) = True
276isConstType (BI _) (AType (ATInt ITBig)) = True
277isConstType (Fl _) (AType ATFloat) = True
278isConstType (Ch _) (AType (ATInt ITChar)) = True
279isConstType (Str _) StrType = True
280isConstType (B8 _) (AType (ATInt _)) = True
281isConstType (B16 _) (AType (ATInt _)) = True
282isConstType (B32 _) (AType (ATInt _)) = True
283isConstType (B64 _) (AType (ATInt _)) = True
284isConstType (B8V _) (AType (ATInt _)) = True
285isConstType (B16V _) (AType (ATInt _)) = True
286isConstType (B32V _) (AType (ATInt _)) = True
287isConstType (B64V _) (AType (ATInt _)) = True
288isConstType _ _ = False
290data Pat = PCon Name Int [Pat]
291 | PConst Const
292 | PV Name Type
293 | PSuc Pat -- special case for n+1 on Integer
294 | PReflected Name [Pat]
295 | PAny
296 | PTyPat -- typecase, not allowed, inspect last
297 deriving Show
299-- If there are repeated variables, take the *last* one (could be name shadowing
300-- in a where clause, so take the most recent).
302toPats :: Bool -> Bool -> Term -> [Pat]
303toPats reflect tc f = reverse (toPat reflect tc (getArgs f)) where
304 getArgs (App f a) = a : getArgs f
305 getArgs _ = []
307toPat :: Bool -> Bool -> [Term] -> [Pat]
308toPat reflect tc tms = evalState (mapM (\x -> toPat' x []) tms) []
309 where
310 toPat' (P (DCon t a) n _) args = do args' <- mapM (\x -> toPat' x []) args
311 return $ PCon n t args'
312 -- n + 1
313 toPat' (P _ (UN pabi) _)
314 [p, Constant (BI 1)] | pabi == txt "prim__addBigInt"
315 = do p' <- toPat' p []
316 return $ PSuc p'
317 -- Typecase
318-- toPat' (P (TCon t a) n _) args | tc
319-- = do args' <- mapM (\x -> toPat' x []) args
320-- return $ PCon n t args'
321-- toPat' (Constant (AType (ATInt ITNative))) []
322-- | tc = return $ PCon (UN "Int") 1 []
323-- toPat' (Constant (AType ATFloat)) [] | tc = return $ PCon (UN "Float") 2 []
324-- toPat' (Constant (AType (ATInt ITChar))) [] | tc = return $ PCon (UN "Char") 3 []
325-- toPat' (Constant StrType) [] | tc = return $ PCon (UN "String") 4 []
326-- toPat' (Constant PtrType) [] | tc = return $ PCon (UN "Ptr") 5 []
327-- toPat' (Constant (AType (ATInt ITBig))) []
328-- | tc = return $ PCon (UN "Integer") 6 []
329-- toPat' (Constant (AType (ATInt (ITFixed n)))) []
330-- | tc = return $ PCon (UN (fixedN n)) (7 + fromEnum n) [] -- 7-10 inclusive
331 toPat' (P Bound n ty) [] = -- trace (show (n, ty)) $
332 do ns <- get
333 if n `elem` ns
334 then return PAny
335 else do put (n : ns)
336 return (PV n ty)
337 toPat' (App f a) args = toPat' f (a : args)
338 toPat' (Constant (AType _)) [] = return PTyPat
339 toPat' (Constant StrType) [] = return PTyPat
340 toPat' (Constant PtrType) [] = return PTyPat
341 toPat' (Constant VoidType) [] = return PTyPat
342 toPat' (Constant x) [] = return $ PConst x
343 toPat' (Bind n (Pi t) sc) [] | reflect && noOccurrence n sc
344 = do t' <- toPat' t []
345 sc' <- toPat' sc []
346 return $ PReflected (sUN "->") (t':sc':[])
347 toPat' (P _ n _) args | reflect
348 = do args' <- mapM (\x -> toPat' x []) args
349 return $ PReflected n args'
350 toPat' t _ = return PAny
352 fixedN IT8 = "Bits8"
353 fixedN IT16 = "Bits16"
354 fixedN IT32 = "Bits32"
355 fixedN IT64 = "Bits64"
358data Partition = Cons [Clause]
359 | Vars [Clause]
360 deriving Show
362isVarPat (PV _ _ : ps , _) = True
363isVarPat (PAny : ps , _) = True
364isVarPat (PTyPat : ps , _) = True
365isVarPat _ = False
367isConPat (PCon _ _ _ : ps, _) = True
368isConPat (PReflected _ _ : ps, _) = True
369isConPat (PSuc _ : ps, _) = True
370isConPat (PConst _ : ps, _) = True
371isConPat _ = False
373partition :: [Clause] -> [Partition]
374partition [] = []
375partition ms@(m : _)
376 | isVarPat m = let (vars, rest) = span isVarPat ms in
377 Vars vars : partition rest
378 | isConPat m = let (cons, rest) = span isConPat ms in
379 Cons cons : partition rest
380partition xs = error $ "Partition " ++ show xs
382-- reorder the patterns so that the one with most distinct names
383-- comes next. Take rightmost first, otherwise (i.e. pick value rather
384-- than dependency)
386order :: [Name] -> [Clause] -> ([Name], [Clause])
387order [] cs = ([], cs)
388order ns [] = (ns, [])
389order ns cs = let patnames = transpose (map (zip ns) (map fst cs))
390 pats' = transpose (sortBy moreDistinct (reverse patnames)) in
391 (getNOrder pats', zipWith rebuild pats' cs)
392 where
393 getNOrder [] = error $ "Failed order on " ++ show (ns, cs)
394 getNOrder (c : _) = map fst c
396 rebuild patnames clause = (map snd patnames, snd clause)
398 moreDistinct xs ys = compare (numNames [] (map snd ys))
399 (numNames [] (map snd xs))
401 numNames xs (PCon n _ _ : ps)
402 | not (Left n `elem` xs) = numNames (Left n : xs) ps
403 numNames xs (PConst c : ps)
404 | not (Right c `elem` xs) = numNames (Right c : xs) ps
405 numNames xs (_ : ps) = numNames xs ps
406 numNames xs [] = length xs
408match :: [Name] -> [Clause] -> SC -- error case
409 -> State CS SC
410match [] (([], ret) : xs) err
411 = do (ts, v, ntys) <- get
412 put (ts ++ (map (fst.snd) xs), v, ntys)
413 case snd ret of
414 Impossible -> return ImpossibleCase
415 tm -> return $ STerm tm -- run out of arguments
416match vs cs err = do let ps = partition cs
417 mixture vs ps err
419mixture :: [Name] -> [Partition] -> SC -> State CS SC
420mixture vs [] err = return err
421mixture vs (Cons ms : ps) err = do fallthrough <- mixture vs ps err
422 conRule vs ms fallthrough
423mixture vs (Vars ms : ps) err = do fallthrough <- mixture vs ps err
424 varRule vs ms fallthrough
426data ConType = CName Name Int -- named constructor
427 | CFn Name -- reflected function name
428 | CSuc -- n+1
429 | CConst Const -- constant, not implemented yet
430 deriving (Show, Eq)
432data Group = ConGroup ConType -- Constructor
433 [([Pat], Clause)] -- arguments and rest of alternative
434 deriving Show
436conRule :: [Name] -> [Clause] -> SC -> State CS SC
437conRule (v:vs) cs err = do groups <- groupCons cs
438 caseGroups (v:vs) groups err
440caseGroups :: [Name] -> [Group] -> SC -> State CS SC
441caseGroups (v:vs) gs err = do g <- altGroups gs
442 return $ Case v (sort g)
443 where
444 altGroups [] = return [DefaultCase err]
445 altGroups (ConGroup (CName n i) args : cs)
446 = do g <- altGroup n i args
447 rest <- altGroups cs
448 return (g : rest)
449 altGroups (ConGroup (CFn n) args : cs)
450 = do g <- altFnGroup n args
451 rest <- altGroups cs
452 return (g : rest)
453 altGroups (ConGroup CSuc args : cs)
454 = do g <- altSucGroup args
455 rest <- altGroups cs
456 return (g : rest)
457 altGroups (ConGroup (CConst c) args : cs)
458 = do g <- altConstGroup c args
459 rest <- altGroups cs
460 return (g : rest)
462 altGroup n i gs = do (newArgs, nextCs) <- argsToAlt gs
463 matchCs <- match (newArgs ++ vs) nextCs err
464 return $ ConCase n i newArgs matchCs
465 altFnGroup n gs = do (newArgs, nextCs) <- argsToAlt gs
466 matchCs <- match (newArgs ++ vs) nextCs err
467 return $ FnCase n newArgs matchCs
468 altSucGroup gs = do ([newArg], nextCs) <- argsToAlt gs
469 matchCs <- match (newArg:vs) nextCs err
470 return $ SucCase newArg matchCs
471 altConstGroup n gs = do (_, nextCs) <- argsToAlt gs
472 matchCs <- match vs nextCs err
473 return $ ConstCase n matchCs
475argsToAlt :: [([Pat], Clause)] -> State CS ([Name], [Clause])
476argsToAlt [] = return ([], [])
477argsToAlt rs@((r, m) : rest)
478 = do newArgs <- getNewVars r
479 return (newArgs, addRs rs)
480 where
481 getNewVars [] = return []
482 getNewVars ((PV n t) : ns) = do v <- getVar "e"
483 (cs, i, ntys) <- get
484 put (cs, i, (v, t) : ntys)
485 nsv <- getNewVars ns
486 return (v : nsv)
487 getNewVars (PAny : ns) = do v <- getVar "i"
488 nsv <- getNewVars ns
489 return (v : nsv)
490 getNewVars (PTyPat : ns) = do v <- getVar "t"
491 nsv <- getNewVars ns
492 return (v : nsv)
493 getNewVars (_ : ns) = do v <- getVar "e"
494 nsv <- getNewVars ns
495 return (v : nsv)
496 addRs [] = []
497 addRs ((r, (ps, res)) : rs) = ((r++ps, res) : addRs rs)
499 uniq i (UN n) = MN i n
500 uniq i n = n
502getVar :: String -> State CS Name
503getVar b = do (t, v, ntys) <- get; put (t, v+1, ntys); return (sMN v b)
505groupCons :: [Clause] -> State CS [Group]
506groupCons cs = gc [] cs
507 where
508 gc acc [] = return acc
509 gc acc ((p : ps, res) : cs) =
510 do acc' <- addGroup p ps res acc
511 gc acc' cs
512 addGroup p ps res acc = case p of
513 PCon con i args -> return $ addg (CName con i) args (ps, res) acc
514 PConst cval -> return $ addConG cval (ps, res) acc
515 PSuc n -> return $ addg CSuc [n] (ps, res) acc
516 PReflected fn args -> return $ addg (CFn fn) args (ps, res) acc
517 pat -> fail $ show pat ++ " is not a constructor or constant (can't happen)"
519 addg c conargs res []
520 = [ConGroup c [(conargs, res)]]
521 addg c conargs res (g@(ConGroup c' cs):gs)
522 | c == c' = ConGroup c (cs ++ [(conargs, res)]) : gs
523 | otherwise = g : addg c conargs res gs
525 addConG con res [] = [ConGroup (CConst con) [([], res)]]
526 addConG con res (g@(ConGroup (CConst n) cs) : gs)
527 | con == n = ConGroup (CConst n) (cs ++ [([], res)]) : gs
528-- | otherwise = g : addConG con res gs
529 addConG con res (g : gs) = g : addConG con res gs
531varRule :: [Name] -> [Clause] -> SC -> State CS SC
532varRule (v : vs) alts err =
533 do alts' <- mapM (repVar v) alts
534 match vs alts' err
535 where
536 repVar v (PV p ty : ps , (lhs, res))
537 = do (cs, i, ntys) <- get
538 put (cs, i, (v, ty) : ntys)
539 return (ps, (lhs, subst p (P Bound v ty) res))
540 repVar v (PAny : ps , res) = return (ps, res)
541 repVar v (PTyPat : ps , res) = return (ps, res)
543-- fix: case e of S k -> f (S k) ==> case e of S k -> f e
545depatt :: [Name] -> SC -> SC
546depatt ns tm = dp [] tm
547 where
548 dp ms (STerm tm) = STerm (applyMaps ms tm)
549 dp ms (Case x alts) = Case x (map (dpa ms x) alts)
550 dp ms sc = sc
552 dpa ms x (ConCase n i args sc)
553 = ConCase n i args (dp ((x, (n, args)) : ms) sc)
554 dpa ms x (FnCase n args sc)
555 = FnCase n args (dp ((x, (n, args)) : ms) sc)
556 dpa ms x (ConstCase c sc) = ConstCase c (dp ms sc)
557 dpa ms x (SucCase n sc) = SucCase n (dp ms sc)
558 dpa ms x (DefaultCase sc) = DefaultCase (dp ms sc)
560 applyMaps ms f@(App _ _)
561 | (P nt cn pty, args) <- unApply f
562 = let args' = map (applyMaps ms) args in
563 applyMap ms nt cn pty args'
564 where
565 applyMap [] nt cn pty args' = mkApp (P nt cn pty) args'
566 applyMap ((x, (n, args)) : ms) nt cn pty args'
567 | and ((length args == length args') :
568 (n == cn) : zipWith same args args') = P Ref x Erased
569 | otherwise = applyMap ms nt cn pty args'
570 same n (P _ n' _) = n == n'
571 same _ _ = False
573 applyMaps ms (App f a) = App (applyMaps ms f) (applyMaps ms a)
574 applyMaps ms t = t
576-- FIXME: Do this for SucCase too
577prune :: Bool -- ^ Convert single branches to projections (only useful at runtime)
578 -> SC -> SC
579prune proj (Case n alts)
580 = let alts' = filter notErased (map pruneAlt alts) in
581 case alts' of
582 [] -> ImpossibleCase
583 as@(ConCase (UN delay) i [arg] sc : _)
584 | delay == txt "Delay"
585 -> if proj then mkForce n arg sc
586 else Case n as
587 as@[ConCase cn i args sc] -> if proj then mkProj n 0 args sc
588 else Case n as
589 as@[SucCase cn sc] -> if proj then mkProj n (-1) [cn] sc
590 else Case n as
591 as@[ConstCase _ sc] -> prune proj sc
592 -- Bit of a hack here! The default case will always be 0, make sure
593 -- it gets caught first.
594 [s@(SucCase _ _), DefaultCase dc]
595 -> Case n [ConstCase (BI 0) dc, s]
596 as -> Case n as
597 where pruneAlt (ConCase cn i ns sc) = ConCase cn i ns (prune proj sc)
598 pruneAlt (FnCase cn ns sc) = FnCase cn ns (prune proj sc)
599 pruneAlt (ConstCase c sc) = ConstCase c (prune proj sc)
600 pruneAlt (SucCase n sc) = SucCase n (prune proj sc)
601 pruneAlt (DefaultCase sc) = DefaultCase (prune proj sc)
603 notErased (DefaultCase (STerm Erased)) = False
604 notErased (DefaultCase ImpossibleCase) = False
605 notErased _ = True
607 mkForce n arg (Case x alts)
608 | x == arg = ProjCase (forceArg n)
609 (map (mkForceAlt n arg) alts)
610 | otherwise = Case x (map (mkForceAlt n arg) alts)
611 mkForce n arg (ProjCase t alts)
612 = ProjCase (forceTm n arg t) (map (mkForceAlt n arg) alts)
613 mkForce n arg (STerm t) = STerm (forceTm n arg t)
614 mkForce n arg c = c
616 mkForceAlt n arg (ConCase cn t args rhs)
617 = ConCase cn t args (mkForce n arg rhs)
618 mkForceAlt n arg (FnCase cn args rhs)
619 = FnCase cn args (mkForce n arg rhs)
620 mkForceAlt n arg (ConstCase t rhs)
621 = ConstCase t (mkForce n arg rhs)
622 mkForceAlt n arg (SucCase sn rhs)
623 = SucCase sn (mkForce n arg rhs)
624 mkForceAlt n arg (DefaultCase rhs)
625 = DefaultCase (mkForce n arg rhs)
627 forceTm n arg t = subst arg (forceArg n) t
629 forceArg n = App (App (App (P Ref (sUN "Force") Erased) Erased) Erased)
630 (P Bound n Erased)
632 mkProj n i [] sc = prune proj sc
633 mkProj n i (x : xs) sc = mkProj n (i + 1) xs (projRep x n i sc)
635 -- Change every 'n' in sc to 'n-1'
636-- mkProjS n cn sc = prune proj (fmap projn sc) where
637-- projn pn@(P _ n' _)
638-- | cn == n' = App (App (P Ref (UN "prim__subBigInt") Erased)
639-- (P Bound n Erased)) (Constant (BI 1))
640-- projn t = t
642 projRep :: Name -> Name -> Int -> SC -> SC
643 projRep arg n i (Case x alts)
644 | x == arg = ProjCase (Proj (P Bound n Erased) i)
645 (map (projRepAlt arg n i) alts)
646 | otherwise = Case x (map (projRepAlt arg n i) alts)
647 projRep arg n i (ProjCase t alts)
648 = ProjCase (projRepTm arg n i t) (map (projRepAlt arg n i) alts)
649 projRep arg n i (STerm t) = STerm (projRepTm arg n i t)
650 projRep arg n i c = c -- unmatched
652 projRepAlt arg n i (ConCase cn t args rhs)
653 = ConCase cn t args (projRep arg n i rhs)
654 projRepAlt arg n i (FnCase cn args rhs)
655 = FnCase cn args (projRep arg n i rhs)
656 projRepAlt arg n i (ConstCase t rhs)
657 = ConstCase t (projRep arg n i rhs)
658 projRepAlt arg n i (SucCase sn rhs)
659 = SucCase sn (projRep arg n i rhs)
660 projRepAlt arg n i (DefaultCase rhs)
661 = DefaultCase (projRep arg n i rhs)
663 projRepTm arg n i t = subst arg (Proj (P Bound n Erased) i) t
665prune _ t = t
667stripLambdas :: CaseDef -> CaseDef
668stripLambdas (CaseDef ns (STerm (Bind x (Lam _) sc)) tm)
669 = stripLambdas (CaseDef (ns ++ [x]) (STerm (instantiate (P Bound x Erased) sc)) tm)
670stripLambdas x = x