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 | ConstCase Const (SC' t)
32 deriving (Show, Eq, Ord, Functor)
34deriving instance Binary CaseAlt
37type CaseAlt = CaseAlt' Term
39instance Show t => Show (SC' t) where
42 show' i (Case n alts) = "case " ++ show n ++ " of\n" ++ indent i ++
43 showSep ("\n" ++ indent i) (map (showA i) alts)
44 show' i (ProjCase tm alts) = "case " ++ show tm ++ " of " ++
45 showSep ("\n" ++ indent i) (map (showA i) alts)
46 show' i (STerm tm) = show tm
47 show' i (UnmatchedCase str) = "error " ++ show str
48 show' i ImpossibleCase = "impossible"
50 indent i = concat $ take i (repeat " ")
52 showA i (ConCase n t args sc)
53 = show n ++ "(" ++ showSep (", ") (map show args) ++ ") => "
55 showA i (ConstCase t sc)
56 = show t ++ " => " ++ show' (i+1) sc
57 showA i (DefaultCase sc)
58 = "_ => " ++ show' (i+1) sc
62type Clause = ([Pat], (Term, Term))
63type CS = ([Term], Int)
65instance TermSize SC where
66 termsize n (Case n' as) = termsize n as
67 termsize n (ProjCase n' as) = termsize n as
68 termsize n (STerm t) = termsize n t
71instance TermSize CaseAlt where
72 termsize n (ConCase _ _ _ s) = termsize n s
73 termsize n (ConstCase _ s) = termsize n s
74 termsize n (DefaultCase s) = termsize n s
76-- simple terms can be inlined trivially - good for primitives in particular
77-- To avoid duplicating work, don't inline something which uses one
78-- of its arguments in more than one place
80small :: Name -> [Name] -> SC -> Bool
81small n args t = let as = findAllUsedArgs t args in
82 length as == length (nub as) &&
85namesUsed :: SC -> [Name]
86namesUsed sc = nub $ nu' [] sc where
87 nu' ps (Case n alts) = nub (concatMap (nua ps) alts) \\ [n]
88 nu' ps (ProjCase t alts) = nub $ (nut ps t ++
89 (concatMap (nua ps) alts))
90 nu' ps (STerm t) = nub $ nut ps t
93 nua ps (ConCase n i args sc) = nub (nu' (ps ++ args) sc) \\ args
94 nua ps (ConstCase _ sc) = nu' ps sc
95 nua ps (DefaultCase sc) = nu' ps sc
97 nut ps (P _ n _) | n `elem` ps = []
99 nut ps (App f a) = nut ps f ++ nut ps a
100 nut ps (Proj t _) = nut ps t
101 nut ps (Bind n (Let t v) sc) = nut ps v ++ nut (n:ps) sc
102 nut ps (Bind n b sc) = nut (n:ps) sc
105-- Return all called functions, and which arguments are used in each argument position
106-- for the call, in order to help reduce compilation time, and trace all unused
109findCalls :: SC -> [Name] -> [(Name, [[Name]])]
110findCalls sc topargs = nub $ nu' topargs sc where
111 nu' ps (Case n alts) = nub (concatMap (nua (n : ps)) alts)
112 nu' ps (ProjCase t alts) = nub (nut ps t ++ concatMap (nua ps) alts)
113 nu' ps (STerm t) = nub $ nut ps t
116 nua ps (ConCase n i args sc) = nub (nu' (ps ++ args) sc)
117 nua ps (ConstCase _ sc) = nu' ps sc
118 nua ps (DefaultCase sc) = nu' ps sc
120 nut ps (P Ref n _) | n `elem` ps = []
121 | otherwise = [(n, [])] -- tmp
123 | (P Ref n _, args) <- unApply fn
124 = if n `elem` ps then nut ps f ++ nut ps a
125 else [(n, map argNames args)] ++ concatMap (nut ps) args
126 | otherwise = nut ps f ++ nut ps a
127 nut ps (Bind n (Let t v) sc) = nut ps v ++ nut (n:ps) sc
128 nut ps (Proj t _) = nut ps t
129 nut ps (Bind n b sc) = nut (n:ps) sc
132 argNames tm = let ns = directUse tm in
133 filter (\x -> x `elem` ns) topargs
135-- Find names which are used directly (i.e. not in a function call) in a term
137directUse :: Eq n => TT n -> [n]
138directUse (P _ n _) = [n]
139directUse (Bind n (Let t v) sc) = nub $ directUse v ++ (directUse sc \\ [n])
141directUse (Bind n b sc) = nub $ directUse (binderTy b) ++ (directUse sc \\ [n])
142directUse fn@(App f a)
143 | (P Ref n _, args) <- unApply fn = [] -- need to know what n does with them
144 | otherwise = nub $ directUse f ++ directUse a
145directUse (Proj x i) = nub $ directUse x
148-- Find all directly used arguments (i.e. used but not in function calls)
150findUsedArgs :: SC -> [Name] -> [Name]
151findUsedArgs sc topargs = nub (findAllUsedArgs sc topargs)
153findAllUsedArgs sc topargs = filter (\x -> x `elem` topargs) (nu' sc) where
154 nu' (Case n alts) = n : concatMap nua alts
155 nu' (ProjCase t alts) = directUse t ++ concatMap nua alts
156 nu' (STerm t) = directUse t
159 nua (ConCase n i args sc) = nu' sc
160 nua (ConstCase _ sc) = nu' sc
161 nua (DefaultCase sc) = nu' sc
163data Phase = CompileTime | RunTime
166-- Generate a simple case tree
169simpleCase :: Bool -> Bool -> Phase -> FC -> [([Name], Term, Term)] ->
171simpleCase tc cover phase fc cs
172 = sc' tc cover phase fc (filter (\(_, _, r) ->
177 sc' tc cover phase fc []
178 = return $ CaseDef [] (UnmatchedCase "No pattern clauses") []
179 sc' tc cover phase fc cs
180 = let proj = phase == RunTime
181 pats = map (\ (avs, l, r) ->
182 (avs, toPats tc l, (l, r))) cs
183 chkPats = mapM chkAccessible pats in
186 let numargs = length (fst (head pats))
187 ns = take numargs args
188 (ns', ps') = order ns pats
189 (tree, st) = runState
190 (match ns' ps' (defaultCase cover)) ([], numargs)
191 t = CaseDef ns (prune proj (depatt ns' tree)) (fst st) in
192 if proj then return (stripLambdas t) else return t
193 Error err -> Error (At fc err)
194 where args = map (\i -> MN i "e") [0..]
195 defaultCase True = STerm Erased
196 defaultCase False = UnmatchedCase "Error"
198 chkAccessible (avs, l, c)
199 | phase == RunTime = return (l, c)
200 | otherwise = do mapM_ (acc l) avs
203 acc [] n = Error (Inaccessible n)
204 acc (PV x : xs) n | x == n = OK ()
205 acc (PCon _ _ ps : xs) n = acc (ps ++ xs) n
206 acc (_ : xs) n = acc xs n
208data Pat = PCon Name Int [Pat]
214-- If there are repeated variables, take the *last* one (could be name shadowing
215-- in a where clause, so take the most recent).
217toPats :: Bool -> Term -> [Pat]
218toPats tc f = reverse (toPat tc (getArgs f)) where
219 getArgs (App f a) = a : getArgs f
222toPat :: Bool -> [Term] -> [Pat]
223toPat tc tms = evalState (mapM (\x -> toPat' x []) tms) []
225 toPat' (P (DCon t a) n _) args = do args' <- mapM (\x -> toPat' x []) args
226 return $ PCon n t args'
228 toPat' (P (TCon t a) n _) args | tc
229 = do args' <- mapM (\x -> toPat' x []) args
230 return $ PCon n t args'
231 toPat' (Constant (AType (ATInt ITNative))) []
232 | tc = return $ PCon (UN "Int") 1 []
233 toPat' (Constant (AType ATFloat)) [] | tc = return $ PCon (UN "Float") 2 []
234 toPat' (Constant ChType) [] | tc = return $ PCon (UN "Char") 3 []
235 toPat' (Constant StrType) [] | tc = return $ PCon (UN "String") 4 []
236 toPat' (Constant PtrType) [] | tc = return $ PCon (UN "Ptr") 5 []
237 toPat' (Constant (AType (ATInt ITBig))) []
238 | tc = return $ PCon (UN "Integer") 6 []
239 toPat' (Constant (AType (ATInt (ITFixed n)))) []
240 | tc = return $ PCon (UN (fixedN n)) (7 + fromEnum n) [] -- 7-10 inclusive
241 toPat' (Constant (AType (ATInt (ITVec ity count)))) []
242 | tc = return $ PCon (UN (fixedN ity)) ((fromEnum ity + 1) * 1000 + count) [] -- 1000-5000 inclusive
243 toPat' (P Bound n _) [] = do ns <- get
248 toPat' (App f a) args = toPat' f (a : args)
249 toPat' (Constant x) [] = return $ PConst x
250 toPat' _ _ = return PAny
253 fixedN IT16 = "Bits16"
254 fixedN IT32 = "Bits32"
255 fixedN IT64 = "Bits64"
258data Partition = Cons [Clause]
262isVarPat (PV _ : ps , _) = True
263isVarPat (PAny : ps , _) = True
266isConPat (PCon _ _ _ : ps, _) = True
267isConPat (PConst _ : ps, _) = True
270partition :: [Clause] -> [Partition]
273 | isVarPat m = let (vars, rest) = span isVarPat ms in
274 Vars vars : partition rest
275 | isConPat m = let (cons, rest) = span isConPat ms in
276 Cons cons : partition rest
277partition xs = error $ "Partition " ++ show xs
279-- reorder the patterns so that the one with most distinct names
280-- comes next. Take rightmost first, otherwise (i.e. pick value rather
283order :: [Name] -> [Clause] -> ([Name], [Clause])
284order [] cs = ([], cs)
285order ns [] = (ns, [])
286order ns cs = let patnames = transpose (map (zip ns) (map fst cs))
287 pats' = transpose (sortBy moreDistinct (reverse patnames)) in
288 (getNOrder pats', zipWith rebuild pats' cs)
290 getNOrder [] = error $ "Failed order on " ++ show (ns, cs)
291 getNOrder (c : _) = map fst c
293 rebuild patnames clause = (map snd patnames, snd clause)
295 moreDistinct xs ys = compare (numNames [] (map snd ys))
296 (numNames [] (map snd xs))
298 numNames xs (PCon n _ _ : ps)
299 | not (Left n `elem` xs) = numNames (Left n : xs) ps
300 numNames xs (PConst c : ps)
301 | not (Right c `elem` xs) = numNames (Right c : xs) ps
302 numNames xs (_ : ps) = numNames xs ps
303 numNames xs [] = length xs
305match :: [Name] -> [Clause] -> SC -- error case
307match [] (([], ret) : xs) err
309 put (ts ++ (map (fst.snd) xs), v)
311 Impossible -> return ImpossibleCase
312 tm -> return $ STerm tm -- run out of arguments
313match vs cs err = do let ps = partition cs
316mixture :: [Name] -> [Partition] -> SC -> State CS SC
317mixture vs [] err = return err
318mixture vs (Cons ms : ps) err = do fallthrough <- mixture vs ps err
319 conRule vs ms fallthrough
320mixture vs (Vars ms : ps) err = do fallthrough <- mixture vs ps err
321 varRule vs ms fallthrough
323data ConType = CName Name Int -- named constructor
324 | CConst Const -- constant, not implemented yet
326data Group = ConGroup ConType -- Constructor
327 [([Pat], Clause)] -- arguments and rest of alternative
329conRule :: [Name] -> [Clause] -> SC -> State CS SC
330conRule (v:vs) cs err = do groups <- groupCons cs
331 caseGroups (v:vs) groups err
333caseGroups :: [Name] -> [Group] -> SC -> State CS SC
334caseGroups (v:vs) gs err = do g <- altGroups gs
335 return $ Case v (sort g)
337 altGroups [] = return [DefaultCase err]
338 altGroups (ConGroup (CName n i) args : cs)
339 = do g <- altGroup n i args
342 altGroups (ConGroup (CConst c) args : cs)
343 = do g <- altConstGroup c args
347 altGroup n i gs = do (newArgs, nextCs) <- argsToAlt gs
348 matchCs <- match (newArgs ++ vs) nextCs err
349 return $ ConCase n i newArgs matchCs
350 altConstGroup n gs = do (_, nextCs) <- argsToAlt gs
351 matchCs <- match vs nextCs err
352 return $ ConstCase n matchCs
354argsToAlt :: [([Pat], Clause)] -> State CS ([Name], [Clause])
355argsToAlt [] = return ([], [])
356argsToAlt rs@((r, m) : rest)
357 = do newArgs <- getNewVars r
358 return (newArgs, addRs rs)
360 getNewVars [] = return []
361 getNewVars ((PV n) : ns) = do v <- getVar "e"
364 getNewVars (PAny : ns) = do v <- getVar "i"
367 getNewVars (_ : ns) = do v <- getVar "e"
371 addRs ((r, (ps, res)) : rs) = ((r++ps, res) : addRs rs)
373 uniq i (UN n) = MN i n
376getVar :: String -> State CS Name
377getVar b = do (t, v) <- get; put (t, v+1); return (MN v b)
379groupCons :: [Clause] -> State CS [Group]
380groupCons cs = gc [] cs
382 gc acc [] = return acc
383 gc acc ((p : ps, res) : cs) =
384 do acc' <- addGroup p ps res acc
386 addGroup p ps res acc = case p of
387 PCon con i args -> return $ addg con i args (ps, res) acc
388 PConst cval -> return $ addConG cval (ps, res) acc
389 pat -> fail $ show pat ++ " is not a constructor or constant (can't happen)"
391 addg con i conargs res [] = [ConGroup (CName con i) [(conargs, res)]]
392 addg con i conargs res (g@(ConGroup (CName n j) cs):gs)
393 | i == j = ConGroup (CName n i) (cs ++ [(conargs, res)]) : gs
394 | otherwise = g : addg con i conargs res gs
396 addConG con res [] = [ConGroup (CConst con) [([], res)]]
397 addConG con res (g@(ConGroup (CConst n) cs) : gs)
398 | con == n = ConGroup (CConst n) (cs ++ [([], res)]) : gs
399 | otherwise = g : addConG con res gs
401varRule :: [Name] -> [Clause] -> SC -> State CS SC
402varRule (v : vs) alts err =
403 do let alts' = map (repVar v) alts
406 repVar v (PV p : ps , (lhs, res))
407 = (ps, (lhs, subst p (P Bound v Erased) res))
408 repVar v (PAny : ps , res) = (ps, res)
410-- fix: case e of S k -> f (S k) ==> case e of S k -> f e
412depatt :: [Name] -> SC -> SC
413depatt ns tm = dp [] tm
415 dp ms (STerm tm) = STerm (applyMaps ms tm)
416 dp ms (Case x alts) = Case x (map (dpa ms x) alts)
419 dpa ms x (ConCase n i args sc)
420 = ConCase n i args (dp ((x, (n, args)) : ms) sc)
421 dpa ms x (ConstCase c sc) = ConstCase c (dp ms sc)
422 dpa ms x (DefaultCase sc) = DefaultCase (dp ms sc)
424 applyMaps ms f@(App _ _)
425 | (P nt cn pty, args) <- unApply f
426 = let args' = map (applyMaps ms) args in
427 applyMap ms nt cn pty args'
429 applyMap [] nt cn pty args' = mkApp (P nt cn pty) args'
430 applyMap ((x, (n, args)) : ms) nt cn pty args'
431 | and ((length args == length args') :
432 (n == cn) : zipWith same args args') = P Ref x Erased
433 | otherwise = applyMap ms nt cn pty args'
434 same n (P _ n' _) = n == n'
437 applyMaps ms (App f a) = App (applyMaps ms f) (applyMaps ms a)
440prune :: Bool -- ^ Convert single branches to projections (only useful at runtime)
442prune proj (Case n alts)
443 = let alts' = filter notErased (map pruneAlt alts) in
446 as@[ConCase cn i args sc] -> if proj then mkProj n 0 args sc
449 where pruneAlt (ConCase cn i ns sc) = ConCase cn i ns (prune proj sc)
450 pruneAlt (ConstCase c sc) = ConstCase c (prune proj sc)
451 pruneAlt (DefaultCase sc) = DefaultCase (prune proj sc)
453 notErased (DefaultCase (STerm Erased)) = False
454 notErased (DefaultCase ImpossibleCase) = False
457 mkProj n i [] sc = sc
458 mkProj n i (x : xs) sc = mkProj n (i + 1) xs (projRep x n i sc)
460 projRep :: Name -> Name -> Int -> SC -> SC
461 projRep arg n i (Case x alts)
462 | x == arg = ProjCase (Proj (P Bound n Erased) i)
463 (map (projRepAlt arg n i) alts)
464 | otherwise = Case x (map (projRepAlt arg n i) alts)
465 projRep arg n i (ProjCase t alts)
466 = ProjCase (projRepTm arg n i t) (map (projRepAlt arg n i) alts)
467 projRep arg n i (STerm t) = STerm (projRepTm arg n i t)
468 projRep arg n i c = c -- unmatched
470 projRepAlt arg n i (ConCase cn t args rhs)
471 = ConCase cn t args (projRep arg n i rhs)
472 projRepAlt arg n i (ConstCase t rhs)
473 = ConstCase t (projRep arg n i rhs)
474 projRepAlt arg n i (DefaultCase rhs)
475 = DefaultCase (projRep arg n i rhs)
477 projRepTm arg n i t = subst arg (Proj (P Bound n Erased) i) t
481stripLambdas :: CaseDef -> CaseDef
482stripLambdas (CaseDef ns (STerm (Bind x (Lam _) sc)) tm)
483 = 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