on 9469ba8 help sign in
Idris-dev/src/Core/CaseTree.hs
393 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 | ImpossibleCase -- already checked to be impossible
21 deriving (Eq, Ord)
22{-!
23deriving instance Binary SC
24!-}
26data CaseAlt = ConCase Name Int [Name] SC
27 | ConstCase Const SC
28 | DefaultCase SC
29 deriving (Show, Eq, Ord)
30{-!
31deriving instance Binary CaseAlt
32!-}
34instance Show SC where
35 show sc = show' 1 sc
36 where
37 show' i (Case n alts) = "case " ++ show n ++ " of\n" ++ indent i ++
38 showSep ("\n" ++ indent i) (map (showA i) alts)
39 show' i (ProjCase tm alts) = "case " ++ show tm ++ " of " ++
40 showSep ("\n" ++ indent i) (map (showA i) alts)
41 show' i (STerm tm) = show tm
42 show' i (UnmatchedCase str) = "error " ++ show str
43 show' i ImpossibleCase = "impossible"
45 indent i = concat $ take i (repeat " ")
47 showA i (ConCase n t args sc)
48 = show n ++ "(" ++ showSep (", ") (map show args) ++ ") => "
49 ++ show' (i+1) sc
50 showA i (ConstCase t sc)
51 = show t ++ " => " ++ show' (i+1) sc
52 showA i (DefaultCase sc)
53 = "_ => " ++ show' (i+1) sc
56type CaseTree = SC
57type Clause = ([Pat], (Term, Term))
58type CS = ([Term], Int)
60instance TermSize SC where
61 termsize (Case n as) = termsize as
62 termsize (STerm t) = termsize t
63 termsize _ = 1
65instance TermSize CaseAlt where
66 termsize (ConCase _ _ _ s) = termsize s
67 termsize (ConstCase _ s) = termsize s
68 termsize (DefaultCase s) = termsize s
70-- simple terms can be inlined trivially - good for primitives in particular
71small :: SC -> Bool
72small t = termsize t < 150
74namesUsed :: SC -> [Name]
75namesUsed sc = nub $ nu' [] sc where
76 nu' ps (Case n alts) = nub (concatMap (nua ps) alts) \\ [n]
77 nu' ps (STerm t) = nub $ nut ps t
78 nu' ps _ = []
80 nua ps (ConCase n i args sc) = nub (nu' (ps ++ args) sc) \\ args
81 nua ps (ConstCase _ sc) = nu' ps sc
82 nua ps (DefaultCase sc) = nu' ps sc
84 nut ps (P _ n _) | n `elem` ps = []
85 | otherwise = [n]
86 nut ps (App f a) = nut ps f ++ nut ps a
87 nut ps (Bind n (Let t v) sc) = nut ps v ++ nut (n:ps) sc
88 nut ps (Bind n b sc) = nut (n:ps) sc
89 nut ps _ = []
91-- Return all called functions, and which arguments are used in each argument position
92-- for the call, in order to help reduce compilation time, and trace all unused
93-- arguments
95findCalls :: SC -> [Name] -> [(Name, [[Name]])]
96findCalls sc topargs = nub $ nu' topargs sc where
97 nu' ps (Case n alts) = nub (concatMap (nua (n : ps)) alts)
98 nu' ps (STerm t) = nub $ nut ps t
99 nu' ps _ = []
101 nua ps (ConCase n i args sc) = nub (nu' (ps ++ args) sc)
102 nua ps (ConstCase _ sc) = nu' ps sc
103 nua ps (DefaultCase sc) = nu' ps sc
105 nut ps (P Ref n _) | n `elem` ps = []
106 | otherwise = [(n, [])] -- tmp
107 nut ps fn@(App f a)
108 | (P Ref n _, args) <- unApply fn
109 = if n `elem` ps then nut ps f ++ nut ps a
110 else [(n, map argNames args)] ++ concatMap (nut ps) args
111 | otherwise = nut ps f ++ nut ps a
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
114 nut ps _ = []
116 argNames tm = let ns = directUse tm in
117 filter (\x -> x `elem` ns) topargs
119-- Find names which are used directly (i.e. not in a function call) in a term
121directUse :: Eq n => TT n -> [n]
122directUse (P _ n _) = [n]
123directUse (Bind n (Let t v) sc) = nub $ directUse v ++ (directUse sc \\ [n])
124 ++ directUse t
125directUse (Bind n b sc) = nub $ directUse (binderTy b) ++ (directUse sc \\ [n])
126directUse fn@(App f a)
127 | (P Ref n _, args) <- unApply fn = [] -- need to know what n does with them
128 | otherwise = nub $ directUse f ++ directUse a
129directUse (Proj x i) = nub $ directUse x
130directUse _ = []
132-- Find all directly used arguments (i.e. used but not in function calls)
134findUsedArgs :: SC -> [Name] -> [Name]
135findUsedArgs sc topargs = filter (\x -> x `elem` topargs) (nub $ nu' sc) where
136 nu' (Case n alts) = n : concatMap nua alts
137 nu' (STerm t) = directUse t
138 nu' _ = []
140 nua (ConCase n i args sc) = nu' sc
141 nua (ConstCase _ sc) = nu' sc
142 nua (DefaultCase sc) = nu' sc
144data Phase = CompileTime | RunTime
145 deriving (Show, Eq)
147-- Generate a simple case tree
148-- Work Left to Right at Compile Time
150simpleCase :: Bool -> Bool -> Phase -> FC -> [([Name], Term, Term)] -> TC CaseDef
151simpleCase tc cover phase fc []
152 = return $ CaseDef [] (UnmatchedCase "No pattern clauses") []
153simpleCase tc cover phase fc cs
154 = let proj = phase == RunTime
155 pats = map (\ (avs, l, r) ->
156 (avs, rev phase (toPats tc l), (l, r))) cs
157 chkPats = mapM chkAccessible pats in
158 case chkPats of
159 OK pats ->
160 let numargs = length (fst (head pats))
161 ns = take numargs args
162 (tree, st) = runState
163 (match (rev phase ns) pats (defaultCase cover)) ([], numargs)
164 t = CaseDef ns (prune proj tree) (fst st) in
165 if proj then return (stripLambdas t) else return t
166 Error err -> Error (At fc err)
167 where args = map (\i -> MN i "e") [0..]
168 defaultCase True = STerm Erased
169 defaultCase False = UnmatchedCase "Error"
171 chkAccessible (avs, l, c) = do mapM_ (acc l) avs
172 return (l, c)
174 acc [] n = Error (Inaccessible n)
175 acc (PV x : xs) n | x == n = OK ()
176 acc (PCon _ _ ps : xs) n = acc (ps ++ xs) n
177 acc (_ : xs) n = acc xs n
179rev CompileTime = id
180rev _ = reverse
182data Pat = PCon Name Int [Pat]
183 | PConst Const
184 | PV Name
185 | PAny
186 deriving Show
188-- If there are repeated variables, take the *last* one (could be name shadowing
189-- in a where clause, so take the most recent).
191toPats :: Bool -> Term -> [Pat]
192toPats tc f = reverse (toPat tc (getArgs f)) where
193 getArgs (App f a) = a : getArgs f
194 getArgs _ = []
196toPat :: Bool -> [Term] -> [Pat]
197toPat tc tms = evalState (mapM (\x -> toPat' x []) tms) []
198 where
199 toPat' (P (DCon t a) n _) args = do args' <- mapM (\x -> toPat' x []) args
200 return $ PCon n t args'
201 -- Typecase
202 toPat' (P (TCon t a) n _) args | tc
203 = do args' <- mapM (\x -> toPat' x []) args
204 return $ PCon n t args'
205 toPat' (Constant IType) [] | tc = return $ PCon (UN "Int") 1 []
206 toPat' (Constant FlType) [] | tc = return $ PCon (UN "Float") 2 []
207 toPat' (Constant ChType) [] | tc = return $ PCon (UN "Char") 3 []
208 toPat' (Constant StrType) [] | tc = return $ PCon (UN "String") 4 []
209 toPat' (Constant PtrType) [] | tc = return $ PCon (UN "Ptr") 5 []
210 toPat' (Constant BIType) [] | tc = return $ PCon (UN "Integer") 6 []
212 toPat' (P Bound n _) [] = do ns <- get
213 if n `elem` ns
214 then return PAny
215 else do put (n : ns)
216 return (PV n)
217 toPat' (App f a) args = toPat' f (a : args)
218 toPat' (Constant x@(I _)) [] = return $ PConst x
219 toPat' _ _ = return PAny
222data Partition = Cons [Clause]
223 | Vars [Clause]
224 deriving Show
226isVarPat (PV _ : ps , _) = True
227isVarPat (PAny : ps , _) = True
228isVarPat _ = False
230isConPat (PCon _ _ _ : ps, _) = True
231isConPat (PConst _ : ps, _) = True
232isConPat _ = False
234partition :: [Clause] -> [Partition]
235partition [] = []
236partition ms@(m : _)
237 | isVarPat m = let (vars, rest) = span isVarPat ms in
238 Vars vars : partition rest
239 | isConPat m = let (cons, rest) = span isConPat ms in
240 Cons cons : partition rest
241partition xs = error $ "Partition " ++ show xs
243match :: [Name] -> [Clause] -> SC -- error case
244 -> State CS SC
245match [] (([], ret) : xs) err
246 = do (ts, v) <- get
247 put (ts ++ (map (fst.snd) xs), v)
248 case snd ret of
249 Impossible -> return ImpossibleCase
250 tm -> return $ STerm tm -- run out of arguments
251match vs cs err = do let ps = partition cs
252 cs <- mixture vs ps err
253 return cs
255mixture :: [Name] -> [Partition] -> SC -> State CS SC
256mixture vs [] err = return err
257mixture vs (Cons ms : ps) err = do fallthrough <- mixture vs ps err
258 conRule vs ms fallthrough
259mixture vs (Vars ms : ps) err = do fallthrough <- mixture vs ps err
260 varRule vs ms fallthrough
262data ConType = CName Name Int -- named constructor
263 | CConst Const -- constant, not implemented yet
265data Group = ConGroup ConType -- Constructor
266 [([Pat], Clause)] -- arguments and rest of alternative
268conRule :: [Name] -> [Clause] -> SC -> State CS SC
269conRule (v:vs) cs err = do groups <- groupCons cs
270 caseGroups (v:vs) groups err
272caseGroups :: [Name] -> [Group] -> SC -> State CS SC
273caseGroups (v:vs) gs err = do g <- altGroups gs
274 return $ Case v (sort g)
275 where
276 altGroups [] = return [DefaultCase err]
277 altGroups (ConGroup (CName n i) args : cs)
278 = do g <- altGroup n i args
279 rest <- altGroups cs
280 return (g : rest)
281 altGroups (ConGroup (CConst c) args : cs)
282 = do g <- altConstGroup c args
283 rest <- altGroups cs
284 return (g : rest)
286 altGroup n i gs = do (newArgs, nextCs) <- argsToAlt gs
287 matchCs <- match (newArgs ++ vs) nextCs err
288 return $ ConCase n i newArgs matchCs
289 altConstGroup n gs = do (_, nextCs) <- argsToAlt gs
290 matchCs <- match vs nextCs err
291 return $ ConstCase n matchCs
293argsToAlt :: [([Pat], Clause)] -> State CS ([Name], [Clause])
294argsToAlt [] = return ([], [])
295argsToAlt rs@((r, m) : rest)
296 = do newArgs <- getNewVars r
297 return (newArgs, addRs rs)
298 where
299 getNewVars [] = return []
300 getNewVars ((PV n) : ns) = do v <- getVar
301 nsv <- getNewVars ns
302 return (v : nsv)
303 getNewVars (_ : ns) = do v <- getVar
304 nsv <- getNewVars ns
305 return (v : nsv)
306 addRs [] = []
307 addRs ((r, (ps, res)) : rs) = ((r++ps, res) : addRs rs)
309 uniq i (UN n) = MN i n
310 uniq i n = n
312getVar :: State CS Name
313getVar = do (t, v) <- get; put (t, v+1); return (MN v "e")
315groupCons :: [Clause] -> State CS [Group]
316groupCons cs = gc [] cs
317 where
318 gc acc [] = return acc
319 gc acc ((p : ps, res) : cs) =
320 do acc' <- addGroup p ps res acc
321 gc acc' cs
322 addGroup p ps res acc = case p of
323 PCon con i args -> return $ addg con i args (ps, res) acc
324 PConst cval -> return $ addConG cval (ps, res) acc
325 pat -> fail $ show pat ++ " is not a constructor or constant (can't happen)"
327 addg con i conargs res [] = [ConGroup (CName con i) [(conargs, res)]]
328 addg con i conargs res (g@(ConGroup (CName n j) cs):gs)
329 | i == j = ConGroup (CName n i) (cs ++ [(conargs, res)]) : gs
330 | otherwise = g : addg con i conargs res gs
332 addConG con res [] = [ConGroup (CConst con) [([], res)]]
333 addConG con res (g@(ConGroup (CConst n) cs) : gs)
334 | con == n = ConGroup (CConst n) (cs ++ [([], res)]) : gs
335 | otherwise = g : addConG con res gs
337varRule :: [Name] -> [Clause] -> SC -> State CS SC
338varRule (v : vs) alts err =
339 do let alts' = map (repVar v) alts
340 match vs alts' err
341 where
342 repVar v (PV p : ps , (lhs, res)) = (ps, (lhs, subst p (P Bound v (V 0)) res))
343 repVar v (PAny : ps , res) = (ps, res)
345prune :: Bool -> -- ^ Convert single brances to projections (only useful at runtime)
346 SC -> SC
347prune proj (Case n alts)
348 = let alts' = filter notErased (map pruneAlt alts) in
349 case alts' of
350 [] -> ImpossibleCase
351 as@[ConCase cn i args sc] -> if proj then mkProj n 0 args sc
352 else Case n as
353 as -> Case n as
354 where pruneAlt (ConCase cn i ns sc) = ConCase cn i ns (prune proj sc)
355 pruneAlt (ConstCase c sc) = ConstCase c (prune proj sc)
356 pruneAlt (DefaultCase sc) = DefaultCase (prune proj sc)
358 notErased (DefaultCase (STerm Erased)) = False
359 notErased (DefaultCase ImpossibleCase) = False
360 notErased _ = True
362 mkProj n i [] sc = sc
363 mkProj n i (x : xs) sc = mkProj n (i + 1) xs (projRep x n i sc)
365 projRep :: Name -> Name -> Int -> SC -> SC
366 projRep arg n i (Case x alts)
367 | x == arg = ProjCase (Proj (P Bound n Erased) i)
368 (map (projRepAlt arg n i) alts)
369 | otherwise = Case x (map (projRepAlt arg n i) alts)
370 projRep arg n i (ProjCase t alts)
371 = ProjCase (projRepTm arg n i t) (map (projRepAlt arg n i) alts)
372 projRep arg n i (STerm t) = STerm (projRepTm arg n i t)
373 projRep arg n i c = c -- unmatched
375 projRepAlt arg n i (ConCase cn t args rhs)
376 = ConCase cn t args (projRep arg n i rhs)
377 projRepAlt arg n i (ConstCase t rhs)
378 = ConstCase t (projRep arg n i rhs)
379 projRepAlt arg n i (DefaultCase rhs)
380 = DefaultCase (projRep arg n i rhs)
382 projRepTm arg n i t = subst arg (Proj (P Bound n Erased) i) t
384prune _ t = t
386stripLambdas :: CaseDef -> CaseDef
387stripLambdas (CaseDef ns (STerm (Bind x (Lam _) sc)) tm)
388 = stripLambdas (CaseDef (ns ++ [x]) (STerm (instantiate (P Bound x Erased) sc)) tm)
389stripLambdas x = x