on 17d2cea help sign in
Idris-dev/src/Core/CaseTree.hs
435 lines 17 kB history raw
1{-# LANGUAGE PatternGuards, DeriveFunctor #-}
3module Core.CaseTree(CaseDef(..), SC, SC'(..), CaseAlt, CaseAlt'(..),
4 Phase(..), CaseTree,
5 simpleCase, small, namesUsed, findCalls, findUsedArgs) where
7import Core.TT
9import Control.Monad.State
10import Data.Maybe
11import Data.List hiding (partition)
12import Debug.Trace
14data CaseDef = CaseDef [Name] SC [Term]
15 deriving Show
17data SC' t = Case Name [CaseAlt' t] -- invariant: lowest tags first
18 | ProjCase t [CaseAlt' t] -- special case for projections
19 | STerm t
20 | UnmatchedCase String -- error message
21 | ImpossibleCase -- already checked to be impossible
22 deriving (Eq, Ord, Functor)
23{-!
24deriving instance Binary SC
25!-}
27type SC = SC' Term
29data CaseAlt' t = ConCase Name Int [Name] (SC' t)
30 | ConstCase Const (SC' t)
31 | DefaultCase (SC' t)
32 deriving (Show, Eq, Ord, Functor)
33{-!
34deriving instance Binary CaseAlt
35!-}
37type CaseAlt = CaseAlt' Term
39instance Show t => Show (SC' t) where
40 show sc = show' 1 sc
41 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) ++ ") => "
54 ++ show' (i+1) sc
55 showA i (ConstCase t sc)
56 = show t ++ " => " ++ show' (i+1) sc
57 showA i (DefaultCase sc)
58 = "_ => " ++ show' (i+1) sc
61type CaseTree = 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
68 termsize n _ = 1
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
85 nu' ps _ = []
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 = []
92 | otherwise = [n]
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
97 nut ps _ = []
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
101-- arguments
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
108 nu' ps _ = []
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
116 nut ps fn@(App f a)
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
124 nut ps _ = []
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])
134 ++ directUse t
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
140directUse _ = []
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' (ProjCase t alts) = directUse t ++ concatMap nua alts
148 nu' (STerm t) = directUse t
149 nu' _ = []
151 nua (ConCase n i args sc) = nu' sc
152 nua (ConstCase _ sc) = nu' sc
153 nua (DefaultCase sc) = nu' sc
155data Phase = CompileTime | RunTime
156 deriving (Show, Eq)
158-- Generate a simple case tree
159-- Work Left to Right at Compile Time
161simpleCase :: Bool -> Bool -> Phase -> FC -> [([Name], Term, Term)] ->
162 TC CaseDef
163simpleCase tc cover phase fc []
164 = return $ CaseDef [] (UnmatchedCase "No pattern clauses") []
165simpleCase tc cover phase fc cs
166 = let proj = phase == RunTime
167 pats = map (\ (avs, l, r) ->
168 (avs, rev phase (toPats tc l), (l, r))) cs
169 chkPats = mapM chkAccessible pats in
170 case chkPats of
171 OK pats ->
172 let numargs = length (fst (head pats))
173 ns = take numargs args
174 (tree, st) = runState
175 (match (rev phase ns) pats (defaultCase cover)) ([], numargs)
176 t = CaseDef ns (prune proj (depatt ns tree)) (fst st) in
177 if proj then return (stripLambdas t) else return t
178 Error err -> Error (At fc err)
179 where args = map (\i -> MN i "e") [0..]
180 defaultCase True = STerm Erased
181 defaultCase False = UnmatchedCase "Error"
183 chkAccessible (avs, l, c)
184 | phase == RunTime = return (l, c)
185 | otherwise = do mapM_ (acc l) avs
186 return (l, c)
188 acc [] n = Error (Inaccessible n)
189 acc (PV x : xs) n | x == n = OK ()
190 acc (PCon _ _ ps : xs) n = acc (ps ++ xs) n
191 acc (_ : xs) n = acc xs n
193rev CompileTime = id
194rev _ = reverse
196data Pat = PCon Name Int [Pat]
197 | PConst Const
198 | PV Name
199 | PAny
200 deriving Show
202-- If there are repeated variables, take the *last* one (could be name shadowing
203-- in a where clause, so take the most recent).
205toPats :: Bool -> Term -> [Pat]
206toPats tc f = reverse (toPat tc (getArgs f)) where
207 getArgs (App f a) = a : getArgs f
208 getArgs _ = []
210toPat :: Bool -> [Term] -> [Pat]
211toPat tc tms = evalState (mapM (\x -> toPat' x []) tms) []
212 where
213 toPat' (P (DCon t a) n _) args = do args' <- mapM (\x -> toPat' x []) args
214 return $ PCon n t args'
215 -- Typecase
216 toPat' (P (TCon t a) n _) args | tc
217 = do args' <- mapM (\x -> toPat' x []) args
218 return $ PCon n t args'
219 toPat' (Constant IType) [] | tc = return $ PCon (UN "Int") 1 []
220 toPat' (Constant FlType) [] | tc = return $ PCon (UN "Float") 2 []
221 toPat' (Constant ChType) [] | tc = return $ PCon (UN "Char") 3 []
222 toPat' (Constant StrType) [] | tc = return $ PCon (UN "String") 4 []
223 toPat' (Constant PtrType) [] | tc = return $ PCon (UN "Ptr") 5 []
224 toPat' (Constant BIType) [] | tc = return $ PCon (UN "Integer") 6 []
226 toPat' (P Bound n _) [] = do ns <- get
227 if n `elem` ns
228 then return PAny
229 else do put (n : ns)
230 return (PV n)
231 toPat' (App f a) args = toPat' f (a : args)
232 toPat' (Constant x) [] = return $ PConst x
233 toPat' _ _ = return PAny
236data Partition = Cons [Clause]
237 | Vars [Clause]
238 deriving Show
240isVarPat (PV _ : ps , _) = True
241isVarPat (PAny : ps , _) = True
242isVarPat _ = False
244isConPat (PCon _ _ _ : ps, _) = True
245isConPat (PConst _ : ps, _) = True
246isConPat _ = False
248partition :: [Clause] -> [Partition]
249partition [] = []
250partition ms@(m : _)
251 | isVarPat m = let (vars, rest) = span isVarPat ms in
252 Vars vars : partition rest
253 | isConPat m = let (cons, rest) = span isConPat ms in
254 Cons cons : partition rest
255partition xs = error $ "Partition " ++ show xs
257match :: [Name] -> [Clause] -> SC -- error case
258 -> State CS SC
259match [] (([], ret) : xs) err
260 = do (ts, v) <- get
261 put (ts ++ (map (fst.snd) xs), v)
262 case snd ret of
263 Impossible -> return ImpossibleCase
264 tm -> return $ STerm tm -- run out of arguments
265match vs cs err = do let ps = partition cs
266 cs <- mixture vs ps err
267 return cs
269mixture :: [Name] -> [Partition] -> SC -> State CS SC
270mixture vs [] err = return err
271mixture vs (Cons ms : ps) err = do fallthrough <- mixture vs ps err
272 conRule vs ms fallthrough
273mixture vs (Vars ms : ps) err = do fallthrough <- mixture vs ps err
274 varRule vs ms fallthrough
276data ConType = CName Name Int -- named constructor
277 | CConst Const -- constant, not implemented yet
279data Group = ConGroup ConType -- Constructor
280 [([Pat], Clause)] -- arguments and rest of alternative
282conRule :: [Name] -> [Clause] -> SC -> State CS SC
283conRule (v:vs) cs err = do groups <- groupCons cs
284 caseGroups (v:vs) groups err
286caseGroups :: [Name] -> [Group] -> SC -> State CS SC
287caseGroups (v:vs) gs err = do g <- altGroups gs
288 return $ Case v (sort g)
289 where
290 altGroups [] = return [DefaultCase err]
291 altGroups (ConGroup (CName n i) args : cs)
292 = do g <- altGroup n i args
293 rest <- altGroups cs
294 return (g : rest)
295 altGroups (ConGroup (CConst c) args : cs)
296 = do g <- altConstGroup c args
297 rest <- altGroups cs
298 return (g : rest)
300 altGroup n i gs = do (newArgs, nextCs) <- argsToAlt gs
301 matchCs <- match (newArgs ++ vs) nextCs err
302 return $ ConCase n i newArgs matchCs
303 altConstGroup n gs = do (_, nextCs) <- argsToAlt gs
304 matchCs <- match vs nextCs err
305 return $ ConstCase n matchCs
307argsToAlt :: [([Pat], Clause)] -> State CS ([Name], [Clause])
308argsToAlt [] = return ([], [])
309argsToAlt rs@((r, m) : rest)
310 = do newArgs <- getNewVars r
311 return (newArgs, addRs rs)
312 where
313 getNewVars [] = return []
314 getNewVars ((PV n) : ns) = do v <- getVar
315 nsv <- getNewVars ns
316 return (v : nsv)
317 getNewVars (_ : ns) = do v <- getVar
318 nsv <- getNewVars ns
319 return (v : nsv)
320 addRs [] = []
321 addRs ((r, (ps, res)) : rs) = ((r++ps, res) : addRs rs)
323 uniq i (UN n) = MN i n
324 uniq i n = n
326getVar :: State CS Name
327getVar = do (t, v) <- get; put (t, v+1); return (MN v "e")
329groupCons :: [Clause] -> State CS [Group]
330groupCons cs = gc [] cs
331 where
332 gc acc [] = return acc
333 gc acc ((p : ps, res) : cs) =
334 do acc' <- addGroup p ps res acc
335 gc acc' cs
336 addGroup p ps res acc = case p of
337 PCon con i args -> return $ addg con i args (ps, res) acc
338 PConst cval -> return $ addConG cval (ps, res) acc
339 pat -> fail $ show pat ++ " is not a constructor or constant (can't happen)"
341 addg con i conargs res [] = [ConGroup (CName con i) [(conargs, res)]]
342 addg con i conargs res (g@(ConGroup (CName n j) cs):gs)
343 | i == j = ConGroup (CName n i) (cs ++ [(conargs, res)]) : gs
344 | otherwise = g : addg con i conargs res gs
346 addConG con res [] = [ConGroup (CConst con) [([], res)]]
347 addConG con res (g@(ConGroup (CConst n) cs) : gs)
348 | con == n = ConGroup (CConst n) (cs ++ [([], res)]) : gs
349 | otherwise = g : addConG con res gs
351varRule :: [Name] -> [Clause] -> SC -> State CS SC
352varRule (v : vs) alts err =
353 do let alts' = map (repVar v) alts
354 match vs alts' err
355 where
356 repVar v (PV p : ps , (lhs, res)) = (ps, (lhs, subst p (P Bound v Erased) res))
357 repVar v (PAny : ps , res) = (ps, res)
359-- fix: case e of S k -> f (S k) ==> case e of S k -> f e
360depatt :: [Name] -> SC -> SC
361depatt ns tm = dp [] tm
362 where
363 dp ms (STerm tm) = STerm (applyMaps ms tm)
364 dp ms (Case x alts) = Case x (map (dpa ms x) alts)
365 dp ms sc = sc
367 dpa ms x (ConCase n i args sc)
368 = ConCase n i args (dp ((x, (n, args)) : ms) sc)
369 dpa ms x (ConstCase c sc) = ConstCase c (dp ms sc)
370 dpa ms x (DefaultCase sc) = DefaultCase (dp ms sc)
372 applyMaps ms f@(App _ _)
373 | (P nt cn pty, args) <- unApply f
374 = let args' = map (applyMaps ms) args in
375 applyMap ms nt cn pty args'
376 where
377 applyMap [] nt cn pty args' = mkApp (P nt cn pty) args'
378 applyMap ((x, (n, args)) : ms) nt cn pty args'
379 | and ((length args == length args') :
380 (n == cn) : zipWith same args args') = P Ref x Erased
381 | otherwise = applyMap ms nt cn pty args'
382 same n (P _ n' _) = n == n'
383 same _ _ = False
384 applyMaps ms (App f a) = App (applyMaps ms f) (applyMaps ms a)
385 applyMaps ms t = t
387prune :: Bool -> -- ^ Convert single branches to projections (only useful at runtime)
388 SC -> SC
389prune proj (Case n alts)
390 = let alts' = filter notErased (map pruneAlt alts) in
391 case alts' of
392 [] -> ImpossibleCase
393 as@[ConCase cn i args sc] -> if proj then mkProj n 0 args sc
394 else Case n as
395 as -> Case n as
396 where pruneAlt (ConCase cn i ns sc) = ConCase cn i ns (prune proj sc)
397 pruneAlt (ConstCase c sc) = ConstCase c (prune proj sc)
398 pruneAlt (DefaultCase sc) = DefaultCase (prune proj sc)
400 notErased (DefaultCase (STerm Erased)) = False
401 notErased (DefaultCase ImpossibleCase) = False
402 notErased _ = True
404 mkProj n i [] sc = sc
405 mkProj n i (x : xs) sc = mkProj n (i + 1) xs (projRep x n i sc)
407 projRep :: Name -> Name -> Int -> SC -> SC
408 projRep arg n i (Case x alts)
409 | x == arg = ProjCase (Proj (P Bound n Erased) i)
410 (map (projRepAlt arg n i) alts)
411 | otherwise = Case x (map (projRepAlt arg n i) alts)
412 projRep arg n i (ProjCase t alts)
413 = ProjCase (projRepTm arg n i t) (map (projRepAlt arg n i) alts)
414 projRep arg n i (STerm t) = STerm (projRepTm arg n i t)
415 projRep arg n i c = c -- unmatched
417 projRepAlt arg n i (ConCase cn t args rhs)
418 = ConCase cn t args (projRep arg n i rhs)
419 projRepAlt arg n i (ConstCase t rhs)
420 = ConstCase t (projRep arg n i rhs)
421 projRepAlt arg n i (DefaultCase rhs)
422 = DefaultCase (projRep arg n i rhs)
424 projRepTm arg n i t = subst arg (Proj (P Bound n Erased) i) t
426prune _ t = t
428stripLambdas :: CaseDef -> CaseDef
429stripLambdas (CaseDef ns (STerm (Bind x (Lam _) sc)) tm)
430 = stripLambdas (CaseDef (ns ++ [x]) (STerm (instantiate (P Bound x Erased) sc)) tm)
431stripLambdas x = x