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
10import Control.Applicative hiding (Const)
11import Control.Monad.State
12import Control.Monad.Reader
14import Data.List hiding (partition)
15import qualified Data.List(partition)
18data CaseDef = CaseDef [Name] !SC [Term]
21-- Note: The case-tree elaborator only produces (Case n alts)-cases;
22-- in other words, it never inspects anything else than variables.
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.
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.
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
36 | UnmatchedCase String -- ^ error message
37 | ImpossibleCase -- ^ already checked to be impossible
38 deriving (Eq, Ord, Functor)
40deriving instance Binary SC'
41deriving instance NFData SC'
44data CaseType = Updatable | Shared
45 deriving (Eq, Ord, Show)
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)
56deriving instance Binary CaseAlt'
57deriving instance NFData CaseAlt'
60type CaseAlt = CaseAlt' Term
62instance Show t => Show (SC' t) 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)
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) ++ ") => "
81 showA i (FnCase n args sc)
82 = "FN " ++ show n ++ "(" ++ showSep (", ") (map show args) ++ ") => "
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
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
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) &&
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
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 = []
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
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
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
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
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
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])
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,
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
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
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
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
233-- Generate a simple case tree
236simpleCase :: Bool -> Bool -> Bool ->
237 Phase -> FC -> [Int] -> [Type] ->
238 [([Name], Term, Term)] ->
241simpleCase tc cover reflect phase fc inacc argtys cs erInfo
242 = sc' tc cover phase fc (filter (\(_, _, r) ->
247 sc' tc cover phase fc []
248 = return $ CaseDef [] (UnmatchedCase "No pattern clauses") []
249 sc' tc cover 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
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' (defaultCase cover))
263 t = CaseDef ns (prune proj (depatt ns' tree)) (fstT st) in
264 if proj then return (stripLambdas t)
266-- FIXME: This check is not quite right in some cases, and is breaking
267-- perfectly valid code!
268-- if checkSameTypes (lstT st) tree
270-- else Error (At fc (Msg "Typecase is not allowed"))
271 Error err -> Error (At fc err)
272 where args = map (\i -> sMN i "e") [0..]
273 defaultCase True = STerm Erased
274 defaultCase False = UnmatchedCase "Error"
278 chkAccessible (avs, l, c)
279 | phase == RunTime || reflect = return (l, c)
280 | otherwise = do mapM_ (acc l) avs
283 acc [] n = Error (Inaccessible n)
284 acc (PV x t : xs) n | x == n = OK ()
285 acc (PCon _ _ _ ps : xs) n = acc (ps ++ xs) n
286 acc (PSuc p : xs) n = acc (p : xs) n
287 acc (_ : xs) n = acc xs n
289-- For each 'Case', make sure every choice is in the same type family,
290-- as directed by the variable type (i.e. there is no implicit type casing
293checkSameTypes :: [(Name, Type)] -> SC -> Bool
294checkSameTypes tys (Case _ n alts)
295 = case lookup n tys of
296 Just t -> and (map (checkAlts t) alts)
297 _ -> and (map ((checkSameTypes tys).getSC) alts)
299 checkAlts t (ConCase n _ _ sc) = isType n t && checkSameTypes tys sc
300 checkAlts (Constant t) (ConstCase c sc) = isConstType c t && checkSameTypes tys sc
301 checkAlts _ (ConstCase c sc) = False
304 getSC (ConCase _ _ _ sc) = sc
305 getSC (FnCase _ _ sc) = sc
306 getSC (ConstCase _ sc) = sc
307 getSC (SucCase _ sc) = sc
308 getSC (DefaultCase sc) = sc
309checkSameTypes _ _ = True
311-- FIXME: All we're actually doing here is checking that we haven't arrived
312-- at a specific constructor for a polymorphic argument. I *think* this
313-- is sufficient, but if it turns out not to be, fix it!
314isType n t | (P (TCon _ _) _ _, _) <- unApply t = True
315isType n t | (P Ref _ _, _) <- unApply t = True
318isConstType (I _) (AType (ATInt ITNative)) = True
319isConstType (BI _) (AType (ATInt ITBig)) = True
320isConstType (Fl _) (AType ATFloat) = True
321isConstType (Ch _) (AType (ATInt ITChar)) = True
322isConstType (Str _) StrType = True
323isConstType (B8 _) (AType (ATInt _)) = True
324isConstType (B16 _) (AType (ATInt _)) = True
325isConstType (B32 _) (AType (ATInt _)) = True
326isConstType (B64 _) (AType (ATInt _)) = True
327isConstType (B8V _) (AType (ATInt _)) = True
328isConstType (B16V _) (AType (ATInt _)) = True
329isConstType (B32V _) (AType (ATInt _)) = True
330isConstType (B64V _) (AType (ATInt _)) = True
331isConstType _ _ = False
333data Pat = PCon Bool Name Int [Pat]
336 | PSuc Pat -- special case for n+1 on Integer
337 | PReflected Name [Pat]
339 | PTyPat -- typecase, not allowed, inspect last
342-- If there are repeated variables, take the *last* one (could be name shadowing
343-- in a where clause, so take the most recent).
345toPats :: Bool -> Bool -> Term -> [Pat]
346toPats reflect tc f = reverse (toPat reflect tc (getArgs f)) where
347 getArgs (App f a) = a : getArgs f
350toPat :: Bool -> Bool -> [Term] -> [Pat]
351toPat reflect tc = map $ toPat' []
353 toPat' [_,_,arg] (P (DCon t a uniq) nm@(UN n) _)
355 = PCon uniq nm t [PAny, PAny, toPat' [] arg]
357 toPat' args (P (DCon t a uniq) nm@(NS (UN n) [own]) _)
358 | n == txt "Read" && own == txt "Ownership"
359 = PCon False nm t (map shareCons (map (toPat' []) args))
360 where shareCons (PCon _ n i ps) = PCon False n i (map shareCons ps)
363 toPat' args (P (DCon t a uniq) n _)
364 = PCon uniq n t $ map (toPat' []) args
367 toPat' [p, Constant (BI 1)] (P _ (UN pabi) _)
368 | pabi == txt "prim__addBigInt"
371 toPat' [] (P Bound n ty) = PV n ty
372 toPat' args (App f a) = toPat' (a : args) f
373 toPat' [] (Constant (AType _)) = PTyPat
374 toPat' [] (Constant StrType) = PTyPat
375 toPat' [] (Constant PtrType) = PTyPat
376 toPat' [] (Constant VoidType) = PTyPat
377 toPat' [] (Constant x) = PConst x
379 toPat' [] (Bind n (Pi t _) sc)
380 | reflect && noOccurrence n sc
381 = PReflected (sUN "->") [toPat' [] t, toPat' [] sc]
383 toPat' args (P _ n _)
385 = PReflected n $ map (toPat' []) args
390 fixedN IT16 = "Bits16"
391 fixedN IT32 = "Bits32"
392 fixedN IT64 = "Bits64"
395data Partition = Cons [Clause]
399isVarPat (PV _ _ : ps , _) = True
400isVarPat (PAny : ps , _) = True
401isVarPat (PTyPat : ps , _) = True
404isConPat (PCon _ _ _ _ : ps, _) = True
405isConPat (PReflected _ _ : ps, _) = True
406isConPat (PSuc _ : ps, _) = True
407isConPat (PConst _ : ps, _) = True
410partition :: [Clause] -> [Partition]
413 | isVarPat m = let (vars, rest) = span isVarPat ms in
414 Vars vars : partition rest
415 | isConPat m = let (cons, rest) = span isConPat ms in
416 Cons cons : partition rest
417partition xs = error $ "Partition " ++ show xs
419-- reorder the patterns so that the one with most distinct names
420-- comes next. Take rightmost first, otherwise (i.e. pick value rather
423-- The first argument means [(Name, IsInaccessible)].
425order :: [(Name, Bool)] -> [Clause] -> ([Name], [Clause])
426order [] cs = ([], cs)
427order ns' [] = (map fst ns', [])
428order ns' cs = let patnames = transpose (map (zip ns') (map fst cs))
429 -- only sort the arguments where there is no clash in
430 -- constructor tags between families, and no constructor/constant
431 -- clash, because otherwise we can't reliable make the
432 -- case distinction on evaluation
433 (patnames_ord, patnames_rest)
434 = Data.List.partition (noClash . map snd) patnames
435 -- note: sortBy . reverse is not nonsense because sortBy is stable
436 pats' = transpose (sortBy moreDistinct (reverse patnames_ord)
438 (getNOrder pats', zipWith rebuild pats' cs)
440 getNOrder [] = error $ "Failed order on " ++ show (map fst ns', cs)
441 getNOrder (c : _) = map (fst . fst) c
443 rebuild patnames clause = (map snd patnames, snd clause)
446 noClash (p : ps) = not (any (clashPat p) ps) && noClash ps
448 clashPat (PCon _ _ _ _) (PConst _) = True
449 clashPat (PConst _) (PCon _ _ _ _) = True
450 clashPat (PCon _ _ _ _) (PSuc _) = True
451 clashPat (PSuc _) (PCon _ _ _ _) = True
452 clashPat (PCon _ n i _) (PCon _ n' i' _) | i == i' = n /= n'
455 -- this compares (+isInaccessible, -numberOfCases)
456 moreDistinct xs ys = compare (snd . fst . head $ xs, numNames [] (map snd ys))
457 (snd . fst . head $ ys, numNames [] (map snd xs))
459 numNames xs (PCon _ n _ _ : ps)
460 | not (Left n `elem` xs) = numNames (Left n : xs) ps
461 numNames xs (PConst c : ps)
462 | not (Right c `elem` xs) = numNames (Right c : xs) ps
463 numNames xs (_ : ps) = numNames xs ps
464 numNames xs [] = length xs
466match :: [Name] -> [Clause] -> SC -- error case
468match [] (([], ret) : xs) err
469 = do (ts, v, ntys) <- get
470 put (ts ++ (map (fst.snd) xs), v, ntys)
472 Impossible -> return ImpossibleCase
473 tm -> return $ STerm tm -- run out of arguments
474match vs cs err = do let ps = partition cs
477mixture :: [Name] -> [Partition] -> SC -> CaseBuilder SC
478mixture vs [] err = return err
479mixture vs (Cons ms : ps) err = do fallthrough <- mixture vs ps err
480 conRule vs ms fallthrough
481mixture vs (Vars ms : ps) err = do fallthrough <- mixture vs ps err
482 varRule vs ms fallthrough
484-- Return the list of inaccessible arguments of a data constructor.
485inaccessibleArgs :: Name -> CaseBuilder [Int]
486inaccessibleArgs n = do
487 getInaccessiblePositions <- ask -- this function is the only thing in the environment
488 return $ getInaccessiblePositions n
490data ConType = CName Name Int -- named constructor
491 | CFn Name -- reflected function name
493 | CConst Const -- constant, not implemented yet
496data Group = ConGroup Bool -- Uniqueness flag
497 ConType -- Constructor
498 [([Pat], Clause)] -- arguments and rest of alternative
501conRule :: [Name] -> [Clause] -> SC -> CaseBuilder SC
502conRule (v:vs) cs err = do groups <- groupCons cs
503 caseGroups (v:vs) groups err
505caseGroups :: [Name] -> [Group] -> SC -> CaseBuilder SC
506caseGroups (v:vs) gs err = do g <- altGroups gs
507 return $ Case (getShared gs) v (sort g)
509 getShared (ConGroup True _ _ : _) = Updatable
512 altGroups [] = return [DefaultCase err]
514 altGroups (ConGroup _ (CName n i) args : cs)
515 = (:) <$> altGroup n i args <*> altGroups cs
517 altGroups (ConGroup _ (CFn n) args : cs)
518 = (:) <$> altFnGroup n args <*> altGroups cs
520 altGroups (ConGroup _ CSuc args : cs)
521 = (:) <$> altSucGroup args <*> altGroups cs
523 altGroups (ConGroup _ (CConst c) args : cs)
524 = (:) <$> altConstGroup c args <*> altGroups cs
527 = do inacc <- inaccessibleArgs n
528 (newVars, accVars, inaccVars, nextCs) <- argsToAlt inacc args
529 matchCs <- match (accVars ++ vs ++ inaccVars) nextCs err
530 return $ ConCase n i newVars matchCs
532 altFnGroup n args = do (newVars, _, [], nextCs) <- argsToAlt [] args
533 matchCs <- match (newVars ++ vs) nextCs err
534 return $ FnCase n newVars matchCs
536 altSucGroup args = do ([newVar], _, [], nextCs) <- argsToAlt [] args
537 matchCs <- match (newVar:vs) nextCs err
538 return $ SucCase newVar matchCs
540 altConstGroup n args = do (_, _, [], nextCs) <- argsToAlt [] args
541 matchCs <- match vs nextCs err
542 return $ ConstCase n matchCs
545-- * names of all variables arising from match
546-- * names of accessible variables (subset of all variables)
547-- * names of inaccessible variables (subset of all variables)
548-- * clauses corresponding to (accVars ++ origVars ++ inaccVars)
549argsToAlt :: [Int] -> [([Pat], Clause)] -> CaseBuilder ([Name], [Name], [Name], [Clause])
550argsToAlt _ [] = return ([], [], [], [])
551argsToAlt inacc rs@((r, m) : rest) = do
552 newVars <- getNewVars r
553 let (accVars, inaccVars) = partitionAcc newVars
554 return (newVars, accVars, inaccVars, addRs rs)
556 -- Create names for new variables arising from the given patterns.
557 getNewVars :: [Pat] -> CaseBuilder [Name]
558 getNewVars [] = return []
559 getNewVars ((PV n t) : ns) = do v <- getVar "e"
562 -- Record the type of the variable.
564 -- It seems that the ordering is not important
565 -- and we can put (v,t) always in front of "ntys"
566 -- (the varName-type pairs seem to represent a mapping).
568 -- The code that reads this is currently
569 -- commented out, anyway.
571 put (cs, i, (v, t) : ntys)
575 getNewVars (PAny : ns) = (:) <$> getVar "i" <*> getNewVars ns
576 getNewVars (PTyPat : ns) = (:) <$> getVar "t" <*> getNewVars ns
577 getNewVars (_ : ns) = (:) <$> getVar "e" <*> getNewVars ns
579 -- Partition a list of things into (accessible, inaccessible) things,
580 -- according to the list of inaccessible indices.
582 ( [x | (i,x) <- zip [0..] xs, i `notElem` inacc]
583 , [x | (i,x) <- zip [0..] xs, i `elem` inacc]
587 addRs ((r, (ps, res)) : rs) = ((acc++ps++inacc, res) : addRs rs)
589 (acc, inacc) = partitionAcc r
591 uniq i (UN n) = MN i n
594getVar :: String -> CaseBuilder Name
595getVar b = do (t, v, ntys) <- get; put (t, v+1, ntys); return (sMN v b)
597groupCons :: [Clause] -> CaseBuilder [Group]
598groupCons cs = gc [] cs
600 gc acc [] = return acc
601 gc acc ((p : ps, res) : cs) =
602 do acc' <- addGroup p ps res acc
604 addGroup p ps res acc = case p of
605 PCon uniq con i args -> return $ addg uniq (CName con i) args (ps, res) acc
606 PConst cval -> return $ addConG cval (ps, res) acc
607 PSuc n -> return $ addg False CSuc [n] (ps, res) acc
608 PReflected fn args -> return $ addg False (CFn fn) args (ps, res) acc
609 pat -> fail $ show pat ++ " is not a constructor or constant (can't happen)"
611 addg uniq c conargs res []
612 = [ConGroup uniq c [(conargs, res)]]
613 addg uniq c conargs res (g@(ConGroup _ c' cs):gs)
614 | c == c' = ConGroup uniq c (cs ++ [(conargs, res)]) : gs
615 | otherwise = g : addg uniq c conargs res gs
617 addConG con res [] = [ConGroup False (CConst con) [([], res)]]
618 addConG con res (g@(ConGroup False (CConst n) cs) : gs)
619 | con == n = ConGroup False (CConst n) (cs ++ [([], res)]) : gs
620-- | otherwise = g : addConG con res gs
621 addConG con res (g : gs) = g : addConG con res gs
623varRule :: [Name] -> [Clause] -> SC -> CaseBuilder SC
624varRule (v : vs) alts err =
625 do alts' <- mapM (repVar v) alts
628 repVar v (PV p ty : ps , (lhs, res))
629 = do (cs, i, ntys) <- get
630 put (cs, i, (v, ty) : ntys)
631 return (ps, (lhs, subst p (P Bound v ty) res))
632 repVar v (PAny : ps , res) = return (ps, res)
633 repVar v (PTyPat : ps , res) = return (ps, res)
635-- fix: case e of S k -> f (S k) ==> case e of S k -> f e
637depatt :: [Name] -> SC -> SC
638depatt ns tm = dp [] tm
640 dp ms (STerm tm) = STerm (applyMaps ms tm)
641 dp ms (Case up x alts) = Case up x (map (dpa ms x) alts)
644 dpa ms x (ConCase n i args sc)
645 = ConCase n i args (dp ((x, (n, args)) : ms) sc)
646 dpa ms x (FnCase n args sc)
647 = FnCase n args (dp ((x, (n, args)) : ms) sc)
648 dpa ms x (ConstCase c sc) = ConstCase c (dp ms sc)
649 dpa ms x (SucCase n sc) = SucCase n (dp ms sc)
650 dpa ms x (DefaultCase sc) = DefaultCase (dp ms sc)
652 applyMaps ms f@(App _ _)
653 | (P nt cn pty, args) <- unApply f
654 = let args' = map (applyMaps ms) args in
655 applyMap ms nt cn pty args'
657 applyMap [] nt cn pty args' = mkApp (P nt cn pty) args'
658 applyMap ((x, (n, args)) : ms) nt cn pty args'
659 | and ((length args == length args') :
660 (n == cn) : zipWith same args args') = P Ref x Erased
661 | otherwise = applyMap ms nt cn pty args'
662 same n (P _ n' _) = n == n'
665 applyMaps ms (App f a) = App (applyMaps ms f) (applyMaps ms a)
668-- FIXME: Do this for SucCase too
669prune :: Bool -- ^ Convert single branches to projections (only useful at runtime)
671prune proj (Case up n alts) = case alts' of
674 -- Projection transformations prevent us from seeing some uses of ctor fields
675 -- because they delete information about which ctor is being used.
677 -- f (X x) = ... x ...
681 -- Hence, we disable this step.
682 -- TODO: re-enable this in toIR
684 -- as@[ConCase cn i args sc]
685 -- | proj -> mkProj n 0 args (prune proj sc)
686 -- mkProj n i xs sc = foldr (\x -> projRep x n i) sc xs
688 -- If none of the args are used in the sc, however, we can just replace it
690 as@[ConCase cn i args sc]
691 | proj -> let sc' = prune proj sc in
692 if any (isUsed sc') args
693 then Case up n [ConCase cn i args sc']
698 -> projRep cn n (-1) $ prune proj sc
703 -- Bit of a hack here! The default case will always be 0, make sure
704 -- it gets caught first.
705 [s@(SucCase _ _), DefaultCase dc]
706 -> Case up n [ConstCase (BI 0) dc, s]
710 alts' = filter (not . erased) $ map pruneAlt alts
712 pruneAlt (ConCase cn i ns sc) = ConCase cn i ns (prune proj sc)
713 pruneAlt (FnCase cn ns sc) = FnCase cn ns (prune proj sc)
714 pruneAlt (ConstCase c sc) = ConstCase c (prune proj sc)
715 pruneAlt (SucCase n sc) = SucCase n (prune proj sc)
716 pruneAlt (DefaultCase sc) = DefaultCase (prune proj sc)
718 erased (DefaultCase (STerm Erased)) = True
719 erased (DefaultCase ImpossibleCase) = True
722 projRep :: Name -> Name -> Int -> SC -> SC
723 projRep arg n i (Case up x alts) | x == arg
724 = ProjCase (Proj (P Bound n Erased) i) $ map (projRepAlt arg n i) alts
725 projRep arg n i (Case up x alts)
726 = Case up x (map (projRepAlt arg n i) alts)
727 projRep arg n i (ProjCase t alts)
728 = ProjCase (projRepTm arg n i t) $ map (projRepAlt arg n i) alts
729 projRep arg n i (STerm t) = STerm (projRepTm arg n i t)
730 projRep arg n i c = c
732 projRepAlt arg n i (ConCase cn t args rhs)
733 = ConCase cn t args (projRep arg n i rhs)
734 projRepAlt arg n i (FnCase cn args rhs)
735 = FnCase cn args (projRep arg n i rhs)
736 projRepAlt arg n i (ConstCase t rhs)
737 = ConstCase t (projRep arg n i rhs)
738 projRepAlt arg n i (SucCase sn rhs)
739 = SucCase sn (projRep arg n i rhs)
740 projRepAlt arg n i (DefaultCase rhs)
741 = DefaultCase (projRep arg n i rhs)
743 projRepTm arg n i t = subst arg (Proj (P Bound n Erased) i) t
747stripLambdas :: CaseDef -> CaseDef
748stripLambdas (CaseDef ns (STerm (Bind x (Lam _) sc)) tm)
749 = stripLambdas (CaseDef (ns ++ [x]) (STerm (instantiate (P Bound x Erased) sc)) tm)
752substSC :: Name -> Name -> SC -> SC
753substSC n repl (Case up n' alts)
754 | n == n' = Case up repl (map (substAlt n repl) alts)
755 | otherwise = Case up n' (map (substAlt n repl) alts)
756substSC n repl (STerm t) = STerm $ subst n (P Bound repl Erased) t
757substSC n repl (UnmatchedCase errmsg) = UnmatchedCase errmsg
758substSC n repl ImpossibleCase = ImpossibleCase
759substSC n repl sc = error $ "unsupported in substSC: " ++ show sc
761substAlt :: Name -> Name -> CaseAlt -> CaseAlt
762substAlt n repl (ConCase cn a ns sc) = ConCase cn a ns (substSC n repl sc)
763substAlt n repl (FnCase fn ns sc) = FnCase fn ns (substSC n repl sc)
764substAlt n repl (ConstCase c sc) = ConstCase c (substSC n repl sc)
765substAlt n repl (SucCase n' sc)
766 | n == n' = SucCase n (substSC n repl sc)
767 | otherwise = SucCase n' (substSC n repl sc)
768substAlt n repl (DefaultCase sc) = DefaultCase (substSC n repl sc)
770-- mkForce n' n t updates the tree t under the assumption that
771-- n' = force n (so basically updating n to n')
772mkForce :: Name -> Name -> SC -> SC
775 mkForceSC n arg (Case up x alts) | x == arg
776 = Case up n $ map (mkForceAlt n arg) alts
778 mkForceSC n arg (Case up x alts)
779 = Case up x (map (mkForceAlt n arg) alts)
781 mkForceSC n arg (ProjCase t alts)
782 = ProjCase t $ map (mkForceAlt n arg) alts
784 mkForceSC n arg c = c
786 mkForceAlt n arg (ConCase cn t args rhs)
787 = ConCase cn t args (mkForceSC n arg rhs)
788 mkForceAlt n arg (FnCase cn args rhs)
789 = FnCase cn args (mkForceSC n arg rhs)
790 mkForceAlt n arg (ConstCase t rhs)
791 = ConstCase t (mkForceSC n arg rhs)
792 mkForceAlt n arg (SucCase sn rhs)
793 = SucCase sn (mkForceSC n arg rhs)
794 mkForceAlt n arg (DefaultCase rhs)
795 = DefaultCase (mkForceSC n arg rhs)
797 forceTm n arg t = subst n arg t
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list