1{-# LANGUAGE PatternGuards, DeriveFunctor, TypeSynonymInstances #-}
3module Core.CaseTree(CaseDef(..), SC, SC'(..), CaseAlt, CaseAlt'(..),
5 simpleCase, small, namesUsed, findCalls, findUsedArgs) where
9import Control.Monad.State
11import Data.List hiding (partition)
14data CaseDef = CaseDef [Name] SC [Term]
17data SC' t = Case Name [CaseAlt' t] -- ^ invariant: lowest tags first
18 | ProjCase t [CaseAlt' t] -- ^ special case for projections
20 | UnmatchedCase String -- ^ error message
21 | ImpossibleCase -- ^ already checked to be impossible
22 deriving (Eq, Ord, Functor)
24deriving instance Binary SC
29data CaseAlt' t = ConCase Name Int [Name] (SC' t)
30 | FnCase Name [Name] (SC' t) -- ^ reflection function
31 | ConstCase Const (SC' t)
32 | SucCase Name (SC' t)
34 deriving (Show, Eq, Ord, Functor)
36deriving instance Binary CaseAlt
39type CaseAlt = CaseAlt' Term
41instance Show t => Show (SC' t) where
44 show' i (Case n alts) = "case " ++ show n ++ " of\n" ++ indent i ++
45 showSep ("\n" ++ indent i) (map (showA i) alts)
46 show' i (ProjCase tm alts) = "case " ++ show tm ++ " of " ++
47 showSep ("\n" ++ indent i) (map (showA i) alts)
48 show' i (STerm tm) = show tm
49 show' i (UnmatchedCase str) = "error " ++ show str
50 show' i ImpossibleCase = "impossible"
52 indent i = concat $ take i (repeat " ")
54 showA i (ConCase n t args sc)
55 = show n ++ "(" ++ showSep (", ") (map show args) ++ ") => "
57 showA i (FnCase n args sc)
58 = "FN " ++ show n ++ "(" ++ showSep (", ") (map show args) ++ ") => "
60 showA i (ConstCase t sc)
61 = show t ++ " => " ++ show' (i+1) sc
62 showA i (SucCase n sc)
63 = show n ++ "+1 => " ++ show' (i+1) sc
64 showA i (DefaultCase sc)
65 = "_ => " ++ show' (i+1) sc
69type Clause = ([Pat], (Term, Term))
70type CS = ([Term], Int)
72instance TermSize SC where
73 termsize n (Case n' as) = termsize n as
74 termsize n (ProjCase n' as) = termsize n as
75 termsize n (STerm t) = termsize n t
78instance TermSize CaseAlt where
79 termsize n (ConCase _ _ _ s) = termsize n s
80 termsize n (FnCase _ _ s) = termsize n s
81 termsize n (ConstCase _ s) = termsize n s
82 termsize n (SucCase _ s) = termsize n s
83 termsize n (DefaultCase s) = termsize n s
85-- simple terms can be inlined trivially - good for primitives in particular
86-- To avoid duplicating work, don't inline something which uses one
87-- of its arguments in more than one place
89small :: Name -> [Name] -> SC -> Bool
90small n args t = let as = findAllUsedArgs t args in
91 length as == length (nub as) &&
94namesUsed :: SC -> [Name]
95namesUsed sc = nub $ nu' [] sc where
96 nu' ps (Case n alts) = nub (concatMap (nua ps) alts) \\ [n]
97 nu' ps (ProjCase t alts) = nub $ (nut ps t ++
98 (concatMap (nua ps) alts))
99 nu' ps (STerm t) = nub $ nut ps t
102 nua ps (ConCase n i args sc) = nub (nu' (ps ++ args) sc) \\ args
103 nua ps (FnCase n args sc) = nub (nu' (ps ++ args) sc) \\ args
104 nua ps (ConstCase _ sc) = nu' ps sc
105 nua ps (SucCase _ sc) = nu' ps sc
106 nua ps (DefaultCase sc) = nu' ps sc
108 nut ps (P _ n _) | n `elem` ps = []
110 nut ps (App f a) = nut ps f ++ nut ps a
111 nut ps (Proj t _) = nut ps t
112 nut ps (Bind n (Let t v) sc) = nut ps v ++ nut (n:ps) sc
113 nut ps (Bind n b sc) = nut (n:ps) sc
116-- Return all called functions, and which arguments are used in each argument position
117-- for the call, in order to help reduce compilation time, and trace all unused
120findCalls :: SC -> [Name] -> [(Name, [[Name]])]
121findCalls sc topargs = nub $ nu' topargs sc where
122 nu' ps (Case n alts) = nub (concatMap (nua (n : ps)) alts)
123 nu' ps (ProjCase t alts) = nub (nut ps t ++ concatMap (nua ps) alts)
124 nu' ps (STerm t) = nub $ nut ps t
127 nua ps (ConCase n i args sc) = nub (nu' (ps ++ args) sc)
128 nua ps (FnCase n args sc) = nub (nu' (ps ++ args) sc)
129 nua ps (ConstCase _ sc) = nu' ps sc
130 nua ps (SucCase _ sc) = nu' ps sc
131 nua ps (DefaultCase sc) = nu' ps sc
133 nut ps (P Ref n _) | n `elem` ps = []
134 | otherwise = [(n, [])] -- tmp
136 | (P Ref n _, args) <- unApply fn
137 = if n `elem` ps then nut ps f ++ nut ps a
138 else [(n, map argNames args)] ++ concatMap (nut ps) args
139 | (P (TCon _ _) n _, _) <- unApply fn = []
140 | otherwise = nut ps f ++ nut ps a
141 nut ps (Bind n (Let t v) sc) = nut ps v ++ nut (n:ps) sc
142 nut ps (Proj t _) = nut ps t
143 nut ps (Bind n b sc) = nut (n:ps) sc
146 argNames tm = let ns = directUse tm in
147 filter (\x -> x `elem` ns) topargs
149-- Find names which are used directly (i.e. not in a function call) in a term
151directUse :: Eq n => TT n -> [n]
152directUse (P _ n _) = [n]
153directUse (Bind n (Let t v) sc) = nub $ directUse v ++ (directUse sc \\ [n])
155directUse (Bind n b sc) = nub $ directUse (binderTy b) ++ (directUse sc \\ [n])
156directUse fn@(App f a)
157 | (P Ref n _, args) <- unApply fn = [] -- need to know what n does with them
158 | otherwise = nub $ directUse f ++ directUse a
159directUse (Proj x i) = nub $ directUse x
162-- Find all directly used arguments (i.e. used but not in function calls)
164findUsedArgs :: SC -> [Name] -> [Name]
165findUsedArgs sc topargs = nub (findAllUsedArgs sc topargs)
167findAllUsedArgs sc topargs = filter (\x -> x `elem` topargs) (nu' sc) where
168 nu' (Case n alts) = n : concatMap nua alts
169 nu' (ProjCase t alts) = directUse t ++ concatMap nua alts
170 nu' (STerm t) = directUse t
173 nua (ConCase n i args sc) = nu' sc
174 nua (FnCase n args sc) = nu' sc
175 nua (ConstCase _ sc) = nu' sc
176 nua (SucCase _ sc) = nu' sc
177 nua (DefaultCase sc) = nu' sc
179data Phase = CompileTime | RunTime
182-- Generate a simple case tree
185simpleCase :: Bool -> Bool -> Bool ->
186 Phase -> FC -> [([Name], Term, Term)] ->
188simpleCase tc cover reflect phase fc cs
189 = sc' tc cover phase fc (filter (\(_, _, r) ->
194 sc' tc cover phase fc []
195 = return $ CaseDef [] (UnmatchedCase "No pattern clauses") []
196 sc' tc cover phase fc cs
197 = let proj = phase == RunTime
198 pats = map (\ (avs, l, r) ->
199 (avs, toPats reflect tc l, (l, r))) cs
200 chkPats = mapM chkAccessible pats in
203 let numargs = length (fst (head pats))
204 ns = take numargs args
205 (ns', ps') = order ns pats
206 (tree, st) = runState
207 (match ns' ps' (defaultCase cover)) ([], numargs)
208 t = CaseDef ns (prune proj (depatt ns' tree)) (fst st) in
209 if proj then return (stripLambdas t) else return t
210 Error err -> Error (At fc err)
211 where args = map (\i -> MN i "e") [0..]
212 defaultCase True = STerm Erased
213 defaultCase False = UnmatchedCase "Error"
215 chkAccessible (avs, l, c)
216 | phase == RunTime || reflect = return (l, c)
217 | otherwise = do mapM_ (acc l) avs
220 acc [] n = Error (Inaccessible n)
221 acc (PV x : xs) n | x == n = OK ()
222 acc (PCon _ _ ps : xs) n = acc (ps ++ xs) n
223 acc (PSuc p : xs) n = acc (p : xs) n
224 acc (_ : xs) n = acc xs n
226data Pat = PCon Name Int [Pat]
229 | PSuc Pat -- special case for n+1 on Integer
230 | PReflected Name [Pat]
234-- If there are repeated variables, take the *last* one (could be name shadowing
235-- in a where clause, so take the most recent).
237toPats :: Bool -> Bool -> Term -> [Pat]
238toPats reflect tc f = reverse (toPat reflect tc (getArgs f)) where
239 getArgs (App f a) = a : getArgs f
242toPat :: Bool -> Bool -> [Term] -> [Pat]
243toPat reflect tc tms = evalState (mapM (\x -> toPat' x []) tms) []
245 toPat' (P (DCon t a) n _) args = do args' <- mapM (\x -> toPat' x []) args
246 return $ PCon n t args'
248 toPat' (P _ (UN "prim__addBigInt") _)
250 = do p' <- toPat' p []
253 toPat' (P (TCon t a) n _) args | tc
254 = do args' <- mapM (\x -> toPat' x []) args
255 return $ PCon n t args'
256 toPat' (Constant (AType (ATInt ITNative))) []
257 | tc = return $ PCon (UN "Int") 1 []
258 toPat' (Constant (AType ATFloat)) [] | tc = return $ PCon (UN "Float") 2 []
259 toPat' (Constant (AType (ATInt ITChar))) [] | tc = return $ PCon (UN "Char") 3 []
260 toPat' (Constant StrType) [] | tc = return $ PCon (UN "String") 4 []
261 toPat' (Constant PtrType) [] | tc = return $ PCon (UN "Ptr") 5 []
262 toPat' (Constant (AType (ATInt ITBig))) []
263 | tc = return $ PCon (UN "Integer") 6 []
264 toPat' (Constant (AType (ATInt (ITFixed n)))) []
265 | tc = return $ PCon (UN (fixedN n)) (7 + fromEnum n) [] -- 7-10 inclusive
266 toPat' (P Bound n _) [] = do ns <- get
271 toPat' (App f a) args = toPat' f (a : args)
272 toPat' (Constant x) [] = return $ PConst x
273 toPat' (Bind n (Pi t) sc) [] | reflect && noOccurrence n sc
274 = do t' <- toPat' t []
276 return $ PReflected (UN "->") (t':sc':[])
277 toPat' (P _ n _) args | reflect
278 = do args' <- mapM (\x -> toPat' x []) args
279 return $ PReflected n args'
280 toPat' t _ = return PAny
283 fixedN IT16 = "Bits16"
284 fixedN IT32 = "Bits32"
285 fixedN IT64 = "Bits64"
288data Partition = Cons [Clause]
292isVarPat (PV _ : ps , _) = True
293isVarPat (PAny : ps , _) = True
296isConPat (PCon _ _ _ : ps, _) = True
297isConPat (PReflected _ _ : ps, _) = True
298isConPat (PSuc _ : ps, _) = True
299isConPat (PConst _ : ps, _) = True
302partition :: [Clause] -> [Partition]
305 | isVarPat m = let (vars, rest) = span isVarPat ms in
306 Vars vars : partition rest
307 | isConPat m = let (cons, rest) = span isConPat ms in
308 Cons cons : partition rest
309partition xs = error $ "Partition " ++ show xs
311-- reorder the patterns so that the one with most distinct names
312-- comes next. Take rightmost first, otherwise (i.e. pick value rather
315order :: [Name] -> [Clause] -> ([Name], [Clause])
316order [] cs = ([], cs)
317order ns [] = (ns, [])
318order ns cs = let patnames = transpose (map (zip ns) (map fst cs))
319 pats' = transpose (sortBy moreDistinct (reverse patnames)) in
320 (getNOrder pats', zipWith rebuild pats' cs)
322 getNOrder [] = error $ "Failed order on " ++ show (ns, cs)
323 getNOrder (c : _) = map fst c
325 rebuild patnames clause = (map snd patnames, snd clause)
327 moreDistinct xs ys = compare (numNames [] (map snd ys))
328 (numNames [] (map snd xs))
330 numNames xs (PCon n _ _ : ps)
331 | not (Left n `elem` xs) = numNames (Left n : xs) ps
332 numNames xs (PConst c : ps)
333 | not (Right c `elem` xs) = numNames (Right c : xs) ps
334 numNames xs (_ : ps) = numNames xs ps
335 numNames xs [] = length xs
337match :: [Name] -> [Clause] -> SC -- error case
339match [] (([], ret) : xs) err
341 put (ts ++ (map (fst.snd) xs), v)
343 Impossible -> return ImpossibleCase
344 tm -> return $ STerm tm -- run out of arguments
345match vs cs err = do let ps = partition cs
348mixture :: [Name] -> [Partition] -> SC -> State CS SC
349mixture vs [] err = return err
350mixture vs (Cons ms : ps) err = do fallthrough <- mixture vs ps err
351 conRule vs ms fallthrough
352mixture vs (Vars ms : ps) err = do fallthrough <- mixture vs ps err
353 varRule vs ms fallthrough
355data ConType = CName Name Int -- named constructor
356 | CFn Name -- reflected function name
358 | CConst Const -- constant, not implemented yet
361data Group = ConGroup ConType -- Constructor
362 [([Pat], Clause)] -- arguments and rest of alternative
365conRule :: [Name] -> [Clause] -> SC -> State CS SC
366conRule (v:vs) cs err = do groups <- groupCons cs
367 caseGroups (v:vs) groups err
369caseGroups :: [Name] -> [Group] -> SC -> State CS SC
370caseGroups (v:vs) gs err = do g <- altGroups gs
371 return $ Case v (sort g)
373 altGroups [] = return [DefaultCase err]
374 altGroups (ConGroup (CName n i) args : cs)
375 = do g <- altGroup n i args
378 altGroups (ConGroup (CFn n) args : cs)
379 = do g <- altFnGroup n args
382 altGroups (ConGroup CSuc args : cs)
383 = do g <- altSucGroup args
386 altGroups (ConGroup (CConst c) args : cs)
387 = do g <- altConstGroup c args
391 altGroup n i gs = do (newArgs, nextCs) <- argsToAlt gs
392 matchCs <- match (newArgs ++ vs) nextCs err
393 return $ ConCase n i newArgs matchCs
394 altFnGroup n gs = do (newArgs, nextCs) <- argsToAlt gs
395 matchCs <- match (newArgs ++ vs) nextCs err
396 return $ FnCase n newArgs matchCs
397 altSucGroup gs = do ([newArg], nextCs) <- argsToAlt gs
398 matchCs <- match (newArg:vs) nextCs err
399 return $ SucCase newArg matchCs
400 altConstGroup n gs = do (_, nextCs) <- argsToAlt gs
401 matchCs <- match vs nextCs err
402 return $ ConstCase n matchCs
404argsToAlt :: [([Pat], Clause)] -> State CS ([Name], [Clause])
405argsToAlt [] = return ([], [])
406argsToAlt rs@((r, m) : rest)
407 = do newArgs <- getNewVars r
408 return (newArgs, addRs rs)
410 getNewVars [] = return []
411 getNewVars ((PV n) : ns) = do v <- getVar "e"
414 getNewVars (PAny : ns) = do v <- getVar "i"
417 getNewVars (_ : ns) = do v <- getVar "e"
421 addRs ((r, (ps, res)) : rs) = ((r++ps, res) : addRs rs)
423 uniq i (UN n) = MN i n
426getVar :: String -> State CS Name
427getVar b = do (t, v) <- get; put (t, v+1); return (MN v b)
429groupCons :: [Clause] -> State CS [Group]
430groupCons cs = gc [] cs
432 gc acc [] = return acc
433 gc acc ((p : ps, res) : cs) =
434 do acc' <- addGroup p ps res acc
436 addGroup p ps res acc = case p of
437 PCon con i args -> return $ addg (CName con i) args (ps, res) acc
438 PConst cval -> return $ addConG cval (ps, res) acc
439 PSuc n -> return $ addg CSuc [n] (ps, res) acc
440 PReflected fn args -> return $ addg (CFn fn) args (ps, res) acc
441 pat -> fail $ show pat ++ " is not a constructor or constant (can't happen)"
443 addg c conargs res []
444 = [ConGroup c [(conargs, res)]]
445 addg c conargs res (g@(ConGroup c' cs):gs)
446 | c == c' = ConGroup c (cs ++ [(conargs, res)]) : gs
447 | otherwise = g : addg c conargs res gs
449 addConG con res [] = [ConGroup (CConst con) [([], res)]]
450 addConG con res (g@(ConGroup (CConst n) cs) : gs)
451 | con == n = ConGroup (CConst n) (cs ++ [([], res)]) : gs
452-- | otherwise = g : addConG con res gs
453 addConG con res (g : gs) = g : addConG con res gs
455varRule :: [Name] -> [Clause] -> SC -> State CS SC
456varRule (v : vs) alts err =
457 do let alts' = map (repVar v) alts
460 repVar v (PV p : ps , (lhs, res))
461 = (ps, (lhs, subst p (P Bound v Erased) res))
462 repVar v (PAny : ps , res) = (ps, res)
464-- fix: case e of S k -> f (S k) ==> case e of S k -> f e
466depatt :: [Name] -> SC -> SC
467depatt ns tm = dp [] tm
469 dp ms (STerm tm) = STerm (applyMaps ms tm)
470 dp ms (Case x alts) = Case x (map (dpa ms x) alts)
473 dpa ms x (ConCase n i args sc)
474 = ConCase n i args (dp ((x, (n, args)) : ms) sc)
475 dpa ms x (FnCase n args sc)
476 = FnCase n args (dp ((x, (n, args)) : ms) sc)
477 dpa ms x (ConstCase c sc) = ConstCase c (dp ms sc)
478 dpa ms x (SucCase n sc) = SucCase n (dp ms sc)
479 dpa ms x (DefaultCase sc) = DefaultCase (dp ms sc)
481 applyMaps ms f@(App _ _)
482 | (P nt cn pty, args) <- unApply f
483 = let args' = map (applyMaps ms) args in
484 applyMap ms nt cn pty args'
486 applyMap [] nt cn pty args' = mkApp (P nt cn pty) args'
487 applyMap ((x, (n, args)) : ms) nt cn pty args'
488 | and ((length args == length args') :
489 (n == cn) : zipWith same args args') = P Ref x Erased
490 | otherwise = applyMap ms nt cn pty args'
491 same n (P _ n' _) = n == n'
494 applyMaps ms (App f a) = App (applyMaps ms f) (applyMaps ms a)
497-- FIXME: Do this for SucCase too
498prune :: Bool -- ^ Convert single branches to projections (only useful at runtime)
500prune proj (Case n alts)
501 = let alts' = filter notErased (map pruneAlt alts) in
504 as@[ConCase cn i args sc] -> if proj then mkProj n 0 args sc
506 as@[SucCase cn sc] -> if proj then mkProj n (-1) [cn] sc
508 as@[ConstCase _ sc] -> prune proj sc
509 -- Bit of a hack here! The default case will always be 0, make sure
510 -- it gets caught first.
511 [s@(SucCase _ _), DefaultCase dc]
512 -> Case n [ConstCase (BI 0) dc, s]
514 where pruneAlt (ConCase cn i ns sc) = ConCase cn i ns (prune proj sc)
515 pruneAlt (FnCase cn ns sc) = FnCase cn ns (prune proj sc)
516 pruneAlt (ConstCase c sc) = ConstCase c (prune proj sc)
517 pruneAlt (SucCase n sc) = SucCase n (prune proj sc)
518 pruneAlt (DefaultCase sc) = DefaultCase (prune proj sc)
520 notErased (DefaultCase (STerm Erased)) = False
521 notErased (DefaultCase ImpossibleCase) = False
524 mkProj n i [] sc = prune proj sc
525 mkProj n i (x : xs) sc = mkProj n (i + 1) xs (projRep x n i sc)
527 -- Change every 'n' in sc to 'n-1'
528-- mkProjS n cn sc = prune proj (fmap projn sc) where
529-- projn pn@(P _ n' _)
530-- | cn == n' = App (App (P Ref (UN "prim__subBigInt") Erased)
531-- (P Bound n Erased)) (Constant (BI 1))
534 projRep :: Name -> Name -> Int -> SC -> SC
535 projRep arg n i (Case x alts)
536 | x == arg = ProjCase (Proj (P Bound n Erased) i)
537 (map (projRepAlt arg n i) alts)
538 | otherwise = Case x (map (projRepAlt arg n i) alts)
539 projRep arg n i (ProjCase t alts)
540 = ProjCase (projRepTm arg n i t) (map (projRepAlt arg n i) alts)
541 projRep arg n i (STerm t) = STerm (projRepTm arg n i t)
542 projRep arg n i c = c -- unmatched
544 projRepAlt arg n i (ConCase cn t args rhs)
545 = ConCase cn t args (projRep arg n i rhs)
546 projRepAlt arg n i (FnCase cn args rhs)
547 = FnCase cn args (projRep arg n i rhs)
548 projRepAlt arg n i (ConstCase t rhs)
549 = ConstCase t (projRep arg n i rhs)
550 projRepAlt arg n i (SucCase sn rhs)
551 = SucCase sn (projRep arg n i rhs)
552 projRepAlt arg n i (DefaultCase rhs)
553 = DefaultCase (projRep arg n i rhs)
555 projRepTm arg n i t = subst arg (Proj (P Bound n Erased) i) t
559stripLambdas :: CaseDef -> CaseDef
560stripLambdas (CaseDef ns (STerm (Bind x (Lam _) sc)) tm)
561 = stripLambdas (CaseDef (ns ++ [x]) (STerm (instantiate (P Bound x Erased) sc)) tm)
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