on 9302221 help sign in
Idris-dev/src/Idris/Core/CaseTree.hs
755 lines 30 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,
6 substSC, substAlt, mkForce) where
8import Idris.Core.TT
10import Control.Monad.State
11import Data.Maybe
12import Data.List hiding (partition)
13import qualified Data.List(partition)
14import Debug.Trace
16data CaseDef = CaseDef [Name] !SC [Term]
17 deriving Show
19-- Note: The case-tree elaborator only produces (Case n alts)-cases;
20-- in other words, it never inspects anything else than variables.
21--
22-- ProjCase is a special powerful case construct that allows inspection
23-- of compound terms. Occurrences of ProjCase arise no earlier than
24-- in the function `prune` as a means of optimisation
25-- of already built case trees.
26--
27-- While the intermediate representation (follows in the pipeline)
28-- allows casing on arbitrary terms, here we choose to maintain the distinction
29-- in order to allow for better optimisation opportunities.
30--
31data SC' t = Case Name [CaseAlt' t] -- ^ invariant: lowest tags first
32 | ProjCase t [CaseAlt' t] -- ^ special case for projections/thunk-forcing before inspection
33 | STerm !t
34 | UnmatchedCase String -- ^ error message
35 | ImpossibleCase -- ^ already checked to be impossible
36 deriving (Eq, Ord, Functor)
37{-!
38deriving instance Binary SC'
39deriving instance NFData SC'
40!-}
42type SC = SC' Term
44data CaseAlt' t = ConCase Name Int [Name] !(SC' t)
45 | FnCase Name [Name] !(SC' t) -- ^ reflection function
46 | ConstCase Const !(SC' t)
47 | SucCase Name !(SC' t)
48 | DefaultCase !(SC' t)
49 deriving (Show, Eq, Ord, Functor)
50{-!
51deriving instance Binary CaseAlt'
52deriving instance NFData CaseAlt'
53!-}
55type CaseAlt = CaseAlt' Term
57instance Show t => Show (SC' t) where
58 show sc = show' 1 sc
59 where
60 show' i (Case n alts) = "case " ++ show n ++ " of\n" ++ indent i ++
61 showSep ("\n" ++ indent i) (map (showA i) alts)
62 show' i (ProjCase tm alts) = "case " ++ show tm ++ " of " ++
63 showSep ("\n" ++ indent i) (map (showA i) alts)
64 show' i (STerm tm) = show tm
65 show' i (UnmatchedCase str) = "error " ++ show str
66 show' i ImpossibleCase = "impossible"
68 indent i = concat $ take i (repeat " ")
70 showA i (ConCase n t args sc)
71 = show n ++ "(" ++ showSep (", ") (map show args) ++ ") => "
72 ++ show' (i+1) sc
73 showA i (FnCase n args sc)
74 = "FN " ++ show n ++ "(" ++ showSep (", ") (map show args) ++ ") => "
75 ++ show' (i+1) sc
76 showA i (ConstCase t sc)
77 = show t ++ " => " ++ show' (i+1) sc
78 showA i (SucCase n sc)
79 = show n ++ "+1 => " ++ show' (i+1) sc
80 showA i (DefaultCase sc)
81 = "_ => " ++ show' (i+1) sc
84type CaseTree = SC
85type Clause = ([Pat], (Term, Term))
86type CS = ([Term], Int, [(Name, Type)])
88instance TermSize SC where
89 termsize n (Case n' as) = termsize n as
90 termsize n (ProjCase n' as) = termsize n as
91 termsize n (STerm t) = termsize n t
92 termsize n _ = 1
94instance TermSize CaseAlt where
95 termsize n (ConCase _ _ _ s) = termsize n s
96 termsize n (FnCase _ _ s) = termsize n s
97 termsize n (ConstCase _ s) = termsize n s
98 termsize n (SucCase _ s) = termsize n s
99 termsize n (DefaultCase s) = termsize n s
101-- simple terms can be inlined trivially - good for primitives in particular
102-- To avoid duplicating work, don't inline something which uses one
103-- of its arguments in more than one place
105small :: Name -> [Name] -> SC -> Bool
106small n args t = let as = findAllUsedArgs t args in
107 length as == length (nub as) &&
108 termsize n t < 10
110namesUsed :: SC -> [Name]
111namesUsed sc = nub $ nu' [] sc where
112 nu' ps (Case n alts) = nub (concatMap (nua ps) alts) \\ [n]
113 nu' ps (ProjCase t alts) = nub $ nut ps t ++ concatMap (nua ps) alts
114 nu' ps (STerm t) = nub $ nut ps t
115 nu' ps _ = []
117 nua ps (ConCase n i args sc) = nub (nu' (ps ++ args) sc) \\ args
118 nua ps (FnCase n args sc) = nub (nu' (ps ++ args) sc) \\ args
119 nua ps (ConstCase _ sc) = nu' ps sc
120 nua ps (SucCase _ sc) = nu' ps sc
121 nua ps (DefaultCase sc) = nu' ps sc
123 nut ps (P _ n _) | n `elem` ps = []
124 | otherwise = [n]
125 nut ps (App f a) = nut ps f ++ nut ps a
126 nut ps (Proj t _) = nut ps t
127 nut ps (Bind n (Let t v) sc) = nut ps v ++ nut (n:ps) sc
128 nut ps (Bind n b sc) = nut (n:ps) sc
129 nut ps _ = []
131-- Return all called functions, and which arguments are used in each argument position
132-- for the call, in order to help reduce compilation time, and trace all unused
133-- arguments
135findCalls :: SC -> [Name] -> [(Name, [[Name]])]
136findCalls sc topargs = nub $ nu' topargs sc where
137 nu' ps (Case n alts) = nub (concatMap (nua (n : ps)) alts)
138 nu' ps (ProjCase t alts) = nub $ nut ps t ++ concatMap (nua ps) alts
139 nu' ps (STerm t) = nub $ nut ps t
140 nu' ps _ = []
142 nua ps (ConCase n i args sc) = nub (nu' (ps ++ args) sc)
143 nua ps (FnCase n args sc) = nub (nu' (ps ++ args) sc)
144 nua ps (ConstCase _ sc) = nu' ps sc
145 nua ps (SucCase _ sc) = nu' ps sc
146 nua ps (DefaultCase sc) = nu' ps sc
148 nut ps (P Ref n _) | n `elem` ps = []
149 | otherwise = [(n, [])] -- tmp
150 nut ps fn@(App f a)
151 | (P Ref n _, args) <- unApply fn
152 = if n `elem` ps then nut ps f ++ nut ps a
153 else [(n, map argNames args)] ++ concatMap (nut ps) args
154 | (P (TCon _ _) n _, _) <- unApply fn = []
155 | otherwise = nut ps f ++ nut ps a
156 nut ps (Bind n (Let t v) sc) = nut ps v ++ nut (n:ps) sc
157 nut ps (Proj t _) = nut ps t
158 nut ps (Bind n b sc) = nut (n:ps) sc
159 nut ps _ = []
161 argNames tm = let ns = directUse tm in
162 filter (\x -> x `elem` ns) topargs
164-- Find names which are used directly (i.e. not in a function call) in a term
166directUse :: TT Name -> [Name]
167directUse (P _ n _) = [n]
168directUse (Bind n (Let t v) sc) = nub $ directUse v ++ (directUse sc \\ [n])
169 ++ directUse t
170directUse (Bind n b sc) = nub $ directUse (binderTy b) ++ (directUse sc \\ [n])
171directUse fn@(App f a)
172 | (P Ref (UN pfk) _, [App e w]) <- unApply fn,
173 pfk == txt "prim_fork"
174 = directUse e ++ directUse w -- HACK so that fork works
175 | (P Ref (UN fce) _, [_, _, a]) <- unApply fn,
176 fce == txt "Force"
177 = directUse a -- forcing a value counts as a use
178 | (P Ref n _, args) <- unApply fn = [] -- need to know what n does with them
179 | (P (TCon _ _) n _, args) <- unApply fn = [] -- type constructors not used at runtime
180 | otherwise = nub $ directUse f ++ directUse a
181directUse (Proj x i) = nub $ directUse x
182directUse _ = []
184-- Find all directly used arguments (i.e. used but not in function calls)
186findUsedArgs :: SC -> [Name] -> [Name]
187findUsedArgs sc topargs = nub (findAllUsedArgs sc topargs)
189findAllUsedArgs sc topargs = filter (\x -> x `elem` topargs) (nu' sc) where
190 nu' (Case n alts) = n : concatMap nua alts
191 nu' (ProjCase t alts) = directUse t ++ concatMap nua alts
192 nu' (STerm t) = directUse t
193 nu' _ = []
195 nua (ConCase n i args sc) = nu' sc
196 nua (FnCase n args sc) = nu' sc
197 nua (ConstCase _ sc) = nu' sc
198 nua (SucCase _ sc) = nu' sc
199 nua (DefaultCase sc) = nu' sc
201-- Return whether name is used anywhere in a case tree
202isUsed :: SC -> Name -> Bool
203isUsed sc n = used sc where
205 used (Case n' alts) = n == n' || or (map usedA alts)
206 used (ProjCase t alts) = n `elem` freeNames t || or (map usedA alts)
207 used (STerm t) = n `elem` freeNames t
208 used _ = False
210 usedA (ConCase _ _ args sc) = used sc
211 usedA (FnCase _ args sc) = used sc
212 usedA (ConstCase _ sc) = used sc
213 usedA (SucCase _ sc) = used sc
214 usedA (DefaultCase sc) = used sc
217data Phase = CompileTime | RunTime
218 deriving (Show, Eq)
220-- Generate a simple case tree
221-- Work Right to Left
223simpleCase :: Bool -> Bool -> Bool ->
224 Phase -> FC -> [Int] -> [Type] ->
225 [([Name], Term, Term)] ->
226 TC CaseDef
227simpleCase tc cover reflect phase fc inacc argtys cs
228 = sc' tc cover phase fc (filter (\(_, _, r) ->
229 case r of
230 Impossible -> False
231 _ -> True) cs)
232 where
233 sc' tc cover phase fc []
234 = return $ CaseDef [] (UnmatchedCase "No pattern clauses") []
235 sc' tc cover phase fc cs
236 = let proj = phase == RunTime
237 vnames = fstT (head cs)
238 pats = map (\ (avs, l, r) ->
239 (avs, toPats reflect tc l, (l, r))) cs
240 chkPats = mapM chkAccessible pats in
241 case chkPats of
242 OK pats ->
243 let numargs = length (fst (head pats))
244 ns = take numargs args
245 (ns', ps') = order [(n, i `elem` inacc) | (i,n) <- zip [0..] ns] pats
246 (tree, st) = runState
247 (match ns' ps' (defaultCase cover))
248 ([], numargs, [])
249 t = CaseDef ns (prune proj (depatt ns' tree)) (fstT st) in
250 if proj then return (stripLambdas t)
251 else return t
252-- FIXME: This check is not quite right in some cases, and is breaking
253-- perfectly valid code!
254-- if checkSameTypes (lstT st) tree
255-- then return t
256-- else Error (At fc (Msg "Typecase is not allowed"))
257 Error err -> Error (At fc err)
258 where args = map (\i -> sMN i "e") [0..]
259 defaultCase True = STerm Erased
260 defaultCase False = UnmatchedCase "Error"
261 fstT (x, _, _) = x
262 lstT (_, _, x) = x
264 chkAccessible (avs, l, c)
265 | phase == RunTime || reflect = return (l, c)
266 | otherwise = do mapM_ (acc l) avs
267 return (l, c)
269 acc [] n = Error (Inaccessible n)
270 acc (PV x t : xs) n | x == n = OK ()
271 acc (PCon _ _ ps : xs) n = acc (ps ++ xs) n
272 acc (PSuc p : xs) n = acc (p : xs) n
273 acc (_ : xs) n = acc xs n
275-- For each 'Case', make sure every choice is in the same type family,
276-- as directed by the variable type (i.e. there is no implicit type casing
277-- going on).
279checkSameTypes :: [(Name, Type)] -> SC -> Bool
280checkSameTypes tys (Case n alts)
281 = case lookup n tys of
282 Just t -> and (map (checkAlts t) alts)
283 _ -> and (map ((checkSameTypes tys).getSC) alts)
284 where
285 checkAlts t (ConCase n _ _ sc) = isType n t && checkSameTypes tys sc
286 checkAlts (Constant t) (ConstCase c sc) = isConstType c t && checkSameTypes tys sc
287 checkAlts _ (ConstCase c sc) = False
288 checkAlts _ _ = True
290 getSC (ConCase _ _ _ sc) = sc
291 getSC (FnCase _ _ sc) = sc
292 getSC (ConstCase _ sc) = sc
293 getSC (SucCase _ sc) = sc
294 getSC (DefaultCase sc) = sc
295checkSameTypes _ _ = True
297-- FIXME: All we're actually doing here is checking that we haven't arrived
298-- at a specific constructor for a polymorphic argument. I *think* this
299-- is sufficient, but if it turns out not to be, fix it!
300isType n t | (P (TCon _ _) _ _, _) <- unApply t = True
301isType n t | (P Ref _ _, _) <- unApply t = True
302isType n t = False
304isConstType (I _) (AType (ATInt ITNative)) = True
305isConstType (BI _) (AType (ATInt ITBig)) = True
306isConstType (Fl _) (AType ATFloat) = True
307isConstType (Ch _) (AType (ATInt ITChar)) = True
308isConstType (Str _) StrType = True
309isConstType (B8 _) (AType (ATInt _)) = True
310isConstType (B16 _) (AType (ATInt _)) = True
311isConstType (B32 _) (AType (ATInt _)) = True
312isConstType (B64 _) (AType (ATInt _)) = True
313isConstType (B8V _) (AType (ATInt _)) = True
314isConstType (B16V _) (AType (ATInt _)) = True
315isConstType (B32V _) (AType (ATInt _)) = True
316isConstType (B64V _) (AType (ATInt _)) = True
317isConstType _ _ = False
319data Pat = PCon Name Int [Pat]
320 | PConst Const
321 | PV Name Type
322 | PSuc Pat -- special case for n+1 on Integer
323 | PReflected Name [Pat]
324 | PAny
325 | PTyPat -- typecase, not allowed, inspect last
326 deriving Show
328-- If there are repeated variables, take the *last* one (could be name shadowing
329-- in a where clause, so take the most recent).
331toPats :: Bool -> Bool -> Term -> [Pat]
332toPats reflect tc f = reverse (toPat reflect tc (getArgs f)) where
333 getArgs (App f a) = a : getArgs f
334 getArgs _ = []
336toPat :: Bool -> Bool -> [Term] -> [Pat]
337toPat reflect tc tms = evalState (mapM (\x -> toPat' x []) tms) []
338 where
339 toPat' (P (DCon t a) n _) args = do args' <- mapM (\x -> toPat' x []) args
340 return $ PCon n t args'
341 -- n + 1
342 toPat' (P _ (UN pabi) _)
343 [p, Constant (BI 1)] | pabi == txt "prim__addBigInt"
344 = do p' <- toPat' p []
345 return $ PSuc p'
346 -- Typecase
347-- toPat' (P (TCon t a) n _) args | tc
348-- = do args' <- mapM (\x -> toPat' x []) args
349-- return $ PCon n t args'
350-- toPat' (Constant (AType (ATInt ITNative))) []
351-- | tc = return $ PCon (UN "Int") 1 []
352-- toPat' (Constant (AType ATFloat)) [] | tc = return $ PCon (UN "Float") 2 []
353-- toPat' (Constant (AType (ATInt ITChar))) [] | tc = return $ PCon (UN "Char") 3 []
354-- toPat' (Constant StrType) [] | tc = return $ PCon (UN "String") 4 []
355-- toPat' (Constant PtrType) [] | tc = return $ PCon (UN "Ptr") 5 []
356-- toPat' (Constant (AType (ATInt ITBig))) []
357-- | tc = return $ PCon (UN "Integer") 6 []
358-- toPat' (Constant (AType (ATInt (ITFixed n)))) []
359-- | tc = return $ PCon (UN (fixedN n)) (7 + fromEnum n) [] -- 7-10 inclusive
360 toPat' (P Bound n ty) [] = -- trace (show (n, ty)) $
361 do ns <- get
362 if n `elem` ns
363 then return PAny
364 else do put (n : ns)
365 return (PV n ty)
366 toPat' (App f a) args = toPat' f (a : args)
367 toPat' (Constant (AType _)) [] = return PTyPat
368 toPat' (Constant StrType) [] = return PTyPat
369 toPat' (Constant PtrType) [] = return PTyPat
370 toPat' (Constant VoidType) [] = return PTyPat
371 toPat' (Constant x) [] = return $ PConst x
372 toPat' (Bind n (Pi t) sc) [] | reflect && noOccurrence n sc
373 = do t' <- toPat' t []
374 sc' <- toPat' sc []
375 return $ PReflected (sUN "->") (t':sc':[])
376 toPat' (P _ n _) args | reflect
377 = do args' <- mapM (\x -> toPat' x []) args
378 return $ PReflected n args'
379 toPat' t _ = return PAny
381 fixedN IT8 = "Bits8"
382 fixedN IT16 = "Bits16"
383 fixedN IT32 = "Bits32"
384 fixedN IT64 = "Bits64"
387data Partition = Cons [Clause]
388 | Vars [Clause]
389 deriving Show
391isVarPat (PV _ _ : ps , _) = True
392isVarPat (PAny : ps , _) = True
393isVarPat (PTyPat : ps , _) = True
394isVarPat _ = False
396isConPat (PCon _ _ _ : ps, _) = True
397isConPat (PReflected _ _ : ps, _) = True
398isConPat (PSuc _ : ps, _) = True
399isConPat (PConst _ : ps, _) = True
400isConPat _ = False
402partition :: [Clause] -> [Partition]
403partition [] = []
404partition ms@(m : _)
405 | isVarPat m = let (vars, rest) = span isVarPat ms in
406 Vars vars : partition rest
407 | isConPat m = let (cons, rest) = span isConPat ms in
408 Cons cons : partition rest
409partition xs = error $ "Partition " ++ show xs
411-- reorder the patterns so that the one with most distinct names
412-- comes next. Take rightmost first, otherwise (i.e. pick value rather
413-- than dependency)
414--
415-- The first argument means [(Name, IsInaccessible)].
417order :: [(Name, Bool)] -> [Clause] -> ([Name], [Clause])
418order [] cs = ([], cs)
419order ns' [] = (map fst ns', [])
420order ns' cs = let patnames = transpose (map (zip ns') (map fst cs))
421 -- only sort the arguments where there is no clash in
422 -- constructor tags between families, and no constructor/constant
423 -- clash, because otherwise we can't reliable make the
424 -- case distinction on evaluation
425 (patnames_ord, patnames_rest)
426 = Data.List.partition (noClash . map snd) patnames
427 -- note: sortBy . reverse is not nonsense because sortBy is stable
428 pats' = transpose (sortBy moreDistinct (reverse patnames_ord)
429 ++ patnames_rest) in
430 (getNOrder pats', zipWith rebuild pats' cs)
431 where
432 getNOrder [] = error $ "Failed order on " ++ show (map fst ns', cs)
433 getNOrder (c : _) = map (fst . fst) c
435 rebuild patnames clause = (map snd patnames, snd clause)
437 noClash [] = True
438 noClash (p : ps) = not (any (clashPat p) ps) && noClash ps
440 clashPat (PCon _ _ _) (PConst _) = True
441 clashPat (PConst _) (PCon _ _ _) = True
442 clashPat (PCon _ _ _) (PSuc _) = True
443 clashPat (PSuc _) (PCon _ _ _) = True
444 clashPat (PCon n i _) (PCon n' i' _) | i == i' = n /= n'
445 clashPat _ _ = False
447 -- this compares (+isInaccessible, -numberOfCases)
448 moreDistinct xs ys = compare (snd . fst . head $ xs, numNames [] (map snd ys))
449 (snd . fst . head $ ys, numNames [] (map snd xs))
451 numNames xs (PCon n _ _ : ps)
452 | not (Left n `elem` xs) = numNames (Left n : xs) ps
453 numNames xs (PConst c : ps)
454 | not (Right c `elem` xs) = numNames (Right c : xs) ps
455 numNames xs (_ : ps) = numNames xs ps
456 numNames xs [] = length xs
458match :: [Name] -> [Clause] -> SC -- error case
459 -> State CS SC
460match [] (([], ret) : xs) err
461 = do (ts, v, ntys) <- get
462 put (ts ++ (map (fst.snd) xs), v, ntys)
463 case snd ret of
464 Impossible -> return ImpossibleCase
465 tm -> return $ STerm tm -- run out of arguments
466match vs cs err = do let ps = partition cs
467 mixture vs ps err
469mixture :: [Name] -> [Partition] -> SC -> State CS SC
470mixture vs [] err = return err
471mixture vs (Cons ms : ps) err = do fallthrough <- mixture vs ps err
472 conRule vs ms fallthrough
473mixture vs (Vars ms : ps) err = do fallthrough <- mixture vs ps err
474 varRule vs ms fallthrough
476data ConType = CName Name Int -- named constructor
477 | CFn Name -- reflected function name
478 | CSuc -- n+1
479 | CConst Const -- constant, not implemented yet
480 deriving (Show, Eq)
482data Group = ConGroup ConType -- Constructor
483 [([Pat], Clause)] -- arguments and rest of alternative
484 deriving Show
486conRule :: [Name] -> [Clause] -> SC -> State CS SC
487conRule (v:vs) cs err = do groups <- groupCons cs
488 caseGroups (v:vs) groups err
490caseGroups :: [Name] -> [Group] -> SC -> State CS SC
491caseGroups (v:vs) gs err = do g <- altGroups gs
492 return $ Case v (sort g)
493 where
494 altGroups [] = return [DefaultCase err]
495 altGroups (ConGroup (CName n i) args : cs)
496 = do g <- altGroup n i args
497 rest <- altGroups cs
498 return (g : rest)
499 altGroups (ConGroup (CFn n) args : cs)
500 = do g <- altFnGroup n args
501 rest <- altGroups cs
502 return (g : rest)
503 altGroups (ConGroup CSuc args : cs)
504 = do g <- altSucGroup args
505 rest <- altGroups cs
506 return (g : rest)
507 altGroups (ConGroup (CConst c) args : cs)
508 = do g <- altConstGroup c args
509 rest <- altGroups cs
510 return (g : rest)
512 altGroup n i gs = do (newArgs, nextCs) <- argsToAlt gs
513 matchCs <- match (newArgs ++ vs) nextCs err
514 return $ ConCase n i newArgs matchCs
515 altFnGroup n gs = do (newArgs, nextCs) <- argsToAlt gs
516 matchCs <- match (newArgs ++ vs) nextCs err
517 return $ FnCase n newArgs matchCs
518 altSucGroup gs = do ([newArg], nextCs) <- argsToAlt gs
519 matchCs <- match (newArg:vs) nextCs err
520 return $ SucCase newArg matchCs
521 altConstGroup n gs = do (_, nextCs) <- argsToAlt gs
522 matchCs <- match vs nextCs err
523 return $ ConstCase n matchCs
525argsToAlt :: [([Pat], Clause)] -> State CS ([Name], [Clause])
526argsToAlt [] = return ([], [])
527argsToAlt rs@((r, m) : rest)
528 = do newArgs <- getNewVars r
529 return (newArgs, addRs rs)
530 where
531 getNewVars [] = return []
532 getNewVars ((PV n t) : ns) = do v <- getVar "e"
533 (cs, i, ntys) <- get
534 put (cs, i, (v, t) : ntys)
535 nsv <- getNewVars ns
536 return (v : nsv)
537 getNewVars (PAny : ns) = do v <- getVar "i"
538 nsv <- getNewVars ns
539 return (v : nsv)
540 getNewVars (PTyPat : ns) = do v <- getVar "t"
541 nsv <- getNewVars ns
542 return (v : nsv)
543 getNewVars (_ : ns) = do v <- getVar "e"
544 nsv <- getNewVars ns
545 return (v : nsv)
546 addRs [] = []
547 addRs ((r, (ps, res)) : rs) = ((r++ps, res) : addRs rs)
549 uniq i (UN n) = MN i n
550 uniq i n = n
552getVar :: String -> State CS Name
553getVar b = do (t, v, ntys) <- get; put (t, v+1, ntys); return (sMN v b)
555groupCons :: [Clause] -> State CS [Group]
556groupCons cs = gc [] cs
557 where
558 gc acc [] = return acc
559 gc acc ((p : ps, res) : cs) =
560 do acc' <- addGroup p ps res acc
561 gc acc' cs
562 addGroup p ps res acc = case p of
563 PCon con i args -> return $ addg (CName con i) args (ps, res) acc
564 PConst cval -> return $ addConG cval (ps, res) acc
565 PSuc n -> return $ addg CSuc [n] (ps, res) acc
566 PReflected fn args -> return $ addg (CFn fn) args (ps, res) acc
567 pat -> fail $ show pat ++ " is not a constructor or constant (can't happen)"
569 addg c conargs res []
570 = [ConGroup c [(conargs, res)]]
571 addg c conargs res (g@(ConGroup c' cs):gs)
572 | c == c' = ConGroup c (cs ++ [(conargs, res)]) : gs
573 | otherwise = g : addg c conargs res gs
575 addConG con res [] = [ConGroup (CConst con) [([], res)]]
576 addConG con res (g@(ConGroup (CConst n) cs) : gs)
577 | con == n = ConGroup (CConst n) (cs ++ [([], res)]) : gs
578-- | otherwise = g : addConG con res gs
579 addConG con res (g : gs) = g : addConG con res gs
581varRule :: [Name] -> [Clause] -> SC -> State CS SC
582varRule (v : vs) alts err =
583 do alts' <- mapM (repVar v) alts
584 match vs alts' err
585 where
586 repVar v (PV p ty : ps , (lhs, res))
587 = do (cs, i, ntys) <- get
588 put (cs, i, (v, ty) : ntys)
589 return (ps, (lhs, subst p (P Bound v ty) res))
590 repVar v (PAny : ps , res) = return (ps, res)
591 repVar v (PTyPat : ps , res) = return (ps, res)
593-- fix: case e of S k -> f (S k) ==> case e of S k -> f e
595depatt :: [Name] -> SC -> SC
596depatt ns tm = dp [] tm
597 where
598 dp ms (STerm tm) = STerm (applyMaps ms tm)
599 dp ms (Case x alts) = Case x (map (dpa ms x) alts)
600 dp ms sc = sc
602 dpa ms x (ConCase n i args sc)
603 = ConCase n i args (dp ((x, (n, args)) : ms) sc)
604 dpa ms x (FnCase n args sc)
605 = FnCase n args (dp ((x, (n, args)) : ms) sc)
606 dpa ms x (ConstCase c sc) = ConstCase c (dp ms sc)
607 dpa ms x (SucCase n sc) = SucCase n (dp ms sc)
608 dpa ms x (DefaultCase sc) = DefaultCase (dp ms sc)
610 applyMaps ms f@(App _ _)
611 | (P nt cn pty, args) <- unApply f
612 = let args' = map (applyMaps ms) args in
613 applyMap ms nt cn pty args'
614 where
615 applyMap [] nt cn pty args' = mkApp (P nt cn pty) args'
616 applyMap ((x, (n, args)) : ms) nt cn pty args'
617 | and ((length args == length args') :
618 (n == cn) : zipWith same args args') = P Ref x Erased
619 | otherwise = applyMap ms nt cn pty args'
620 same n (P _ n' _) = n == n'
621 same _ _ = False
623 applyMaps ms (App f a) = App (applyMaps ms f) (applyMaps ms a)
624 applyMaps ms t = t
626-- FIXME: Do this for SucCase too
627prune :: Bool -- ^ Convert single branches to projections (only useful at runtime)
628 -> SC -> SC
629prune proj (Case n alts) = case alts' of
630 [] -> ImpossibleCase
632 -- Projection transformations prevent us from seeing some uses of ctor fields
633 -- because they delete information about which ctor is being used.
634 -- Consider:
635 -- f (X x) = ... x ...
636 -- vs.
637 -- f x = ... x!0 ...
638 --
639 -- Hence, we disable this step.
640 -- TODO: re-enable this in toIR
641 --
642 -- as@[ConCase cn i args sc]
643 -- | proj -> mkProj n 0 args (prune proj sc)
644 -- mkProj n i xs sc = foldr (\x -> projRep x n i) sc xs
646 -- If none of the args are used in the sc, however, we can just replace it
647 -- with sc
648 as@[ConCase cn i args sc]
649 | proj -> let sc' = prune proj sc in
650 if any (isUsed sc') args
651 then Case n [ConCase cn i args sc']
652 else sc'
654 [SucCase cn sc]
655 | proj
656 -> projRep cn n (-1) $ prune proj sc
658 [ConstCase _ sc]
659 -> prune proj sc
661 -- Bit of a hack here! The default case will always be 0, make sure
662 -- it gets caught first.
663 [s@(SucCase _ _), DefaultCase dc]
664 -> Case n [ConstCase (BI 0) dc, s]
666 as -> Case n as
667 where
668 alts' = filter (not . erased) $ map pruneAlt alts
670 pruneAlt (ConCase cn i ns sc) = ConCase cn i ns (prune proj sc)
671 pruneAlt (FnCase cn ns sc) = FnCase cn ns (prune proj sc)
672 pruneAlt (ConstCase c sc) = ConstCase c (prune proj sc)
673 pruneAlt (SucCase n sc) = SucCase n (prune proj sc)
674 pruneAlt (DefaultCase sc) = DefaultCase (prune proj sc)
676 erased (DefaultCase (STerm Erased)) = True
677 erased (DefaultCase ImpossibleCase) = True
678 erased _ = False
680 projRep :: Name -> Name -> Int -> SC -> SC
681 projRep arg n i (Case x alts) | x == arg
682 = ProjCase (Proj (P Bound n Erased) i) $ map (projRepAlt arg n i) alts
683 projRep arg n i (Case x alts)
684 = Case x (map (projRepAlt arg n i) alts)
685 projRep arg n i (ProjCase t alts)
686 = ProjCase (projRepTm arg n i t) $ map (projRepAlt arg n i) alts
687 projRep arg n i (STerm t) = STerm (projRepTm arg n i t)
688 projRep arg n i c = c
690 projRepAlt arg n i (ConCase cn t args rhs)
691 = ConCase cn t args (projRep arg n i rhs)
692 projRepAlt arg n i (FnCase cn args rhs)
693 = FnCase cn args (projRep arg n i rhs)
694 projRepAlt arg n i (ConstCase t rhs)
695 = ConstCase t (projRep arg n i rhs)
696 projRepAlt arg n i (SucCase sn rhs)
697 = SucCase sn (projRep arg n i rhs)
698 projRepAlt arg n i (DefaultCase rhs)
699 = DefaultCase (projRep arg n i rhs)
701 projRepTm arg n i t = subst arg (Proj (P Bound n Erased) i) t
703prune _ t = t
705stripLambdas :: CaseDef -> CaseDef
706stripLambdas (CaseDef ns (STerm (Bind x (Lam _) sc)) tm)
707 = stripLambdas (CaseDef (ns ++ [x]) (STerm (instantiate (P Bound x Erased) sc)) tm)
708stripLambdas x = x
710substSC :: Name -> Name -> SC -> SC
711substSC n repl (Case n' alts)
712 | n == n' = Case repl (map (substAlt n repl) alts)
713 | otherwise = Case n' (map (substAlt n repl) alts)
714substSC n repl (STerm t) = STerm $ subst n (P Bound repl Erased) t
715substSC n repl sc = error $ "unsupported in substSC: " ++ show sc
717substAlt :: Name -> Name -> CaseAlt -> CaseAlt
718substAlt n repl (ConCase cn a ns sc) = ConCase cn a ns (substSC n repl sc)
719substAlt n repl (FnCase fn ns sc) = FnCase fn ns (substSC n repl sc)
720substAlt n repl (ConstCase c sc) = ConstCase c (substSC n repl sc)
721substAlt n repl (SucCase n' sc)
722 | n == n' = SucCase n (substSC n repl sc)
723 | otherwise = SucCase n' (substSC n repl sc)
724substAlt n repl (DefaultCase sc) = DefaultCase (substSC n repl sc)
726mkForce :: Name -> Name -> SC -> SC
727mkForce = mkForceSC
728 where
729 mkForceSC n arg (Case x alts) | x == arg
730 = ProjCase (forceArg n) $ map (mkForceAlt n arg) alts
732 mkForceSC n arg (Case x alts)
733 = Case x (map (mkForceAlt n arg) alts)
735 mkForceSC n arg (ProjCase t alts)
736 = ProjCase (forceTm n arg t) $ map (mkForceAlt n arg) alts
738 mkForceSC n arg (STerm t) = STerm (forceTm n arg t)
739 mkForceSC n arg c = c
741 mkForceAlt n arg (ConCase cn t args rhs)
742 = ConCase cn t args (mkForceSC n arg rhs)
743 mkForceAlt n arg (FnCase cn args rhs)
744 = FnCase cn args (mkForceSC n arg rhs)
745 mkForceAlt n arg (ConstCase t rhs)
746 = ConstCase t (mkForceSC n arg rhs)
747 mkForceAlt n arg (SucCase sn rhs)
748 = SucCase sn (mkForceSC n arg rhs)
749 mkForceAlt n arg (DefaultCase rhs)
750 = DefaultCase (mkForceSC n arg rhs)
752 forceTm n arg t = subst arg (forceArg n) t
754 forceArg n = App (App (App (P Ref (sUN "Force") Erased) Erased) Erased)
755 (P Bound n Erased)