on 8063cfd help sign in
Idris-dev/src/Core/CaseTree.hs
386 lines 15 kB history raw
1{-# LANGUAGE PatternGuards #-}
3module Core.CaseTree(CaseDef(..), SC(..), CaseAlt(..), Phase(..), CaseTree,
4 simpleCase, small, namesUsed, findCalls, findUsedArgs) where
6import Core.TT
8import Control.Monad.State
9import Data.Maybe
10import Data.List hiding (partition)
11import Debug.Trace
13data CaseDef = CaseDef [Name] SC [Term]
14 deriving Show
16data SC = Case Name [CaseAlt] -- invariant: lowest tags first
17 | ProjCase Term [CaseAlt] -- special case for projections
18 | STerm Term
19 | UnmatchedCase String -- error message
20 deriving (Eq, Ord)
21{-!
22deriving instance Binary SC
23!-}
25data CaseAlt = ConCase Name Int [Name] SC
26 | ConstCase Const SC
27 | DefaultCase SC
28 deriving (Show, Eq, Ord)
29{-!
30deriving instance Binary CaseAlt
31!-}
33instance Show SC where
34 show sc = show' 1 sc
35 where
36 show' i (Case n alts) = "case " ++ show n ++ " of\n" ++ indent i ++
37 showSep ("\n" ++ indent i) (map (showA i) alts)
38 show' i (ProjCase tm alts) = "case " ++ show tm ++ " of " ++
39 showSep ("\n" ++ indent i) (map (showA i) alts)
40 show' i (STerm tm) = show tm
41 show' i (UnmatchedCase str) = "error " ++ show str
43 indent i = concat $ take i (repeat " ")
45 showA i (ConCase n t args sc)
46 = show n ++ "(" ++ showSep (", ") (map show args) ++ ") => "
47 ++ show' (i+1) sc
48 showA i (ConstCase t sc)
49 = show t ++ " => " ++ show' (i+1) sc
50 showA i (DefaultCase sc)
51 = "_ => " ++ show' (i+1) sc
54type CaseTree = SC
55type Clause = ([Pat], (Term, Term))
56type CS = ([Term], Int)
58instance TermSize SC where
59 termsize (Case n as) = termsize as
60 termsize (STerm t) = termsize t
61 termsize _ = 1
63instance TermSize CaseAlt where
64 termsize (ConCase _ _ _ s) = termsize s
65 termsize (ConstCase _ s) = termsize s
66 termsize (DefaultCase s) = termsize s
68-- simple terms can be inlined trivially - good for primitives in particular
69small :: SC -> Bool
70small t = termsize t < 150
72namesUsed :: SC -> [Name]
73namesUsed sc = nub $ nu' [] sc where
74 nu' ps (Case n alts) = nub (concatMap (nua ps) alts) \\ [n]
75 nu' ps (STerm t) = nub $ nut ps t
76 nu' ps _ = []
78 nua ps (ConCase n i args sc) = nub (nu' (ps ++ args) sc) \\ args
79 nua ps (ConstCase _ sc) = nu' ps sc
80 nua ps (DefaultCase sc) = nu' ps sc
82 nut ps (P _ n _) | n `elem` ps = []
83 | otherwise = [n]
84 nut ps (App f a) = nut ps f ++ nut ps a
85 nut ps (Bind n (Let t v) sc) = nut ps v ++ nut (n:ps) sc
86 nut ps (Bind n b sc) = nut (n:ps) sc
87 nut ps _ = []
89-- Return all called functions, and which arguments are used in each argument position
90-- for the call, in order to help reduce compilation time, and trace all unused
91-- arguments
93findCalls :: SC -> [Name] -> [(Name, [[Name]])]
94findCalls sc topargs = nub $ nu' topargs sc where
95 nu' ps (Case n alts) = nub (concatMap (nua (n : ps)) alts)
96 nu' ps (STerm t) = nub $ nut ps t
97 nu' ps _ = []
99 nua ps (ConCase n i args sc) = nub (nu' (ps ++ args) sc)
100 nua ps (ConstCase _ sc) = nu' ps sc
101 nua ps (DefaultCase sc) = nu' ps sc
103 nut ps (P Ref n _) | n `elem` ps = []
104 | otherwise = [(n, [])] -- tmp
105 nut ps fn@(App f a)
106 | (P Ref n _, args) <- unApply fn
107 = if n `elem` ps then nut ps f ++ nut ps a
108 else [(n, map argNames args)] ++ concatMap (nut ps) args
109 | otherwise = nut ps f ++ nut ps a
110 nut ps (Bind n (Let t v) sc) = nut ps v ++ nut (n:ps) sc
111 nut ps (Bind n b sc) = nut (n:ps) sc
112 nut ps _ = []
114 argNames tm = let ns = directUse tm in
115 filter (\x -> x `elem` ns) topargs
117-- Find names which are used directly (i.e. not in a function call) in a term
119directUse :: Eq n => TT n -> [n]
120directUse (P _ n _) = [n]
121directUse (Bind n (Let t v) sc) = nub $ directUse v ++ (directUse sc \\ [n])
122 ++ directUse t
123directUse (Bind n b sc) = nub $ directUse (binderTy b) ++ (directUse sc \\ [n])
124directUse fn@(App f a)
125 | (P Ref n _, args) <- unApply fn = [] -- need to know what n does with them
126 | otherwise = nub $ directUse f ++ directUse a
127directUse (Proj x i) = nub $ directUse x
128directUse _ = []
130-- Find all directly used arguments (i.e. used but not in function calls)
132findUsedArgs :: SC -> [Name] -> [Name]
133findUsedArgs sc topargs = filter (\x -> x `elem` topargs) (nub $ nu' sc) where
134 nu' (Case n alts) = n : concatMap nua alts
135 nu' (STerm t) = directUse t
136 nu' _ = []
138 nua (ConCase n i args sc) = nu' sc
139 nua (ConstCase _ sc) = nu' sc
140 nua (DefaultCase sc) = nu' sc
142data Phase = CompileTime | RunTime
143 deriving (Show, Eq)
145-- Generate a simple case tree
146--
148simpleCase :: Bool -> Bool -> Phase -> FC -> [([Name], Term, Term)] -> TC CaseDef
149simpleCase tc cover phase fc []
150 = return $ CaseDef [] (UnmatchedCase "No pattern clauses") []
151simpleCase tc cover phase fc cs
152 = let proj = phase == RunTime
153 pats = map (\ (avs, l, r) ->
154 (avs, reverse (toPats tc l), (l, r))) cs
155 chkPats = mapM chkAccessible pats in
156 case chkPats of
157 OK pats ->
158 let numargs = length (fst (head pats))
159 ns = take numargs args
160 (tree, st) = runState
161 (match (reverse ns) pats (defaultCase cover)) ([], numargs)
162 t = CaseDef ns (prune proj tree) (fst st) in
163 if proj then return (stripLambdas t) else return t
164 Error err -> Error (At fc err)
165 where args = map (\i -> MN i "e") [0..]
166 defaultCase True = STerm Erased
167 defaultCase False = UnmatchedCase "Error"
169 chkAccessible (avs, l, c) = do mapM_ (acc l) avs
170 return (l, c)
172 acc [] n = Error (Inaccessible n)
173 acc (PV x : xs) n | x == n = OK ()
174 acc (PCon _ _ ps : xs) n = acc (ps ++ xs) n
175 acc (_ : xs) n = acc xs n
177data Pat = PCon Name Int [Pat]
178 | PConst Const
179 | PV Name
180 | PAny
181 deriving Show
183-- If there are repeated variables, take the *last* one (could be name shadowing
184-- in a where clause, so take the most recent).
186toPats :: Bool -> Term -> [Pat]
187toPats tc f = reverse (toPat tc (getArgs f)) where
188 getArgs (App f a) = a : getArgs f
189 getArgs _ = []
191toPat :: Bool -> [Term] -> [Pat]
192toPat tc tms = evalState (mapM (\x -> toPat' x []) tms) []
193 where
194 toPat' (P (DCon t a) n _) args = do args' <- mapM (\x -> toPat' x []) args
195 return $ PCon n t args'
196 -- Typecase
197 toPat' (P (TCon t a) n _) args | tc
198 = do args' <- mapM (\x -> toPat' x []) args
199 return $ PCon n t args'
200 toPat' (Constant IType) [] | tc = return $ PCon (UN "Int") 1 []
201 toPat' (Constant FlType) [] | tc = return $ PCon (UN "Float") 2 []
202 toPat' (Constant ChType) [] | tc = return $ PCon (UN "Char") 3 []
203 toPat' (Constant StrType) [] | tc = return $ PCon (UN "String") 4 []
204 toPat' (Constant PtrType) [] | tc = return $ PCon (UN "Ptr") 5 []
205 toPat' (Constant BIType) [] | tc = return $ PCon (UN "Integer") 6 []
207 toPat' (P Bound n _) [] = do ns <- get
208 if n `elem` ns
209 then return PAny
210 else do put (n : ns)
211 return (PV n)
212 toPat' (App f a) args = toPat' f (a : args)
213 toPat' (Constant x@(I _)) [] = return $ PConst x
214 toPat' _ _ = return PAny
217data Partition = Cons [Clause]
218 | Vars [Clause]
219 deriving Show
221isVarPat (PV _ : ps , _) = True
222isVarPat (PAny : ps , _) = True
223isVarPat _ = False
225isConPat (PCon _ _ _ : ps, _) = True
226isConPat (PConst _ : ps, _) = True
227isConPat _ = False
229partition :: [Clause] -> [Partition]
230partition [] = []
231partition ms@(m : _)
232 | isVarPat m = let (vars, rest) = span isVarPat ms in
233 Vars vars : partition rest
234 | isConPat m = let (cons, rest) = span isConPat ms in
235 Cons cons : partition rest
236partition xs = error $ "Partition " ++ show xs
238match :: [Name] -> [Clause] -> SC -- error case
239 -> State CS SC
240match [] (([], ret) : xs) err
241 = do (ts, v) <- get
242 put (ts ++ (map (fst.snd) xs), v)
243 return $ STerm (snd ret) -- run out of arguments
244match vs cs err = do let ps = partition cs
245 cs <- mixture vs ps err
246 return cs
248mixture :: [Name] -> [Partition] -> SC -> State CS SC
249mixture vs [] err = return err
250mixture vs (Cons ms : ps) err = do fallthrough <- mixture vs ps err
251 conRule vs ms fallthrough
252mixture vs (Vars ms : ps) err = do fallthrough <- mixture vs ps err
253 varRule vs ms fallthrough
255data ConType = CName Name Int -- named constructor
256 | CConst Const -- constant, not implemented yet
258data Group = ConGroup ConType -- Constructor
259 [([Pat], Clause)] -- arguments and rest of alternative
261conRule :: [Name] -> [Clause] -> SC -> State CS SC
262conRule (v:vs) cs err = do groups <- groupCons cs
263 caseGroups (v:vs) groups err
265caseGroups :: [Name] -> [Group] -> SC -> State CS SC
266caseGroups (v:vs) gs err = do g <- altGroups gs
267 return $ Case v (sort g)
268 where
269 altGroups [] = return [DefaultCase err]
270 altGroups (ConGroup (CName n i) args : cs)
271 = do g <- altGroup n i args
272 rest <- altGroups cs
273 return (g : rest)
274 altGroups (ConGroup (CConst c) args : cs)
275 = do g <- altConstGroup c args
276 rest <- altGroups cs
277 return (g : rest)
279 altGroup n i gs = do (newArgs, nextCs) <- argsToAlt gs
280 matchCs <- match (newArgs ++ vs) nextCs err
281 return $ ConCase n i newArgs matchCs
282 altConstGroup n gs = do (_, nextCs) <- argsToAlt gs
283 matchCs <- match vs nextCs err
284 return $ ConstCase n matchCs
286argsToAlt :: [([Pat], Clause)] -> State CS ([Name], [Clause])
287argsToAlt [] = return ([], [])
288argsToAlt rs@((r, m) : rest)
289 = do newArgs <- getNewVars r
290 return (newArgs, addRs rs)
291 where
292 getNewVars [] = return []
293 getNewVars ((PV n) : ns) = do v <- getVar
294 nsv <- getNewVars ns
295 return (v : nsv)
296 getNewVars (_ : ns) = do v <- getVar
297 nsv <- getNewVars ns
298 return (v : nsv)
299 addRs [] = []
300 addRs ((r, (ps, res)) : rs) = ((r++ps, res) : addRs rs)
302 uniq i (UN n) = MN i n
303 uniq i n = n
305getVar :: State CS Name
306getVar = do (t, v) <- get; put (t, v+1); return (MN v "e")
308groupCons :: [Clause] -> State CS [Group]
309groupCons cs = gc [] cs
310 where
311 gc acc [] = return acc
312 gc acc ((p : ps, res) : cs) =
313 do acc' <- addGroup p ps res acc
314 gc acc' cs
315 addGroup p ps res acc = case p of
316 PCon con i args -> return $ addg con i args (ps, res) acc
317 PConst cval -> return $ addConG cval (ps, res) acc
318 pat -> fail $ show pat ++ " is not a constructor or constant (can't happen)"
320 addg con i conargs res [] = [ConGroup (CName con i) [(conargs, res)]]
321 addg con i conargs res (g@(ConGroup (CName n j) cs):gs)
322 | i == j = ConGroup (CName n i) (cs ++ [(conargs, res)]) : gs
323 | otherwise = g : addg con i conargs res gs
325 addConG con res [] = [ConGroup (CConst con) [([], res)]]
326 addConG con res (g@(ConGroup (CConst n) cs) : gs)
327 | con == n = ConGroup (CConst n) (cs ++ [([], res)]) : gs
328 | otherwise = g : addConG con res gs
330varRule :: [Name] -> [Clause] -> SC -> State CS SC
331varRule (v : vs) alts err =
332 do let alts' = map (repVar v) alts
333 match vs alts' err
334 where
335 repVar v (PV p : ps , (lhs, res)) = (ps, (lhs, subst p (P Bound v (V 0)) res))
336 repVar v (PAny : ps , res) = (ps, res)
338prune :: Bool -> -- ^ Convert single brances to projections (only useful at runtime)
339 SC -> SC
340prune proj (Case n alts)
341 = let alts' = map pruneAlt $
342 filter notErased alts in
343 case alts' of
344 [] -> STerm Erased
345 as@[ConCase cn i args sc] -> if proj then mkProj n 0 args sc
346 else Case n as
347 as -> Case n as
348 where pruneAlt (ConCase cn i ns sc) = ConCase cn i ns (prune proj sc)
349 pruneAlt (ConstCase c sc) = ConstCase c (prune proj sc)
350 pruneAlt (DefaultCase sc) = DefaultCase (prune proj sc)
352 notErased (DefaultCase (STerm Erased)) = False
353 notErased _ = True
355 mkProj n i [] sc = sc
356 mkProj n i (x : xs) sc = mkProj n (i + 1) xs (projRep x n i sc)
358 projRep :: Name -> Name -> Int -> SC -> SC
359 projRep arg n i (Case x alts)
360 | x == arg = ProjCase (Proj (P Bound n Erased) i)
361 (map (projRepAlt arg n i) alts)
362 | otherwise = Case x (map (projRepAlt arg n i) alts)
363 projRep arg n i (ProjCase t alts)
364 = ProjCase (projRepTm arg n i t) (map (projRepAlt arg n i) alts)
365 projRep arg n i (STerm t) = STerm (projRepTm arg n i t)
366 projRep arg n i c = c -- unmatched
368 projRepAlt arg n i (ConCase cn t args rhs)
369 = ConCase cn t args (projRep arg n i rhs)
370 projRepAlt arg n i (ConstCase t rhs)
371 = ConstCase t (projRep arg n i rhs)
372 projRepAlt arg n i (DefaultCase rhs)
373 = DefaultCase (projRep arg n i rhs)
375 projRepTm arg n i t = subst arg (Proj (P Bound n Erased) i) t
377prune _ t = t
379stripLambdas :: CaseDef -> CaseDef
380stripLambdas (CaseDef ns (STerm (Bind x (Lam _) sc)) tm)
381 = stripLambdas (CaseDef (ns ++ [x]) (STerm (instantiate (P Bound x Erased) sc)) tm)
382stripLambdas x = x