on 8a3d348 help sign in
Idris-dev/src/Idris/Core/CaseTree.hs
788 lines 31 kB history raw
1{-# LANGUAGE PatternGuards, DeriveFunctor, TypeSynonymInstances #-}
3module Idris.Core.CaseTree(CaseDef(..), SC, SC'(..), CaseAlt, CaseAlt'(..), ErasureInfo,
4 Phase(..), CaseTree, CaseType(..),
5 simpleCase, small, namesUsed, findCalls, findUsedArgs,
6 substSC, substAlt, mkForce) where
8import Idris.Core.TT
10import Control.Applicative hiding (Const)
11import Control.Monad.State
12import Control.Monad.Reader
13import Data.Maybe
14import Data.List hiding (partition)
15import qualified Data.List(partition)
16import Debug.Trace
18data CaseDef = CaseDef [Name] !SC [Term]
19 deriving Show
21-- Note: The case-tree elaborator only produces (Case n alts)-cases;
22-- in other words, it never inspects anything else than variables.
23--
24-- ProjCase is a special powerful case construct that allows inspection
25-- of compound terms. Occurrences of ProjCase arise no earlier than
26-- in the function `prune` as a means of optimisation
27-- of already built case trees.
28--
29-- While the intermediate representation (follows in the pipeline, named LExp)
30-- allows casing on arbitrary terms, here we choose to maintain the distinction
31-- in order to allow for better optimisation opportunities.
32--
33data SC' t = Case CaseType Name [CaseAlt' t] -- ^ invariant: lowest tags first
34 | ProjCase t [CaseAlt' t] -- ^ special case for projections/thunk-forcing before inspection
35 | STerm !t
36 | UnmatchedCase String -- ^ error message
37 | ImpossibleCase -- ^ already checked to be impossible
38 deriving (Eq, Ord, Functor)
39{-!
40deriving instance Binary SC'
41deriving instance NFData SC'
42!-}
44data CaseType = Updatable | Shared
45 deriving (Eq, Ord, Show)
47type SC = SC' Term
49data CaseAlt' t = ConCase Name Int [Name] !(SC' t)
50 | FnCase Name [Name] !(SC' t) -- ^ reflection function
51 | ConstCase Const !(SC' t)
52 | SucCase Name !(SC' t)
53 | DefaultCase !(SC' t)
54 deriving (Show, Eq, Ord, Functor)
55{-!
56deriving instance Binary CaseAlt'
57deriving instance NFData CaseAlt'
58!-}
60type CaseAlt = CaseAlt' Term
62instance Show t => Show (SC' t) where
63 show sc = show' 1 sc
64 where
65 show' i (Case up n alts) = "case" ++ u ++ show n ++ " of\n" ++ indent i ++
66 showSep ("\n" ++ indent i) (map (showA i) alts)
67 where u = case up of
68 Updatable -> "! "
69 Shared -> " "
70 show' i (ProjCase tm alts) = "case " ++ show tm ++ " of " ++
71 showSep ("\n" ++ indent i) (map (showA i) alts)
72 show' i (STerm tm) = show tm
73 show' i (UnmatchedCase str) = "error " ++ show str
74 show' i ImpossibleCase = "impossible"
76 indent i = concat $ take i (repeat " ")
78 showA i (ConCase n t args sc)
79 = show n ++ "(" ++ showSep (", ") (map show args) ++ ") => "
80 ++ show' (i+1) sc
81 showA i (FnCase n args sc)
82 = "FN " ++ show n ++ "(" ++ showSep (", ") (map show args) ++ ") => "
83 ++ show' (i+1) sc
84 showA i (ConstCase t sc)
85 = show t ++ " => " ++ show' (i+1) sc
86 showA i (SucCase n sc)
87 = show n ++ "+1 => " ++ show' (i+1) sc
88 showA i (DefaultCase sc)
89 = "_ => " ++ show' (i+1) sc
92type CaseTree = SC
93type Clause = ([Pat], (Term, Term))
94type CS = ([Term], Int, [(Name, Type)])
96instance TermSize SC where
97 termsize n (Case _ n' as) = termsize n as
98 termsize n (ProjCase n' as) = termsize n as
99 termsize n (STerm t) = termsize n t
100 termsize n _ = 1
102instance TermSize CaseAlt where
103 termsize n (ConCase _ _ _ s) = termsize n s
104 termsize n (FnCase _ _ s) = termsize n s
105 termsize n (ConstCase _ s) = termsize n s
106 termsize n (SucCase _ s) = termsize n s
107 termsize n (DefaultCase s) = termsize n s
109-- simple terms can be inlined trivially - good for primitives in particular
110-- To avoid duplicating work, don't inline something which uses one
111-- of its arguments in more than one place
113small :: Name -> [Name] -> SC -> Bool
114small n args t = let as = findAllUsedArgs t args in
115 length as == length (nub as) &&
116 termsize n t < 10
118namesUsed :: SC -> [Name]
119namesUsed sc = nub $ nu' [] sc where
120 nu' ps (Case _ n alts) = nub (concatMap (nua ps) alts) \\ [n]
121 nu' ps (ProjCase t alts) = nub $ nut ps t ++ concatMap (nua ps) alts
122 nu' ps (STerm t) = nub $ nut ps t
123 nu' ps _ = []
125 nua ps (ConCase n i args sc) = nub (nu' (ps ++ args) sc) \\ args
126 nua ps (FnCase n args sc) = nub (nu' (ps ++ args) sc) \\ args
127 nua ps (ConstCase _ sc) = nu' ps sc
128 nua ps (SucCase _ sc) = nu' ps sc
129 nua ps (DefaultCase sc) = nu' ps sc
131 nut ps (P _ n _) | n `elem` ps = []
132 | otherwise = [n]
133 nut ps (App f a) = nut ps f ++ nut ps a
134 nut ps (Proj t _) = nut ps t
135 nut ps (Bind n (Let t v) sc) = nut ps v ++ nut (n:ps) sc
136 nut ps (Bind n b sc) = nut (n:ps) sc
137 nut ps _ = []
139-- Return all called functions, and which arguments are used in each argument position
140-- for the call, in order to help reduce compilation time, and trace all unused
141-- arguments
143findCalls :: SC -> [Name] -> [(Name, [[Name]])]
144findCalls sc topargs = nub $ nu' topargs sc where
145 nu' ps (Case _ n alts) = nub (concatMap (nua (n : ps)) alts)
146 nu' ps (ProjCase t alts) = nub $ nut ps t ++ concatMap (nua ps) alts
147 nu' ps (STerm t) = nub $ nut ps t
148 nu' ps _ = []
150 nua ps (ConCase n i args sc) = nub (nu' (ps ++ args) sc)
151 nua ps (FnCase n args sc) = nub (nu' (ps ++ args) sc)
152 nua ps (ConstCase _ sc) = nu' ps sc
153 nua ps (SucCase _ sc) = nu' ps sc
154 nua ps (DefaultCase sc) = nu' ps sc
156 nut ps (P Ref n _) | n `elem` ps = []
157 | otherwise = [(n, [])] -- tmp
158 nut ps fn@(App f a)
159 | (P Ref n _, args) <- unApply fn
160 = if n `elem` ps then nut ps f ++ nut ps a
161 else [(n, map argNames args)] ++ concatMap (nut ps) args
162 | (P (TCon _ _) n _, _) <- unApply fn = []
163 | otherwise = nut ps f ++ nut ps a
164 nut ps (Bind n (Let t v) sc) = nut ps v ++ nut (n:ps) sc
165 nut ps (Proj t _) = nut ps t
166 nut ps (Bind n b sc) = nut (n:ps) sc
167 nut ps _ = []
169 argNames tm = let ns = directUse tm in
170 filter (\x -> x `elem` ns) topargs
172-- Find names which are used directly (i.e. not in a function call) in a term
174directUse :: TT Name -> [Name]
175directUse (P _ n _) = [n]
176directUse (Bind n (Let t v) sc) = nub $ directUse v ++ (directUse sc \\ [n])
177 ++ directUse t
178directUse (Bind n b sc) = nub $ directUse (binderTy b) ++ (directUse sc \\ [n])
179directUse fn@(App f a)
180 | (P Ref (UN pfk) _, [App e w]) <- unApply fn,
181 pfk == txt "prim_fork"
182 = directUse e ++ directUse w -- HACK so that fork works
183 | (P Ref (UN fce) _, [_, _, a]) <- unApply fn,
184 fce == txt "Force"
185 = directUse a -- forcing a value counts as a use
186 | (P Ref n _, args) <- unApply fn = [] -- need to know what n does with them
187 | (P (TCon _ _) n _, args) <- unApply fn = [] -- type constructors not used at runtime
188 | otherwise = nub $ directUse f ++ directUse a
189directUse (Proj x i) = nub $ directUse x
190directUse _ = []
192-- Find all directly used arguments (i.e. used but not in function calls)
194findUsedArgs :: SC -> [Name] -> [Name]
195findUsedArgs sc topargs = nub (findAllUsedArgs sc topargs)
197findAllUsedArgs sc topargs = filter (\x -> x `elem` topargs) (nu' sc) where
198 nu' (Case _ n alts) = n : concatMap nua alts
199 nu' (ProjCase t alts) = directUse t ++ concatMap nua alts
200 nu' (STerm t) = directUse t
201 nu' _ = []
203 nua (ConCase n i args sc) = nu' sc
204 nua (FnCase n args sc) = nu' sc
205 nua (ConstCase _ sc) = nu' sc
206 nua (SucCase _ sc) = nu' sc
207 nua (DefaultCase sc) = nu' sc
209-- Return whether name is used anywhere in a case tree
210isUsed :: SC -> Name -> Bool
211isUsed sc n = used sc where
213 used (Case _ n' alts) = n == n' || or (map usedA alts)
214 used (ProjCase t alts) = n `elem` freeNames t || or (map usedA alts)
215 used (STerm t) = n `elem` freeNames t
216 used _ = False
218 usedA (ConCase _ _ args sc) = used sc
219 usedA (FnCase _ args sc) = used sc
220 usedA (ConstCase _ sc) = used sc
221 usedA (SucCase _ sc) = used sc
222 usedA (DefaultCase sc) = used sc
224type ErasureInfo = Name -> [Int] -- name to list of inaccessible arguments; empty list if name not found
225type CaseBuilder a = ReaderT ErasureInfo (State CS) a
227runCaseBuilder :: ErasureInfo -> CaseBuilder a -> (CS -> (a, CS))
228runCaseBuilder ei bld = runState $ runReaderT bld ei
230data Phase = CompileTime | RunTime
231 deriving (Show, Eq)
233-- Generate a simple case tree
234-- Work Right to Left
236simpleCase :: Bool -> SC -> Bool ->
237 Phase -> FC -> [Int] -> [Type] ->
238 [([Name], Term, Term)] ->
239 ErasureInfo ->
240 TC CaseDef
241simpleCase tc defcase reflect phase fc inacc argtys cs erInfo
242 = sc' tc defcase phase fc (filter (\(_, _, r) ->
243 case r of
244 Impossible -> False
245 _ -> True) cs)
246 where
247 sc' tc defcase phase fc []
248 = return $ CaseDef [] (UnmatchedCase "No pattern clauses") []
249 sc' tc defcase phase fc cs
250 = let proj = phase == RunTime
251 vnames = fstT (head cs)
252 pats = map (\ (avs, l, r) ->
253 (avs, toPats reflect tc l, (l, r))) cs
254 chkPats = mapM chkAccessible pats in
255 case chkPats of
256 OK pats ->
257 let numargs = length (fst (head pats))
258 ns = take numargs args
259 (ns', ps') = order [(n, i `elem` inacc) | (i,n) <- zip [0..] ns] pats
260 (tree, st) = runCaseBuilder erInfo
261 (match ns' ps' defcase)
262 ([], numargs, [])
263 t = CaseDef ns (prune proj (depatt ns' tree)) (fstT st) in
264 if proj then return (stripLambdas t)
265 else return t
266 Error err -> Error (At fc err)
267 where args = map (\i -> sMN i "e") [0..]
268 defaultCase True = STerm Erased
269 defaultCase False = UnmatchedCase "Error"
270 fstT (x, _, _) = x
271 lstT (_, _, x) = x
273 chkAccessible (avs, l, c)
274 | phase == RunTime || reflect = return (l, c)
275 | otherwise = do mapM_ (acc l) avs
276 return (l, c)
278 acc [] n = Error (Inaccessible n)
279 acc (PV x t : xs) n | x == n = OK ()
280 acc (PCon _ _ _ ps : xs) n = acc (ps ++ xs) n
281 acc (PSuc p : xs) n = acc (p : xs) n
282 acc (_ : xs) n = acc xs n
284-- For each 'Case', make sure every choice is in the same type family,
285-- as directed by the variable type (i.e. there is no implicit type casing
286-- going on).
288checkSameTypes :: [(Name, Type)] -> SC -> Bool
289checkSameTypes tys (Case _ n alts)
290 = case lookup n tys of
291 Just t -> and (map (checkAlts t) alts)
292 _ -> and (map ((checkSameTypes tys).getSC) alts)
293 where
294 checkAlts t (ConCase n _ _ sc) = isType n t && checkSameTypes tys sc
295 checkAlts (Constant t) (ConstCase c sc) = isConstType c t && checkSameTypes tys sc
296 checkAlts _ (ConstCase c sc) = False
297 checkAlts _ _ = True
299 getSC (ConCase _ _ _ sc) = sc
300 getSC (FnCase _ _ sc) = sc
301 getSC (ConstCase _ sc) = sc
302 getSC (SucCase _ sc) = sc
303 getSC (DefaultCase sc) = sc
304checkSameTypes _ _ = True
306-- FIXME: All we're actually doing here is checking that we haven't arrived
307-- at a specific constructor for a polymorphic argument. I *think* this
308-- is sufficient, but if it turns out not to be, fix it!
309--
310-- Issue #1718 on the issue tracker: https://github.com/idris-lang/Idris-dev/issues/1718
311isType n t | (P (TCon _ _) _ _, _) <- unApply t = True
312isType n t | (P Ref _ _, _) <- unApply t = True
313isType n t = False
315isConstType (I _) (AType (ATInt ITNative)) = True
316isConstType (BI _) (AType (ATInt ITBig)) = True
317isConstType (Fl _) (AType ATFloat) = True
318isConstType (Ch _) (AType (ATInt ITChar)) = True
319isConstType (Str _) StrType = True
320isConstType (B8 _) (AType (ATInt _)) = True
321isConstType (B16 _) (AType (ATInt _)) = True
322isConstType (B32 _) (AType (ATInt _)) = True
323isConstType (B64 _) (AType (ATInt _)) = True
324isConstType _ _ = False
326data Pat = PCon Bool Name Int [Pat]
327 | PConst Const
328 | PV Name Type
329 | PSuc Pat -- special case for n+1 on Integer
330 | PReflected Name [Pat]
331 | PAny
332 | PTyPat -- typecase, not allowed, inspect last
333 deriving Show
335-- If there are repeated variables, take the *last* one (could be name shadowing
336-- in a where clause, so take the most recent).
338toPats :: Bool -> Bool -> Term -> [Pat]
339toPats reflect tc f = reverse (toPat reflect tc (getArgs f)) where
340 getArgs (App f a) = a : getArgs f
341 getArgs _ = []
343toPat :: Bool -> Bool -> [Term] -> [Pat]
344toPat reflect tc = map $ toPat' []
345 where
346 toPat' [_,_,arg] (P (DCon t a uniq) nm@(UN n) _)
347 | n == txt "Delay"
348 = PCon uniq nm t [PAny, PAny, toPat' [] arg]
350 toPat' args (P (DCon t a uniq) nm@(NS (UN n) [own]) _)
351 | n == txt "Read" && own == txt "Ownership"
352 = PCon False nm t (map shareCons (map (toPat' []) args))
353 where shareCons (PCon _ n i ps) = PCon False n i (map shareCons ps)
354 shareCons p = p
356 toPat' args (P (DCon t a uniq) n _)
357 = PCon uniq n t $ map (toPat' []) args
359 -- n + 1
360 toPat' [p, Constant (BI 1)] (P _ (UN pabi) _)
361 | pabi == txt "prim__addBigInt"
362 = PSuc $ toPat' [] p
364 toPat' [] (P Bound n ty) = PV n ty
365 toPat' args (App f a) = toPat' (a : args) f
366 toPat' [] (Constant x) | isTypeConst x = PTyPat
367 | otherwise = PConst x
369 toPat' [] (Bind n (Pi _ t _) sc)
370 | reflect && noOccurrence n sc
371 = PReflected (sUN "->") [toPat' [] t, toPat' [] sc]
373 toPat' args (P _ n _)
374 | reflect
375 = PReflected n $ map (toPat' []) args
377 toPat' _ t = PAny
379 fixedN IT8 = "Bits8"
380 fixedN IT16 = "Bits16"
381 fixedN IT32 = "Bits32"
382 fixedN IT64 = "Bits64"
385data Partition = Cons [Clause]
386 | Vars [Clause]
387 deriving Show
389isVarPat (PV _ _ : ps , _) = True
390isVarPat (PAny : ps , _) = True
391isVarPat (PTyPat : ps , _) = True
392isVarPat _ = False
394isConPat (PCon _ _ _ _ : ps, _) = True
395isConPat (PReflected _ _ : ps, _) = True
396isConPat (PSuc _ : ps, _) = True
397isConPat (PConst _ : ps, _) = True
398isConPat _ = False
400partition :: [Clause] -> [Partition]
401partition [] = []
402partition ms@(m : _)
403 | isVarPat m = let (vars, rest) = span isVarPat ms in
404 Vars vars : partition rest
405 | isConPat m = let (cons, rest) = span isConPat ms in
406 Cons cons : partition rest
407partition xs = error $ "Partition " ++ show xs
409-- reorder the patterns so that the one with most distinct names
410-- comes next. Take rightmost first, otherwise (i.e. pick value rather
411-- than dependency)
412--
413-- The first argument means [(Name, IsInaccessible)].
415order :: [(Name, Bool)] -> [Clause] -> ([Name], [Clause])
416order [] cs = ([], cs)
417order ns' [] = (map fst ns', [])
418order ns' cs = let patnames = transpose (map (zip ns') (map fst cs))
419 -- only sort the arguments where there is no clash in
420 -- constructor tags between families, and no constructor/constant
421 -- clash, because otherwise we can't reliable make the
422 -- case distinction on evaluation
423 (patnames_ord, patnames_rest)
424 = Data.List.partition (noClash . map snd) patnames
425 -- note: sortBy . reverse is not nonsense because sortBy is stable
426 pats' = transpose (sortBy moreDistinct (reverse patnames_ord)
427 ++ patnames_rest) in
428 (getNOrder pats', zipWith rebuild pats' cs)
429 where
430 getNOrder [] = error $ "Failed order on " ++ show (map fst ns', cs)
431 getNOrder (c : _) = map (fst . fst) c
433 rebuild patnames clause = (map snd patnames, snd clause)
435 noClash [] = True
436 noClash (p : ps) = not (any (clashPat p) ps) && noClash ps
438 clashPat (PCon _ _ _ _) (PConst _) = True
439 clashPat (PConst _) (PCon _ _ _ _) = True
440 clashPat (PCon _ _ _ _) (PSuc _) = True
441 clashPat (PSuc _) (PCon _ _ _ _) = True
442 clashPat (PCon _ n i _) (PCon _ n' i' _) | i == i' = n /= n'
443 clashPat _ _ = False
445 -- this compares (+isInaccessible, -numberOfCases)
446 moreDistinct xs ys = compare (snd . fst . head $ xs, numNames [] (map snd ys))
447 (snd . fst . head $ ys, numNames [] (map snd xs))
449 numNames xs (PCon _ n _ _ : ps)
450 | not (Left n `elem` xs) = numNames (Left n : xs) ps
451 numNames xs (PConst c : ps)
452 | not (Right c `elem` xs) = numNames (Right c : xs) ps
453 numNames xs (_ : ps) = numNames xs ps
454 numNames xs [] = length xs
456match :: [Name] -> [Clause] -> SC -- error case
457 -> CaseBuilder SC
458match [] (([], ret) : xs) err
459 = do (ts, v, ntys) <- get
460 put (ts ++ (map (fst.snd) xs), v, ntys)
461 case snd ret of
462 Impossible -> return ImpossibleCase
463 tm -> return $ STerm tm -- run out of arguments
464match vs cs err = do let ps = partition cs
465 mixture vs ps err
467mixture :: [Name] -> [Partition] -> SC -> CaseBuilder SC
468mixture vs [] err = return err
469mixture vs (Cons ms : ps) err = do fallthrough <- mixture vs ps err
470 conRule vs ms fallthrough
471mixture vs (Vars ms : ps) err = do fallthrough <- mixture vs ps err
472 varRule vs ms fallthrough
474-- Return the list of inaccessible arguments of a data constructor.
475inaccessibleArgs :: Name -> CaseBuilder [Int]
476inaccessibleArgs n = do
477 getInaccessiblePositions <- ask -- this function is the only thing in the environment
478 return $ getInaccessiblePositions n
480data ConType = CName Name Int -- named constructor
481 | CFn Name -- reflected function name
482 | CSuc -- n+1
483 | CConst Const -- constant, not implemented yet
484 deriving (Show, Eq)
486data Group = ConGroup Bool -- Uniqueness flag
487 ConType -- Constructor
488 [([Pat], Clause)] -- arguments and rest of alternative
489 deriving Show
491conRule :: [Name] -> [Clause] -> SC -> CaseBuilder SC
492conRule (v:vs) cs err = do groups <- groupCons cs
493 caseGroups (v:vs) groups err
495caseGroups :: [Name] -> [Group] -> SC -> CaseBuilder SC
496caseGroups (v:vs) gs err = do g <- altGroups gs
497 return $ Case (getShared gs) v (sort g)
498 where
499 getShared (ConGroup True _ _ : _) = Updatable
500 getShared _ = Shared
502 altGroups [] = return [DefaultCase err]
504 altGroups (ConGroup _ (CName n i) args : cs)
505 = (:) <$> altGroup n i args <*> altGroups cs
507 altGroups (ConGroup _ (CFn n) args : cs)
508 = (:) <$> altFnGroup n args <*> altGroups cs
510 altGroups (ConGroup _ CSuc args : cs)
511 = (:) <$> altSucGroup args <*> altGroups cs
513 altGroups (ConGroup _ (CConst c) args : cs)
514 = (:) <$> altConstGroup c args <*> altGroups cs
516 altGroup n i args
517 = do inacc <- inaccessibleArgs n
518 (newVars, accVars, inaccVars, nextCs) <- argsToAlt inacc args
519 matchCs <- match (accVars ++ vs ++ inaccVars) nextCs err
520 return $ ConCase n i newVars matchCs
522 altFnGroup n args = do (newVars, _, [], nextCs) <- argsToAlt [] args
523 matchCs <- match (newVars ++ vs) nextCs err
524 return $ FnCase n newVars matchCs
526 altSucGroup args = do ([newVar], _, [], nextCs) <- argsToAlt [] args
527 matchCs <- match (newVar:vs) nextCs err
528 return $ SucCase newVar matchCs
530 altConstGroup n args = do (_, _, [], nextCs) <- argsToAlt [] args
531 matchCs <- match vs nextCs err
532 return $ ConstCase n matchCs
534-- Returns:
535-- * names of all variables arising from match
536-- * names of accessible variables (subset of all variables)
537-- * names of inaccessible variables (subset of all variables)
538-- * clauses corresponding to (accVars ++ origVars ++ inaccVars)
539argsToAlt :: [Int] -> [([Pat], Clause)] -> CaseBuilder ([Name], [Name], [Name], [Clause])
540argsToAlt _ [] = return ([], [], [], [])
541argsToAlt inacc rs@((r, m) : rest) = do
542 newVars <- getNewVars r
543 let (accVars, inaccVars) = partitionAcc newVars
544 return (newVars, accVars, inaccVars, addRs rs)
545 where
546 -- Create names for new variables arising from the given patterns.
547 getNewVars :: [Pat] -> CaseBuilder [Name]
548 getNewVars [] = return []
549 getNewVars ((PV n t) : ns) = do v <- getVar "e"
550 nsv <- getNewVars ns
552 -- Record the type of the variable.
553 --
554 -- It seems that the ordering is not important
555 -- and we can put (v,t) always in front of "ntys"
556 -- (the varName-type pairs seem to represent a mapping).
557 --
558 -- The code that reads this is currently
559 -- commented out, anyway.
560 (cs, i, ntys) <- get
561 put (cs, i, (v, t) : ntys)
563 return (v : nsv)
565 getNewVars (PAny : ns) = (:) <$> getVar "i" <*> getNewVars ns
566 getNewVars (PTyPat : ns) = (:) <$> getVar "t" <*> getNewVars ns
567 getNewVars (_ : ns) = (:) <$> getVar "e" <*> getNewVars ns
569 -- Partition a list of things into (accessible, inaccessible) things,
570 -- according to the list of inaccessible indices.
571 partitionAcc xs =
572 ( [x | (i,x) <- zip [0..] xs, i `notElem` inacc]
573 , [x | (i,x) <- zip [0..] xs, i `elem` inacc]
574 )
576 addRs [] = []
577 addRs ((r, (ps, res)) : rs) = ((acc++ps++inacc, res) : addRs rs)
578 where
579 (acc, inacc) = partitionAcc r
581 uniq i (UN n) = MN i n
582 uniq i n = n
584getVar :: String -> CaseBuilder Name
585getVar b = do (t, v, ntys) <- get; put (t, v+1, ntys); return (sMN v b)
587groupCons :: [Clause] -> CaseBuilder [Group]
588groupCons cs = gc [] cs
589 where
590 gc acc [] = return acc
591 gc acc ((p : ps, res) : cs) =
592 do acc' <- addGroup p ps res acc
593 gc acc' cs
594 addGroup p ps res acc = case p of
595 PCon uniq con i args -> return $ addg uniq (CName con i) args (ps, res) acc
596 PConst cval -> return $ addConG cval (ps, res) acc
597 PSuc n -> return $ addg False CSuc [n] (ps, res) acc
598 PReflected fn args -> return $ addg False (CFn fn) args (ps, res) acc
599 pat -> fail $ show pat ++ " is not a constructor or constant (can't happen)"
601 addg uniq c conargs res []
602 = [ConGroup uniq c [(conargs, res)]]
603 addg uniq c conargs res (g@(ConGroup _ c' cs):gs)
604 | c == c' = ConGroup uniq c (cs ++ [(conargs, res)]) : gs
605 | otherwise = g : addg uniq c conargs res gs
607 addConG con res [] = [ConGroup False (CConst con) [([], res)]]
608 addConG con res (g@(ConGroup False (CConst n) cs) : gs)
609 | con == n = ConGroup False (CConst n) (cs ++ [([], res)]) : gs
610-- | otherwise = g : addConG con res gs
611 addConG con res (g : gs) = g : addConG con res gs
613varRule :: [Name] -> [Clause] -> SC -> CaseBuilder SC
614varRule (v : vs) alts err =
615 do alts' <- mapM (repVar v) alts
616 match vs alts' err
617 where
618 repVar v (PV p ty : ps , (lhs, res))
619 = do (cs, i, ntys) <- get
620 put (cs, i, (v, ty) : ntys)
621 return (ps, (lhs, subst p (P Bound v ty) res))
622 repVar v (PAny : ps , res) = return (ps, res)
623 repVar v (PTyPat : ps , res) = return (ps, res)
625-- fix: case e of S k -> f (S k) ==> case e of S k -> f e
627depatt :: [Name] -> SC -> SC
628depatt ns tm = dp [] tm
629 where
630 dp ms (STerm tm) = STerm (applyMaps ms tm)
631 dp ms (Case up x alts) = Case up x (map (dpa ms x) alts)
632 dp ms sc = sc
634 dpa ms x (ConCase n i args sc)
635 = ConCase n i args (dp ((x, (n, args)) : ms) sc)
636 dpa ms x (FnCase n args sc)
637 = FnCase n args (dp ((x, (n, args)) : ms) sc)
638 dpa ms x (ConstCase c sc) = ConstCase c (dp ms sc)
639 dpa ms x (SucCase n sc) = SucCase n (dp ms sc)
640 dpa ms x (DefaultCase sc) = DefaultCase (dp ms sc)
642 applyMaps ms f@(App _ _)
643 | (P nt cn pty, args) <- unApply f
644 = let args' = map (applyMaps ms) args in
645 applyMap ms nt cn pty args'
646 where
647 applyMap [] nt cn pty args' = mkApp (P nt cn pty) args'
648 applyMap ((x, (n, args)) : ms) nt cn pty args'
649 | and ((length args == length args') :
650 (n == cn) : zipWith same args args') = P Ref x Erased
651 | otherwise = applyMap ms nt cn pty args'
652 same n (P _ n' _) = n == n'
653 same _ _ = False
655 applyMaps ms (App f a) = App (applyMaps ms f) (applyMaps ms a)
656 applyMaps ms t = t
658-- FIXME: Do this for SucCase too
659-- Issue #1719 on the issue tracker: https://github.com/idris-lang/Idris-dev/issues/1719
660prune :: Bool -- ^ Convert single branches to projections (only useful at runtime)
661 -> SC -> SC
662prune proj (Case up n alts) = case alts' of
663 [] -> ImpossibleCase
665 -- Projection transformations prevent us from seeing some uses of ctor fields
666 -- because they delete information about which ctor is being used.
667 -- Consider:
668 -- f (X x) = ... x ...
669 -- vs.
670 -- f x = ... x!0 ...
671 --
672 -- Hence, we disable this step.
673 -- TODO: re-enable this in toIR
674 --
675 -- as@[ConCase cn i args sc]
676 -- | proj -> mkProj n 0 args (prune proj sc)
677 -- mkProj n i xs sc = foldr (\x -> projRep x n i) sc xs
679 -- If none of the args are used in the sc, however, we can just replace it
680 -- with sc
681 as@[ConCase cn i args sc]
682 | proj -> let sc' = prune proj sc in
683 if any (isUsed sc') args
684 then Case up n [ConCase cn i args sc']
685 else sc'
687 [SucCase cn sc]
688 | proj
689 -> projRep cn n (-1) $ prune proj sc
691 [ConstCase _ sc]
692 -> prune proj sc
694 -- Bit of a hack here! The default case will always be 0, make sure
695 -- it gets caught first.
696 [s@(SucCase _ _), DefaultCase dc]
697 -> Case up n [ConstCase (BI 0) dc, s]
699 as -> Case up n as
700 where
701 alts' = filter (not . erased) $ map pruneAlt alts
703 pruneAlt (ConCase cn i ns sc) = ConCase cn i ns (prune proj sc)
704 pruneAlt (FnCase cn ns sc) = FnCase cn ns (prune proj sc)
705 pruneAlt (ConstCase c sc) = ConstCase c (prune proj sc)
706 pruneAlt (SucCase n sc) = SucCase n (prune proj sc)
707 pruneAlt (DefaultCase sc) = DefaultCase (prune proj sc)
709 erased (DefaultCase (STerm Erased)) = True
710 erased (DefaultCase ImpossibleCase) = True
711 erased _ = False
713 projRep :: Name -> Name -> Int -> SC -> SC
714 projRep arg n i (Case up x alts) | x == arg
715 = ProjCase (Proj (P Bound n Erased) i) $ map (projRepAlt arg n i) alts
716 projRep arg n i (Case up x alts)
717 = Case up x (map (projRepAlt arg n i) alts)
718 projRep arg n i (ProjCase t alts)
719 = ProjCase (projRepTm arg n i t) $ map (projRepAlt arg n i) alts
720 projRep arg n i (STerm t) = STerm (projRepTm arg n i t)
721 projRep arg n i c = c
723 projRepAlt arg n i (ConCase cn t args rhs)
724 = ConCase cn t args (projRep arg n i rhs)
725 projRepAlt arg n i (FnCase cn args rhs)
726 = FnCase cn args (projRep arg n i rhs)
727 projRepAlt arg n i (ConstCase t rhs)
728 = ConstCase t (projRep arg n i rhs)
729 projRepAlt arg n i (SucCase sn rhs)
730 = SucCase sn (projRep arg n i rhs)
731 projRepAlt arg n i (DefaultCase rhs)
732 = DefaultCase (projRep arg n i rhs)
734 projRepTm arg n i t = subst arg (Proj (P Bound n Erased) i) t
736prune _ t = t
738stripLambdas :: CaseDef -> CaseDef
739stripLambdas (CaseDef ns (STerm (Bind x (Lam _) sc)) tm)
740 = stripLambdas (CaseDef (ns ++ [x]) (STerm (instantiate (P Bound x Erased) sc)) tm)
741stripLambdas x = x
743substSC :: Name -> Name -> SC -> SC
744substSC n repl (Case up n' alts)
745 | n == n' = Case up repl (map (substAlt n repl) alts)
746 | otherwise = Case up n' (map (substAlt n repl) alts)
747substSC n repl (STerm t) = STerm $ subst n (P Bound repl Erased) t
748substSC n repl (UnmatchedCase errmsg) = UnmatchedCase errmsg
749substSC n repl ImpossibleCase = ImpossibleCase
750substSC n repl sc = error $ "unsupported in substSC: " ++ show sc
752substAlt :: Name -> Name -> CaseAlt -> CaseAlt
753substAlt n repl (ConCase cn a ns sc) = ConCase cn a ns (substSC n repl sc)
754substAlt n repl (FnCase fn ns sc) = FnCase fn ns (substSC n repl sc)
755substAlt n repl (ConstCase c sc) = ConstCase c (substSC n repl sc)
756substAlt n repl (SucCase n' sc)
757 | n == n' = SucCase n (substSC n repl sc)
758 | otherwise = SucCase n' (substSC n repl sc)
759substAlt n repl (DefaultCase sc) = DefaultCase (substSC n repl sc)
761-- mkForce n' n t updates the tree t under the assumption that
762-- n' = force n (so basically updating n to n')
763mkForce :: Name -> Name -> SC -> SC
764mkForce = mkForceSC
765 where
766 mkForceSC n arg (Case up x alts) | x == arg
767 = Case up n $ map (mkForceAlt n arg) alts
769 mkForceSC n arg (Case up x alts)
770 = Case up x (map (mkForceAlt n arg) alts)
772 mkForceSC n arg (ProjCase t alts)
773 = ProjCase t $ map (mkForceAlt n arg) alts
775 mkForceSC n arg c = c
777 mkForceAlt n arg (ConCase cn t args rhs)
778 = ConCase cn t args (mkForceSC n arg rhs)
779 mkForceAlt n arg (FnCase cn args rhs)
780 = FnCase cn args (mkForceSC n arg rhs)
781 mkForceAlt n arg (ConstCase t rhs)
782 = ConstCase t (mkForceSC n arg rhs)
783 mkForceAlt n arg (SucCase sn rhs)
784 = SucCase sn (mkForceSC n arg rhs)
785 mkForceAlt n arg (DefaultCase rhs)
786 = DefaultCase (mkForceSC n arg rhs)
788 forceTm n arg t = subst n arg t