on fc0a04c help sign in
Idris-dev/src/Idris/Coverage.hs
708 lines 30 kB history raw
1{-# LANGUAGE PatternGuards #-}
3module Idris.Coverage where
5import Core.TT
6import Core.Evaluate
7import Core.CaseTree
9import Idris.AbsSyntax
10import Idris.Delaborate
11import Idris.Error
13import Data.List
14import Data.Either
15import Data.Maybe
16import Debug.Trace
18import Control.Monad.State
20mkPatTm :: PTerm -> Idris Term
21mkPatTm t = do i <- getIState
22 let timp = addImpl' True [] [] i t
23 evalStateT (toTT timp) 0
24 where
25 toTT (PRef _ n) = do i <- lift getIState
26 case lookupDef n (tt_ctxt i) of
27 [TyDecl nt _] -> return $ P nt n Erased
28 _ -> return $ P Ref n Erased
29 toTT (PApp _ t args) = do t' <- toTT t
30 args' <- mapM (toTT . getTm) args
31 return $ mkApp t' args'
32 toTT _ = do v <- get
33 put (v + 1)
34 return (P Bound (MN v "imp") Erased)
36-- Given a list of LHSs, generate a extra clauses which cover the remaining
37-- cases. The ones which haven't been provided are marked 'absurd' so that the
38-- checker will make sure they can't happen.
40-- This will only work after the given clauses have been typechecked and the
41-- names are fully explicit!
43genClauses :: FC -> Name -> [Term] -> [PClause] -> Idris [PTerm]
44genClauses fc n xs given
45 = do i <- getIState
46 let lhss = map (getLHS i) xs
47 let argss = transpose lhss
48 let all_args = map (genAll i) argss
49 logLvl 5 $ "COVERAGE of " ++ show n
50 logLvl 5 $ show (map length argss) ++ "\n" ++ show (map length all_args)
51 logLvl 10 $ show argss ++ "\n" ++ show all_args
52 logLvl 10 $ "Original: \n" ++
53 showSep "\n" (map (\t -> showImp Nothing True False (delab' i t True True)) xs)
54 -- add an infinite supply of explicit arguments to update the possible
55 -- cases for (the return type may be variadic, or function type, sp
56 -- there may be more case splitting that the idris_implicits record
57 -- suggests)
58 let parg = case lookupCtxt n (idris_implicits i) of
59 (p : _) -> p ++ repeat (PExp 0 False Placeholder "")
60 _ -> repeat (pexp Placeholder)
61 let tryclauses = mkClauses parg all_args
62 logLvl 2 $ show (length tryclauses) ++ " initially to check"
63 logLvl 5 $ showSep "\n" (map (showImp Nothing True False) tryclauses)
64 let new = filter (noMatch i) (nub tryclauses)
65 logLvl 1 $ show (length new) ++ " clauses to check for impossibility"
66 logLvl 5 $ "New clauses: \n" ++ showSep "\n" (map (showImp Nothing True False) new)
67-- ++ " from:\n" ++ showSep "\n" (map (showImp True) tryclauses)
68 return new
69-- return (map (\t -> PClause n t [] PImpossible []) new)
70 where getLHS i term
71 | (f, args) <- unApply term = map (\t -> delab' i t True True) args
72 | otherwise = []
74 lhsApp (PClause _ _ l _ _ _) = l
75 lhsApp (PWith _ _ l _ _ _) = l
77 noMatch i tm = all (\x -> case matchClause i (delab' i x True True) tm of
78 Right _ -> False
79 Left miss -> True) xs
82 mkClauses :: [PArg] -> [[PTerm]] -> [PTerm]
83 mkClauses parg args
84 | all (== [Placeholder]) args = []
85 mkClauses parg args
86 = do args' <- mkArg args
87 let tm = PApp fc (PRef fc n) (zipWith upd args' parg)
88 return tm
89 where
90 mkArg :: [[PTerm]] -> [[PTerm]]
91 mkArg [] = return []
92 mkArg (a : as) = do a' <- a
93 as' <- mkArg as
94 return (a':as')
96fnub xs = fnub' [] xs
98fnub' acc (x : xs) | x `qelem` acc = fnub' acc (filter (not.(quickEq x)) xs)
99 | otherwise = fnub' (x : acc) xs
100fnub' acc [] = acc
102-- quick check for constructor equality
103quickEq :: PTerm -> PTerm -> Bool
104quickEq (PRef _ n) (PRef _ n') = n == n'
105quickEq (PApp _ t as) (PApp _ t' as')
106 | length as == length as'
107 = quickEq t t' && and (zipWith quickEq (map getTm as) (map getTm as'))
108quickEq Placeholder Placeholder = True
109quickEq x y = False
111qelem x [] = False
112qelem x (y : ys) | x `quickEq` y = True
113 | otherwise = qelem x ys
115-- FIXME: Just look for which one is the deepest, then generate all
116-- possibilities up to that depth.
118genAll :: IState -> [PTerm] -> [PTerm]
119genAll i args
120 = case filter (/=Placeholder) $ fnub (concatMap otherPats (fnub args)) of
121 [] -> [Placeholder]
122 xs -> inventConsts xs
123 where
124 -- if they're constants, invent a new one to make sure that
125 -- constants which are not explicitly handled are covered
126 inventConsts cs@(PConstant c : _) = map PConstant (ic' (mapMaybe getConst cs))
127 where getConst (PConstant c) = Just c
128 getConst _ = Nothing
129 inventConsts xs = xs
131 -- try constants until they're not in the list.
132 -- FIXME: It is, of course, possible that someone has enumerated all
133 -- the constants and matched on them (maybe in generated code) and this
134 -- will be really slow. This is sufficiently unlikely that we won't
135 -- worry for now...
137 ic' xs@(I _ : _) = firstMissing xs (lotsOfNums I)
138 ic' xs@(BI _ : _) = firstMissing xs (lotsOfNums BI)
139 ic' xs@(Fl _ : _) = firstMissing xs (lotsOfNums Fl)
140 ic' xs@(B8 _ : _) = firstMissing xs (lotsOfNums B8)
141 ic' xs@(B16 _ : _) = firstMissing xs (lotsOfNums B16)
142 ic' xs@(B32 _ : _) = firstMissing xs (lotsOfNums B32)
143 ic' xs@(B64 _ : _) = firstMissing xs (lotsOfNums B64)
144 ic' xs@(Ch _ : _) = firstMissing xs lotsOfChars
145 ic' xs@(Str _ : _) = firstMissing xs lotsOfStrings
146 -- TODO: Bit vectors
147 -- The rest are types with only one case
148 ic' xs = xs
150 firstMissing cs (x : xs) | x `elem` cs = firstMissing cs xs
151 | otherwise = x : cs
153 lotsOfNums t = map t [0..]
154 lotsOfChars = map Ch ['a'..]
155 lotsOfStrings = map Str (map (("some string " ++).show) [1..])
157 conForm (PApp _ (PRef fc n) _) = isConName n (tt_ctxt i)
158 conForm (PRef fc n) = isConName n (tt_ctxt i)
159 conForm _ = False
161 nubMap f acc [] = acc
162 nubMap f acc (x : xs) = nubMap f (fnub' acc (f x)) xs
164 otherPats :: PTerm -> [PTerm]
165 otherPats o@(PRef fc n) = ops fc n [] o
166 otherPats o@(PApp _ (PRef fc n) xs) = ops fc n xs o
167 otherPats o@(PPair fc l r)
168 = ops fc pairCon
169 ([pimp (UN "A") Placeholder True,
170 pimp (UN "B") Placeholder True] ++
171 [pexp l, pexp r]) o
172 otherPats o@(PDPair fc t _ v)
173 = ops fc (UN "Ex_intro")
174 ([pimp (UN "a") Placeholder True,
175 pimp (UN "P") Placeholder True] ++
176 [pexp t,pexp v]) o
177 otherPats o@(PConstant c) = return o
178 otherPats arg = return Placeholder
180 ops fc n xs o
181 | (TyDecl c@(DCon _ arity) ty : _) <- lookupDef n (tt_ctxt i)
182 = do xs' <- mapM otherPats (map getExpTm xs)
183 let p = resugar (PApp fc (PRef fc n) (zipWith upd xs' xs))
184 let tyn = getTy n (tt_ctxt i)
185 case lookupCtxt tyn (idris_datatypes i) of
186 (TI ns _ _ : _) -> p : map (mkPat fc) (ns \\ [n])
187 _ -> [p]
188 ops fc n arg o = return Placeholder
190 getExpTm (PImp _ True _ _ _ _) = Placeholder -- machine inferred, no point!
191 getExpTm t = getTm t
193 -- put it back to its original form
194 resugar (PApp _ (PRef fc (UN "Ex_intro")) [_,_,t,v])
195 = PDPair fc (getTm t) Placeholder (getTm v)
196 resugar (PApp _ (PRef fc n) [_,_,l,r])
197 | n == pairCon
198 = PPair fc (getTm l) (getTm r)
199 resugar t = t
201 dropForce force (x : xs) i | i `elem` force
202 = upd Placeholder x : dropForce force xs (i + 1)
203 dropForce force (x : xs) i = x : dropForce force xs (i + 1)
204 dropForce _ [] _ = []
207 getTy n ctxt = case lookupTy n ctxt of
208 (t : _) -> case unApply (getRetTy t) of
209 (P _ tyn _, _) -> tyn
210 x -> error $ "Can't happen getTy 1 " ++ show (n, x)
211 _ -> error "Can't happen getTy 2"
213 mkPat fc x = case lookupCtxt x (idris_implicits i) of
214 (pargs : _)
215 -> PApp fc (PRef fc x) (map (upd Placeholder) pargs)
216 _ -> error "Can't happen - genAll"
218upd p' p = p { getTm = p' }
220-- Check if, in a given type n, the constructor cn : ty is strictly positive,
221-- and update the context accordingly
223checkPositive :: Name -> (Name, Type) -> Idris ()
224checkPositive n (cn, ty)
225 = do let p = cp ty
226 i <- getIState
227 let tot = if p then Total (args ty) else Partial NotPositive
228 let ctxt' = setTotal cn tot (tt_ctxt i)
229 putIState (i { tt_ctxt = ctxt' })
230 logLvl 5 $ "Constructor " ++ show cn ++ " is " ++ show tot
231 addIBC (IBCTotal cn tot)
232 where
233 args t = [0..length (getArgTys t)-1]
235 cp (Bind n (Pi aty) sc) = posArg aty && cp sc
236 cp t = True
238 posArg (Bind _ (Pi nty) sc)
239 | (P _ n' _, args) <- unApply nty
240 = n /= n' && posArg sc
241 posArg t = True
243calcProd :: IState -> FC -> Name -> [([Name], Term, Term)] -> Idris Totality
244calcProd i fc topn pats
245 = cp topn pats []
246 where
247 -- every application of n must be in an argument of a coinductive
248 -- constructor, in every function reachable from here in the
249 -- call graph.
250 cp n pats done = do patsprod <- mapM (prodRec n done) pats
251 if (and patsprod)
252 then return Productive
253 else return (Partial NotProductive)
255 prodRec :: Name -> [Name] -> ([Name], Term, Term) -> Idris Bool
256 prodRec n done _ | n `elem` done = return True
257 prodRec n done (_, _, tm) = prod n done False tm
259 prod :: Name -> [Name] -> Bool -> Term -> Idris Bool
260 prod n done ok ap@(App _ _)
261 | (P _ (UN "lazy") _, [_, arg]) <- unApply ap = prod n done ok arg
262 | (P nt f _, args) <- unApply ap
263 = do recOK <- checkProdRec (n:done) f
264 let ctxt = tt_ctxt i
265 let [ty] = lookupTy f ctxt -- must exist!
266 let co = cotype nt f ty in
267 if (not recOK) then return False else
268 if f == topn
269 then do argsprod <- mapM (prod n done co) args
270 return (and (ok : argsprod) )
271 else do argsprod <- mapM (prod n done co) args
272 return (and argsprod)
273 prod n done ok (App f a) = liftM2 (&&) (prod n done False f)
274 (prod n done False a)
275 prod n done ok (Bind _ (Let t v) sc)
276 = liftM2 (&&) (prod n done False v) (prod n done False v)
277 prod n done ok (Bind _ b sc) = prod n done ok sc
278 prod n done ok t = return True
280 checkProdRec :: [Name] -> Name -> Idris Bool
281 checkProdRec done f
282 = case lookupCtxt f (idris_patdefs i) of
283 [(def, _)] -> do ok <- mapM (prodRec f done) def
284 return (and ok)
285 _ -> return True -- defined elsewhere, can't call topn
287 cotype (DCon _ _) n ty
288 | (P _ t _, _) <- unApply (getRetTy ty)
289 = case lookupCtxt t (idris_datatypes i) of
290 [TI _ True _] -> True
291 _ -> False
292 cotype nt n ty = False
294calcTotality :: [Name] -> FC -> Name -> [([Name], Term, Term)]
295 -> Idris Totality
296calcTotality path fc n pats
297 = do i <- getIState
298 let opts = case lookupCtxt n (idris_flags i) of
299 [fs] -> fs
300 _ -> []
301 case mapMaybe (checkLHS i) (map (\ (_, l, r) -> l) pats) of
302 (failure : _) -> return failure
303 _ -> if (Coinductive `elem` opts)
304 then calcProd i fc n pats
305 else checkSizeChange n
306 where
307 checkLHS i (P _ fn _)
308 = case lookupTotal fn (tt_ctxt i) of
309 [Partial _] -> return (Partial (Other [fn]))
310 _ -> Nothing
311 checkLHS i (App f a) = mplus (checkLHS i f) (checkLHS i a)
312 checkLHS _ _ = Nothing
314checkTotality :: [Name] -> FC -> Name -> Idris Totality
315checkTotality path fc n
316 | n `elem` path = return (Partial (Mutual (n : path)))
317 | otherwise = do
318 t <- getTotality n
319 updateContext (simplifyCasedef n)
320 ctxt <- getContext
321 i <- getIState
322 let opts = case lookupCtxt n (idris_flags i) of
323 [fs] -> fs
324 _ -> []
325 t' <- case t of
326 Unchecked ->
327 case lookupDef n ctxt of
328 [CaseOp _ _ _ pats _] ->
329 do t' <- if AssertTotal `elem` opts
330 then return $ Total []
331 else calcTotality path fc n pats
332 setTotality n t'
333 addIBC (IBCTotal n t')
334 -- if it's not total, it can't reduce, to keep
335 -- typechecking decidable
336 case t' of
337 p@(Partial _) ->
338 do setAccessibility n Frozen
339 addIBC (IBCAccess n Frozen)
340 logLvl 5 $ "HIDDEN: "
341 ++ show n ++ show p
342 _ -> return ()
343 return t'
344 _ -> return $ Total []
345 x -> return x
346 case t' of
347 Total _ -> return t'
348 Productive -> return t'
349 e -> do w <- cmdOptType WarnPartial
350 if TotalFn `elem` opts
351 then totalityError t'
352 else do when (w && not (PartialFn `elem` opts)) $
353 warnPartial n t'
354 return t'
355 where
356 totalityError t = tclift $ tfail (At fc (Msg (show n ++ " is " ++ show t)))
358 warnPartial n t
359 = do i <- getIState
360 case lookupDef n (tt_ctxt i) of
361 [x] -> do
362 iputStrLn $ show fc ++ ":Warning - " ++ show n ++ " is " ++ show t
363-- ++ "\n" ++ show x
364-- let cg = lookupCtxtName Nothing n (idris_callgraph i)
365-- iputStrLn (show cg)
368checkDeclTotality :: (FC, Name) -> Idris Totality
369checkDeclTotality (fc, n)
370 = do logLvl 2 $ "Checking " ++ show n ++ " for totality"
371-- buildSCG (fc, n)
372-- logLvl 2 $ "Built SCG"
373 checkTotality [] fc n
375-- Calculate the size change graph for this definition
377-- SCG for a function f consists of a list of:
378-- (g, [(a1, sizechange1), (a2, sizechange2), ..., (an, sizechangen)])
380-- where g is a function called
381-- a1 ... an are the arguments of f in positions 1..n of g
382-- sizechange1 ... sizechange2 is how their size has changed wrt the input
383-- to f
384-- Nothing, if the argument is unrelated to the input
386buildSCG :: (FC, Name) -> Idris ()
387buildSCG (_, n) = do
388 ist <- getIState
389 case lookupCtxt n (idris_callgraph ist) of
390 [cg] -> case lookupDef n (tt_ctxt ist) of
391 [CaseOp _ _ pats _ cd] ->
392 let (args, sc) = cases_totcheck cd in
393 do logLvl 2 $ "Building SCG for " ++ show n ++ " from\n"
394 ++ show pats ++ "\n" ++ show sc
395 let newscg = buildSCG' ist (rights pats) args
396 logLvl 5 $ show newscg
397 addToCG n ( cg { scg = newscg } )
398 [] -> logLvl 5 $ "Could not build SCG for " ++ show n ++ "\n"
399 x -> error $ "buildSCG: " ++ show (n, x)
401buildSCG' :: IState -> [(Term, Term)] -> [Name] -> [SCGEntry]
402buildSCG' ist pats args = nub $ concatMap scgPat pats where
403 scgPat (lhs, rhs) = let (f, pargs) = unApply (dePat lhs) in
404 findCalls (dePat rhs) (patvars lhs) pargs
406 findCalls ap@(App f a) pvs pargs
407 | (P _ (UN "lazy") _, [_, arg]) <- unApply ap
408 = findCalls arg pvs pargs
409 | (P _ n _, args) <- unApply ap
410 = mkChange n args pargs ++
411 concatMap (\x -> findCalls x pvs pargs) args
412 findCalls (App f a) pvs pargs
413 = findCalls f pvs pargs ++ findCalls a pvs pargs
414 findCalls (Bind n (Let t v) e) pvs pargs
415 = findCalls v pvs pargs ++ findCalls e (n : pvs) pargs
416 findCalls (Bind n _ e) pvs pargs
417 = findCalls e (n : pvs) pargs
418 findCalls (P _ f _ ) pvs pargs
419 | not (f `elem` pvs) = [(f, [])]
420 findCalls _ _ _ = []
422 expandToArity n args
423 = case lookupTy n (tt_ctxt ist) of
424 [ty] -> expand 0 (normalise (tt_ctxt ist) [] ty) args
425 _ -> args
426 where expand i (Bind n (Pi _) sc) (x : xs) = x : expand (i + 1) sc xs
427 expand i (Bind n (Pi _) sc) [] = Just (i, Same) : expand (i + 1) sc []
428 expand i _ xs = xs
430 mkChange n args pargs = [(n, expandToArity n (sizes args))]
431 where
432 sizes [] = []
433 sizes (a : as) = checkSize a pargs 0 : sizes as
435 -- find which argument in pargs <a> is smaller than, if any
436 checkSize a (p : ps) i
437 | a == p = Just (i, Same)
438 | smaller Nothing a (p, Nothing) = Just (i, Smaller)
439 | otherwise = checkSize a ps (i + 1)
440 checkSize a [] i = Nothing
442 -- the smaller thing we find must be the same type as <a>, and
443 -- not be coinductive - so carry the type of the constructor we've
444 -- gone under.
446 smaller (Just tyn) a (t, Just tyt)
447 | a == t = isInductive (fst (unApply (getRetTy tyn)))
448 (fst (unApply (getRetTy tyt)))
449 smaller ty a (ap@(App f s), _)
450 | (P (DCon _ _) n _, args) <- unApply ap
451 = let tyn = getType n in
452 any (smaller (ty `mplus` Just tyn) a)
453 (zip args (map toJust (getArgTys tyn)))
454 -- check higher order recursive arguments
455 smaller ty (App f s) a = smaller ty f a
456 smaller _ _ _ = False
458 toJust (n, t) = Just t
460 getType n = case lookupTy n (tt_ctxt ist) of
461 [ty] -> ty -- must exist
463 isInductive (P _ nty _) (P _ nty' _) =
464 let co = case lookupCtxt nty (idris_datatypes ist) of
465 [TI _ x _] -> x
466 _ -> False in
467 nty == nty' && not co
468 isInductive _ _ = False
470-- getTypeFam t | (P _ n _, _) <- unApply t
472 dePat (Bind x (PVar ty) sc) = dePat (instantiate (P Bound x ty) sc)
473 dePat t = t
475 patvars (Bind x (PVar _) sc) = x : patvars sc
476 patvars _ = []
478{-
479buildSCG' :: IState -> SC -> [Name] -> [SCGEntry]
480buildSCG' ist sc args = -- trace ("Building SCG for " ++ show sc) $
481 nub $ scg sc (zip args args)
482 (zip args (zip args (repeat Same)))
483 where
484 scg :: SC -> [(Name, Name)] -> -- local var, originating top level var
485 [(Name, (Name, SizeChange))] -> -- orig to new, and relationship
486 [SCGEntry]
487 scg (Case x alts) vars szs
488 = let x' = findTL x vars in
489 concatMap (scgAlt x' vars szs) alts
490 where
491 findTL x vars
492 | Just x' <- lookup x vars
493 = if x' `elem` args then x'
494 else findTL x' vars
495 | otherwise = x
497 scg (STerm tm) vars szs = scgTerm tm vars szs
498 scg _ _ _ = []
500 -- how the arguments relate - either Smaller or Unknown
501 argRels :: Name -> [(Name, SizeChange)]
502 argRels n = let ctxt = tt_ctxt ist
503 [ty] = lookupTy n ctxt -- must exist!
504 P _ nty _ = fst (unApply (getRetTy ty))
505 co = case lookupCtxt nty (idris_datatypes ist) of
506 [TI _ x _] -> x
507 _ -> False
508 args = map snd (getArgTys ty) in
509 map (getRel co nty) (map (fst . unApply . getRetTy) args)
510 where
511 getRel True _ _ = (n, Unknown) -- coinductive
512 getRel _ ty (P _ n' _) | n' == ty = (n, Smaller)
513 getRel _ ty t = (n, Unknown)
515 scgAlt x vars szs (ConCase n _ args sc)
516 -- all args smaller than top variable of x in sc
517 -- (as long as they are in the same type family, and it's
518 -- not coinductive)
519 | Just tvar <- lookup x vars
520 = let arel = argRels n
521 szs' = zipWith (\arg (_,t) -> (arg, (x, t))) args arel
522 ++ szs
523 vars' = nub (zip args (repeat tvar) ++ vars) in
524 scg sc vars' szs'
525 | otherwise = scg sc vars szs
526 scgAlt x vars szs (ConstCase _ sc) = scg sc vars szs
527 scgAlt x vars szs (DefaultCase sc) = scg sc vars szs
529 scgTerm f@(App _ _) vars szs
530 | (P _ (UN "lazy") _, [_, arg]) <- unApply f
531 = scgTerm arg vars szs
532 | (P _ fn _, args) <- unApply f
533 = let rest = concatMap (\x -> scgTerm x vars szs) args in
534 case lookup fn vars of
535 Just _ -> rest
536 Nothing -> nub $ (fn, map (mkChange szs) args) : rest
537 scgTerm (App f a) vars szs
538 = scgTerm f vars szs ++ scgTerm a vars szs
539 scgTerm (Bind n (Let t v) e) vars szs
540 = scgTerm v vars szs ++ scgTerm e vars szs
541 scgTerm (Bind n _ e) vars szs
542 = scgTerm e (nub ((n, n) : vars)) szs
543 scgTerm (P _ fn _) vars szs
544 = case lookup fn vars of
545 Just _ -> []
546 Nothing -> [(fn, [])]
547 scgTerm _ _ _ = []
549 mkChange :: [(Name, (Name, SizeChange))] -> Term
550 -> Maybe (Int, SizeChange)
551 mkChange szs tm
552 | (P _ (UN "lazy") _, [_, arg]) <- unApply tm = mkChange szs arg
553 | (P _ n ty, _) <- unApply tm -- get higher order args too
554 = do sc <- lookup n szs
555 case sc of
556 (_, Unknown) -> Nothing
557 (o, sc) -> do i <- getArgPos 0 o args
558 return (i, sc)
559 mkChange _ _ = Nothing
561 getArgPos :: Int -> Name -> [Name] -> Maybe Int
562 getArgPos i n [] = Nothing
563 getArgPos i n (x : xs) | n == x = Just i
564 | otherwise = getArgPos (i + 1) n xs
565-}
567checkSizeChange :: Name -> Idris Totality
568checkSizeChange n = do
569 ist <- getIState
570 case lookupCtxt n (idris_callgraph ist) of
571 [cg] -> do let ms = mkMultiPaths ist [] (scg cg)
572 logLvl 5 ("Multipath for " ++ show n ++ ":\n" ++
573 "from " ++ show (scg cg) ++ "\n" ++
574 show (length ms) ++ "\n" ++
575 showSep "\n" (map show ms))
576 logLvl 6 (show cg)
577 -- every multipath must have an infinitely descending
578 -- thread, then the function terminates
579 -- also need to checks functions called are all total
580 -- (Unchecked is okay as we'll spot problems here)
581 let tot = map (checkMP ist (getArity ist n)) ms
582 logLvl 4 $ "Generated " ++ show (length tot) ++ " paths"
583 logLvl 6 $ "Paths for " ++ show n ++ " yield " ++ (show tot)
584 return (noPartial tot)
585 [] -> do logLvl 5 $ "No paths for " ++ show n
586 return Unchecked
587 where getArity ist n
588 = case lookupTy n (tt_ctxt ist) of
589 [ty] -> arity (normalise (tt_ctxt ist) [] ty)
590 _ -> error "Can't happen: checkSizeChange.getArity"
592type MultiPath = [SCGEntry]
594mkMultiPaths :: IState -> MultiPath -> [SCGEntry] -> [MultiPath]
595mkMultiPaths ist path [] = [reverse path]
596mkMultiPaths ist path cg
597 = concat (map extend cg)
598 where extend (nextf, args)
599 | (nextf, args) `elem` path = [ reverse ((nextf, args) : path) ]
600 | [Unchecked] <- lookupTotal nextf (tt_ctxt ist)
601 = case lookupCtxt nextf (idris_callgraph ist) of
602 [ncg] -> mkMultiPaths ist ((nextf, args) : path) (scg ncg)
603 _ -> [ reverse ((nextf, args) : path) ]
604 | otherwise = [ reverse ((nextf, args) : path) ]
606-- do (nextf, args) <- cg
607-- if ((nextf, args) `elem` path)
608-- then return (reverse ((nextf, args) : path))
609-- else case lookupCtxt nextf (idris_callgraph ist) of
610-- [ncg] -> mkMultiPaths ist ((nextf, args) : path) (scg ncg)
611-- _ -> return (reverse ((nextf, args) : path))
613-- If any route along the multipath leads to infinite descent, we're fine.
614-- Try a route beginning with every argument.
615-- If we reach a point we've been to before, but with a smaller value,
616-- that means there is an infinitely descending path from that argument.
618checkMP :: IState -> Int -> MultiPath -> Totality
619checkMP ist i mp = if i > 0
620 then let paths = (map (tryPath 0 [] mp) [0..i-1]) in
621-- trace ("Paths " ++ show paths) $
622 collapse paths
623 else tryPath 0 [] mp 0
624 where
625 tryPath' d path mp arg
626 = let res = tryPath d path mp arg in
627 trace (show mp ++ "\n" ++ show arg ++ " " ++ show res) res
629 tryPath :: Int -> [((SCGEntry, Int), Int)] -> MultiPath -> Int -> Totality
630 tryPath desc path [] _ = Total []
631-- tryPath desc path ((UN "believe_me", _) : _) arg
632-- = Partial BelieveMe
633 -- if we get to a constructor, it's fine as long as it's strictly positive
634 tryPath desc path ((f, _) : es) arg
635 | [TyDecl (DCon _ _) _] <- lookupDef f (tt_ctxt ist)
636 = case lookupTotal f (tt_ctxt ist) of
637 [Total _] -> Unchecked -- okay so far
638 [Partial _] -> Partial (Other [f])
639 x -> error (show x)
640 | [TyDecl (TCon _ _) _] <- lookupDef f (tt_ctxt ist)
641 = Total []
642 tryPath desc path (e@(f, args) : es) arg
643 | e `elem` es && allNothing args = Partial (Mutual [f])
644 tryPath desc path (e@(f, nextargs) : es) arg
645 | Just d <- lookup (e, arg) path
646 = if desc > 0
647 then -- trace ("Descent " ++ show (desc - d) ++ " "
648 -- ++ show (path, e)) $
649 Total []
650 else Partial (Mutual (map (fst . fst . fst) path ++ [f]))
651 | e `elem` map (fst . fst) path
652 && not (f `elem` map fst es)
653 = Partial (Mutual (map (fst . fst . fst) path ++ [f]))
654 | [Unchecked] <- lookupTotal f (tt_ctxt ist) =
655 let argspos = case collapseNothing (zip nextargs [0..]) of
656 [] -> [(Nothing, 0)]
657 x -> x
658-- trace (show (argspos, nextargs, path)) $
659 pathres =
660 do (a, pos) <- argspos
661 case a of
662 Nothing -> -- don't know, but if the
663 -- rest definitely terminates without
664 -- any cycles with route so far,
665 -- then we might yet be total
666 case collapse (map (tryPath 0 (((e, arg), 0):path) es)
667 [0..length nextargs - 1]) of
668 Total _ -> return Unchecked
669 x -> return x
670 Just (nextarg, sc) ->
671 if nextarg == arg then
672 case sc of
673 Same -> return $ tryPath desc (((e, arg), desc) : path)
674 es pos
675 Smaller -> return $ tryPath (desc+1)
676 (((e, arg), desc) : path)
677 es
678 pos
679 _ -> trace ("Shouldn't happen " ++ show e) $
680 return (Partial Itself)
681 else return Unchecked in
682-- trace (show (desc, argspos, path, es, pathres)) $
683 collapse' Unchecked pathres
685 | [Total a] <- lookupTotal f (tt_ctxt ist) = Total a
686 | [Partial _] <- lookupTotal f (tt_ctxt ist) = Partial (Other [f])
687 | otherwise = Unchecked
689allNothing xs = null (collapseNothing (zip xs [0..]))
691collapseNothing ((Nothing, _) : xs)
692 = filter (\ (x, _) -> case x of
693 Nothing -> False
694 _ -> True) xs
695collapseNothing (x : xs) = x : collapseNothing xs
696collapseNothing [] = []
698noPartial (Partial p : xs) = Partial p
699noPartial (_ : xs) = noPartial xs
700noPartial [] = Total []
702collapse xs = collapse' Unchecked xs
703collapse' def (Total r : xs) = Total r
704collapse' def (Unchecked : xs) = collapse' def xs
705collapse' def (d : xs) = collapse' d xs
706-- collapse' Unchecked [] = Total []
707collapse' def [] = def