1{-# LANGUAGE PatternGuards, DeriveFunctor #-}
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 (STerm t) = termsize n t
70instance TermSize CaseAlt where
71 termsize n (ConCase _ _ _ s) = termsize n s
72 termsize n (ConstCase _ s) = termsize n s
73 termsize n (DefaultCase s) = termsize n s
75-- simple terms can be inlined trivially - good for primitives in particular
76small :: Name -> SC -> Bool
77small n t = termsize n t < 50
79namesUsed :: SC -> [Name]
80namesUsed sc = nub $ nu' [] sc where
81 nu' ps (Case n alts) = nub (concatMap (nua ps) alts) \\ [n]
82 nu' ps (ProjCase t alts) = nub $ (nut ps t ++
83 (concatMap (nua ps) alts))
84 nu' ps (STerm t) = nub $ nut ps t
87 nua ps (ConCase n i args sc) = nub (nu' (ps ++ args) sc) \\ args
88 nua ps (ConstCase _ sc) = nu' ps sc
89 nua ps (DefaultCase sc) = nu' ps sc
91 nut ps (P _ n _) | n `elem` ps = []
93 nut ps (App f a) = nut ps f ++ nut ps a
94 nut ps (Proj t _) = nut ps t
95 nut ps (Bind n (Let t v) sc) = nut ps v ++ nut (n:ps) sc
96 nut ps (Bind n b sc) = nut (n:ps) sc
99-- Return all called functions, and which arguments are used in each argument position
100-- for the call, in order to help reduce compilation time, and trace all unused
103findCalls :: SC -> [Name] -> [(Name, [[Name]])]
104findCalls sc topargs = nub $ nu' topargs sc where
105 nu' ps (Case n alts) = nub (concatMap (nua (n : ps)) alts)
106 nu' ps (ProjCase t alts) = nub (nut ps t ++ concatMap (nua ps) alts)
107 nu' ps (STerm t) = nub $ nut ps t
110 nua ps (ConCase n i args sc) = nub (nu' (ps ++ args) sc)
111 nua ps (ConstCase _ sc) = nu' ps sc
112 nua ps (DefaultCase sc) = nu' ps sc
114 nut ps (P Ref n _) | n `elem` ps = []
115 | otherwise = [(n, [])] -- tmp
117 | (P Ref n _, args) <- unApply fn
118 = if n `elem` ps then nut ps f ++ nut ps a
119 else [(n, map argNames args)] ++ concatMap (nut ps) args
120 | otherwise = nut ps f ++ nut ps a
121 nut ps (Bind n (Let t v) sc) = nut ps v ++ nut (n:ps) sc
122 nut ps (Proj t _) = nut ps t
123 nut ps (Bind n b sc) = nut (n:ps) sc
126 argNames tm = let ns = directUse tm in
127 filter (\x -> x `elem` ns) topargs
129-- Find names which are used directly (i.e. not in a function call) in a term
131directUse :: Eq n => TT n -> [n]
132directUse (P _ n _) = [n]
133directUse (Bind n (Let t v) sc) = nub $ directUse v ++ (directUse sc \\ [n])
135directUse (Bind n b sc) = nub $ directUse (binderTy b) ++ (directUse sc \\ [n])
136directUse fn@(App f a)
137 | (P Ref n _, args) <- unApply fn = [] -- need to know what n does with them
138 | otherwise = nub $ directUse f ++ directUse a
139directUse (Proj x i) = nub $ directUse x
142-- Find all directly used arguments (i.e. used but not in function calls)
144findUsedArgs :: SC -> [Name] -> [Name]
145findUsedArgs sc topargs = filter (\x -> x `elem` topargs) (nub $ nu' sc) where
146 nu' (Case n alts) = n : concatMap nua alts
147 nu' (STerm t) = directUse t
150 nua (ConCase n i args sc) = nu' sc
151 nua (ConstCase _ sc) = nu' sc
152 nua (DefaultCase sc) = nu' sc
154data Phase = CompileTime | RunTime
157-- Generate a simple case tree
158-- Work Left to Right at Compile Time
160simpleCase :: Bool -> Bool -> Phase -> FC -> [([Name], Term, Term)] -> TC CaseDef
161simpleCase tc cover phase fc []
162 = return $ CaseDef [] (UnmatchedCase "No pattern clauses") []
163simpleCase tc cover phase fc cs
164 = let proj = phase == RunTime
165 pats = map (\ (avs, l, r) ->
166 (avs, rev phase (toPats tc l), (l, r))) cs
167 chkPats = mapM chkAccessible pats in
170 let numargs = length (fst (head pats))
171 ns = take numargs args
172 (tree, st) = runState
173 (match (rev phase ns) pats (defaultCase cover)) ([], numargs)
174 t = CaseDef ns (prune proj (depatt ns tree)) (fst st) in
175 if proj then return (stripLambdas t) else return t
176 Error err -> Error (At fc err)
177 where args = map (\i -> MN i "e") [0..]
178 defaultCase True = STerm Erased
179 defaultCase False = UnmatchedCase "Error"
181 chkAccessible (avs, l, c)
182 | phase == RunTime = return (l, c)
183 | otherwise = do mapM_ (acc l) avs
186 acc [] n = Error (Inaccessible n)
187 acc (PV x : xs) n | x == n = OK ()
188 acc (PCon _ _ ps : xs) n = acc (ps ++ xs) n
189 acc (_ : xs) n = acc xs n
194data Pat = PCon Name Int [Pat]
200-- If there are repeated variables, take the *last* one (could be name shadowing
201-- in a where clause, so take the most recent).
203toPats :: Bool -> Term -> [Pat]
204toPats tc f = reverse (toPat tc (getArgs f)) where
205 getArgs (App f a) = a : getArgs f
208toPat :: Bool -> [Term] -> [Pat]
209toPat tc tms = evalState (mapM (\x -> toPat' x []) tms) []
211 toPat' (P (DCon t a) n _) args = do args' <- mapM (\x -> toPat' x []) args
212 return $ PCon n t args'
214 toPat' (P (TCon t a) n _) args | tc
215 = do args' <- mapM (\x -> toPat' x []) args
216 return $ PCon n t args'
217 toPat' (Constant IType) [] | tc = return $ PCon (UN "Int") 1 []
218 toPat' (Constant FlType) [] | tc = return $ PCon (UN "Float") 2 []
219 toPat' (Constant ChType) [] | tc = return $ PCon (UN "Char") 3 []
220 toPat' (Constant StrType) [] | tc = return $ PCon (UN "String") 4 []
221 toPat' (Constant PtrType) [] | tc = return $ PCon (UN "Ptr") 5 []
222 toPat' (Constant BIType) [] | tc = return $ PCon (UN "Integer") 6 []
224 toPat' (P Bound n _) [] = do ns <- get
229 toPat' (App f a) args = toPat' f (a : args)
230 toPat' (Constant x) [] = return $ PConst x
231 toPat' _ _ = return PAny
234data Partition = Cons [Clause]
238isVarPat (PV _ : ps , _) = True
239isVarPat (PAny : ps , _) = True
242isConPat (PCon _ _ _ : ps, _) = True
243isConPat (PConst _ : ps, _) = True
246partition :: [Clause] -> [Partition]
249 | isVarPat m = let (vars, rest) = span isVarPat ms in
250 Vars vars : partition rest
251 | isConPat m = let (cons, rest) = span isConPat ms in
252 Cons cons : partition rest
253partition xs = error $ "Partition " ++ show xs
255match :: [Name] -> [Clause] -> SC -- error case
257match [] (([], ret) : xs) err
259 put (ts ++ (map (fst.snd) xs), v)
261 Impossible -> return ImpossibleCase
262 tm -> return $ STerm tm -- run out of arguments
263match vs cs err = do let ps = partition cs
264 cs <- mixture vs ps err
267mixture :: [Name] -> [Partition] -> SC -> State CS SC
268mixture vs [] err = return err
269mixture vs (Cons ms : ps) err = do fallthrough <- mixture vs ps err
270 conRule vs ms fallthrough
271mixture vs (Vars ms : ps) err = do fallthrough <- mixture vs ps err
272 varRule vs ms fallthrough
274data ConType = CName Name Int -- named constructor
275 | CConst Const -- constant, not implemented yet
277data Group = ConGroup ConType -- Constructor
278 [([Pat], Clause)] -- arguments and rest of alternative
280conRule :: [Name] -> [Clause] -> SC -> State CS SC
281conRule (v:vs) cs err = do groups <- groupCons cs
282 caseGroups (v:vs) groups err
284caseGroups :: [Name] -> [Group] -> SC -> State CS SC
285caseGroups (v:vs) gs err = do g <- altGroups gs
286 return $ Case v (sort g)
288 altGroups [] = return [DefaultCase err]
289 altGroups (ConGroup (CName n i) args : cs)
290 = do g <- altGroup n i args
293 altGroups (ConGroup (CConst c) args : cs)
294 = do g <- altConstGroup c args
298 altGroup n i gs = do (newArgs, nextCs) <- argsToAlt gs
299 matchCs <- match (newArgs ++ vs) nextCs err
300 return $ ConCase n i newArgs matchCs
301 altConstGroup n gs = do (_, nextCs) <- argsToAlt gs
302 matchCs <- match vs nextCs err
303 return $ ConstCase n matchCs
305argsToAlt :: [([Pat], Clause)] -> State CS ([Name], [Clause])
306argsToAlt [] = return ([], [])
307argsToAlt rs@((r, m) : rest)
308 = do newArgs <- getNewVars r
309 return (newArgs, addRs rs)
311 getNewVars [] = return []
312 getNewVars ((PV n) : ns) = do v <- getVar
315 getNewVars (_ : ns) = do v <- getVar
319 addRs ((r, (ps, res)) : rs) = ((r++ps, res) : addRs rs)
321 uniq i (UN n) = MN i n
324getVar :: State CS Name
325getVar = do (t, v) <- get; put (t, v+1); return (MN v "e")
327groupCons :: [Clause] -> State CS [Group]
328groupCons cs = gc [] cs
330 gc acc [] = return acc
331 gc acc ((p : ps, res) : cs) =
332 do acc' <- addGroup p ps res acc
334 addGroup p ps res acc = case p of
335 PCon con i args -> return $ addg con i args (ps, res) acc
336 PConst cval -> return $ addConG cval (ps, res) acc
337 pat -> fail $ show pat ++ " is not a constructor or constant (can't happen)"
339 addg con i conargs res [] = [ConGroup (CName con i) [(conargs, res)]]
340 addg con i conargs res (g@(ConGroup (CName n j) cs):gs)
341 | i == j = ConGroup (CName n i) (cs ++ [(conargs, res)]) : gs
342 | otherwise = g : addg con i conargs res gs
344 addConG con res [] = [ConGroup (CConst con) [([], res)]]
345 addConG con res (g@(ConGroup (CConst n) cs) : gs)
346 | con == n = ConGroup (CConst n) (cs ++ [([], res)]) : gs
347 | otherwise = g : addConG con res gs
349varRule :: [Name] -> [Clause] -> SC -> State CS SC
350varRule (v : vs) alts err =
351 do let alts' = map (repVar v) alts
354 repVar v (PV p : ps , (lhs, res)) = (ps, (lhs, subst p (P Bound v Erased) res))
355 repVar v (PAny : ps , res) = (ps, res)
357-- fix: case e of S k -> f (S k) ==> case e of S k -. f e
358depatt :: [Name] -> SC -> SC
359depatt ns tm = dp [] tm
361 dp ms (STerm tm) = STerm (applyMaps ms tm)
362 dp ms (Case x alts) = Case x (map (dpa ms x) alts)
365 dpa ms x (ConCase n i args sc)
366 = ConCase n i args (dp ((x, (n, args)) : ms) sc)
367 dpa ms x (ConstCase c sc) = ConstCase c (dp ms sc)
368 dpa ms x (DefaultCase sc) = DefaultCase (dp ms sc)
370 applyMaps ms f@(App _ _)
371 | (P nt cn pty, args) <- unApply f
372 = let args' = map (applyMaps ms) args in
373 applyMap ms nt cn pty args'
375 applyMap [] nt cn pty args' = mkApp (P nt cn pty) args'
376 applyMap ((x, (n, args)) : ms) nt cn pty args'
377 | and ((n == cn) : zipWith same args args') = P Ref x Erased
378 | otherwise = applyMap ms nt cn pty args'
379 same n (P _ n' _) = n == n'
381 applyMaps ms (App f a) = App (applyMaps ms f) (applyMaps ms a)
384prune :: Bool -> -- ^ Convert single branches to projections (only useful at runtime)
386prune proj (Case n alts)
387 = let alts' = filter notErased (map pruneAlt alts) in
390 as@[ConCase cn i args sc] -> if proj then mkProj n 0 args sc
393 where pruneAlt (ConCase cn i ns sc) = ConCase cn i ns (prune proj sc)
394 pruneAlt (ConstCase c sc) = ConstCase c (prune proj sc)
395 pruneAlt (DefaultCase sc) = DefaultCase (prune proj sc)
397 notErased (DefaultCase (STerm Erased)) = False
398 notErased (DefaultCase ImpossibleCase) = False
401 mkProj n i [] sc = sc
402 mkProj n i (x : xs) sc = mkProj n (i + 1) xs (projRep x n i sc)
404 projRep :: Name -> Name -> Int -> SC -> SC
405 projRep arg n i (Case x alts)
406 | x == arg = ProjCase (Proj (P Bound n Erased) i)
407 (map (projRepAlt arg n i) alts)
408 | otherwise = Case x (map (projRepAlt arg n i) alts)
409 projRep arg n i (ProjCase t alts)
410 = ProjCase (projRepTm arg n i t) (map (projRepAlt arg n i) alts)
411 projRep arg n i (STerm t) = STerm (projRepTm arg n i t)
412 projRep arg n i c = c -- unmatched
414 projRepAlt arg n i (ConCase cn t args rhs)
415 = ConCase cn t args (projRep arg n i rhs)
416 projRepAlt arg n i (ConstCase t rhs)
417 = ConstCase t (projRep arg n i rhs)
418 projRepAlt arg n i (DefaultCase rhs)
419 = DefaultCase (projRep arg n i rhs)
421 projRepTm arg n i t = subst arg (Proj (P Bound n Erased) i) t
425stripLambdas :: CaseDef -> CaseDef
426stripLambdas (CaseDef ns (STerm (Bind x (Lam _) sc)) tm)
427 = 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