on f8a6746 help sign in
Idris-dev/src/Idris/Coverage.hs
737 lines 31 kB history raw
1{-# LANGUAGE PatternGuards #-}
3module Idris.Coverage where
5import Idris.Core.TT
6import Idris.Core.Evaluate
7import Idris.Core.CaseTree
9import Idris.AbsSyntax
10import Idris.Delaborate
11import Idris.Error
12import Idris.Output (iWarn, iputStrLn)
14import Data.List
15import Data.Either
16import Data.Maybe
17import Debug.Trace
19import Control.Monad.State.Strict
21-- Generate a pattern from an 'impossible' LHS. (Need this to eliminate the
22-- pattern clauses which have been provided explicitly from new clause
23-- generation.)
25mkPatTm :: PTerm -> Idris Term
26mkPatTm t = do i <- getIState
27 let timp = addImpl' True [] [] i t
28 evalStateT (toTT (mapPT deNS timp)) 0
29 where
30 toTT (PRef _ n) = do i <- lift getIState
31 case lookupDef n (tt_ctxt i) of
32 [TyDecl nt _] -> return $ P nt n Erased
33 _ -> return $ P Ref n Erased
34 toTT (PApp _ t args) = do t' <- toTT t
35 args' <- mapM (toTT . getTm) args
36 return $ mkApp t' args'
37 -- For alternatives, pick the first and drop the namespaces. It doesn't
38 -- really matter which is taken since matching will ignore the namespace.
39 toTT (PAlternative _ (a : as)) = toTT a
40 toTT _ = do v <- get
41 put (v + 1)
42 return (P Bound (sMN v "imp") Erased)
44 deNS (PRef f (NS n _)) = PRef f n
45 deNS t = t
47-- Given a list of LHSs, generate a extra clauses which cover the remaining
48-- cases. The ones which haven't been provided are marked 'absurd' so that the
49-- checker will make sure they can't happen.
51-- This will only work after the given clauses have been typechecked and the
52-- names are fully explicit!
54genClauses :: FC -> Name -> [Term] -> [PTerm] -> Idris [PTerm]
55genClauses fc n xs given
56 = do i <- getIState
57 let lhs_tms = map (\x -> delab' i x True True) xs
58 -- if a placeholder was given, don't bother generating cases for it
59 let lhs_tms' = zipWith mergePlaceholders lhs_tms given
60 let lhss = map pUnApply lhs_tms'
62 let argss = transpose lhss
63 let all_args = map (genAll i) argss
64 logLvl 5 $ "COVERAGE of " ++ show n
65 logLvl 5 $ show lhss
66 logLvl 5 $ show (map length argss) ++ "\n" ++ show (map length all_args)
67 logLvl 10 $ show argss ++ "\n" ++ show all_args
68 logLvl 3 $ "Original: \n" ++
69 showSep "\n" (map (\t -> showTm i (delab' i t True True)) xs)
70 -- add an infinite supply of explicit arguments to update the possible
71 -- cases for (the return type may be variadic, or function type, so
72 -- there may be more case splitting that the idris_implicits record
73 -- suggests)
74 let parg = case lookupCtxt n (idris_implicits i) of
75 (p : _) ->
76 p ++ repeat (PExp 0 [] (sMN 0 "gcarg") Placeholder)
77 _ -> repeat (pexp Placeholder)
78 let tryclauses = mkClauses parg all_args
79 logLvl 3 $ show (length tryclauses) ++ " initially to check"
80 logLvl 2 $ showSep "\n" (map (showTm i) tryclauses)
81 let new = filter (noMatch i) (nub tryclauses)
82 logLvl 2 $ show (length new) ++ " clauses to check for impossibility"
83 logLvl 4 $ "New clauses: \n" ++ showSep "\n" (map (showTm i) new)
84-- ++ " from:\n" ++ showSep "\n" (map (showImp True) tryclauses)
85 return new
86-- return (map (\t -> PClause n t [] PImpossible []) new)
87 where getLHS i term
88 | (f, args) <- unApply term = map (\t -> delab' i t True True) args
89 | otherwise = []
91 pUnApply (PApp _ _ args) = map getTm args
92 pUnApply _ = []
94 -- Return whether the given clause matches none of the input clauses
95 -- (xs)
96 noMatch i tm = all (\x -> case matchClause i (delab' i x True True) tm of
97 Right ms -> False
98 Left miss -> True) xs
101 mergePlaceholders :: PTerm -> PTerm -> PTerm
102 mergePlaceholders x Placeholder = Placeholder
103 mergePlaceholders (PApp fc f args) (PApp fc' f' args')
104 = PApp fc' f' (zipWith mergePArg args args')
105 where mergePArg x y = let xtm = mergePlaceholders (getTm x) (getTm y) in
106 x { getTm = xtm}
107 mergePlaceholders x _ = x
109 mkClauses :: [PArg] -> [[PTerm]] -> [PTerm]
110 mkClauses parg args
111 | all (== [Placeholder]) args = []
112 mkClauses parg args
113 = do args' <- mkArg args
114 let tm = PApp fc (PRef fc n) (zipWith upd args' parg)
115 return tm
116 where
117 mkArg :: [[PTerm]] -> [[PTerm]]
118 mkArg [] = return []
119 mkArg (a : as) = do a' <- a
120 as' <- mkArg as
121 return (a':as')
123-- FIXME: Just look for which one is the deepest, then generate all
124-- possibilities up to that depth.
126genAll :: IState -> [PTerm] -> [PTerm]
127genAll i args
128 = case filter (/=Placeholder) $ fnub (concatMap otherPats (fnub args)) of
129 [] -> [Placeholder]
130 xs -> inventConsts xs
131 where
132 -- if they're constants, invent a new one to make sure that
133 -- constants which are not explicitly handled are covered
134 inventConsts cs@(PConstant c : _) = map PConstant (ic' (mapMaybe getConst cs))
135 where getConst (PConstant c) = Just c
136 getConst _ = Nothing
137 inventConsts xs = xs
139 -- try constants until they're not in the list.
140 -- FIXME: It is, of course, possible that someone has enumerated all
141 -- the constants and matched on them (maybe in generated code) and this
142 -- will be really slow. This is sufficiently unlikely that we won't
143 -- worry for now...
145 ic' xs@(I _ : _) = firstMissing xs (lotsOfNums I)
146 ic' xs@(BI _ : _) = firstMissing xs (lotsOfNums BI)
147 ic' xs@(Fl _ : _) = firstMissing xs (lotsOfNums Fl)
148 ic' xs@(B8 _ : _) = firstMissing xs (lotsOfNums B8)
149 ic' xs@(B16 _ : _) = firstMissing xs (lotsOfNums B16)
150 ic' xs@(B32 _ : _) = firstMissing xs (lotsOfNums B32)
151 ic' xs@(B64 _ : _) = firstMissing xs (lotsOfNums B64)
152 ic' xs@(Ch _ : _) = firstMissing xs lotsOfChars
153 ic' xs@(Str _ : _) = firstMissing xs lotsOfStrings
154 -- TODO: Bit vectors
155 -- The rest are types with only one case
156 ic' xs = xs
158 firstMissing cs (x : xs) | x `elem` cs = firstMissing cs xs
159 | otherwise = x : cs
161 lotsOfNums t = map t [0..]
162 lotsOfChars = map Ch ['a'..]
163 lotsOfStrings = map Str (map (("some string " ++).show) [1..])
165 conForm (PApp _ (PRef fc n) _) = isConName n (tt_ctxt i)
166 conForm (PRef fc n) = isConName n (tt_ctxt i)
167 conForm _ = False
169 nubMap f acc [] = acc
170 nubMap f acc (x : xs) = nubMap f (fnub' acc (f x)) xs
172 otherPats :: PTerm -> [PTerm]
173 otherPats o@(PRef fc n) = ops fc n [] o
174 otherPats o@(PApp _ (PRef fc n) xs) = ops fc n xs o
175 otherPats o@(PPair fc _ l r)
176 = ops fc pairCon
177 ([pimp (sUN "A") Placeholder True,
178 pimp (sUN "B") Placeholder True] ++
179 [pexp l, pexp r]) o
180 otherPats o@(PDPair fc p t _ v)
181 = ops fc (sUN "Ex_intro")
182 ([pimp (sUN "a") Placeholder True,
183 pimp (sUN "P") Placeholder True] ++
184 [pexp t,pexp v]) o
185 otherPats o@(PConstant c) = return o
186 otherPats arg = return Placeholder
188 ops fc n xs o
189 | (TyDecl c@(DCon _ arity _) ty : _) <- lookupDef n (tt_ctxt i)
190 = do xs' <- mapM otherPats (map getExpTm xs)
191 let p = resugar (PApp fc (PRef fc n) (zipWith upd xs' xs))
192 let tyn = getTy n (tt_ctxt i)
193 case lookupCtxt tyn (idris_datatypes i) of
194 (TI ns _ _ _ _ : _) -> p : map (mkPat fc) (ns \\ [n])
195 _ -> [p]
196 ops fc n arg o = return Placeholder
198 getExpTm (PImp _ True _ _ _) = Placeholder -- machine inferred, no point!
199 getExpTm t = getTm t
201 -- put it back to its original form
202 resugar (PApp _ (PRef fc (UN ei)) [_,_,t,v])
203 | ei == txt "Ex_intro"
204 = PDPair fc TypeOrTerm (getTm t) Placeholder (getTm v)
205 resugar (PApp _ (PRef fc n) [_,_,l,r])
206 | n == pairCon
207 = PPair fc IsTerm (getTm l) (getTm r)
208 resugar t = t
210 dropForce force (x : xs) i | i `elem` force
211 = upd Placeholder x : dropForce force xs (i + 1)
212 dropForce force (x : xs) i = x : dropForce force xs (i + 1)
213 dropForce _ [] _ = []
216 getTy n ctxt = case lookupTy n ctxt of
217 (t : _) -> case unApply (getRetTy t) of
218 (P _ tyn _, _) -> tyn
219 x -> error $ "Can't happen getTy 1 " ++ show (n, x)
220 _ -> error "Can't happen getTy 2"
222 mkPat fc x = case lookupCtxt x (idris_implicits i) of
223 (pargs : _)
224 -> PApp fc (PRef fc x) (map (upd Placeholder) pargs)
225 _ -> error "Can't happen - genAll"
227 fnub :: [PTerm] -> [PTerm]
228 fnub xs = fnub' [] xs
230 fnub' :: [PTerm] -> [PTerm] -> [PTerm]
231 fnub' acc (x : xs) | x `qelem` acc = fnub' acc (filter (not.(quickEq x)) xs)
232 | otherwise = fnub' (x : acc) xs
233 fnub' acc [] = acc
235 -- quick check for constructor equality
236 quickEq :: PTerm -> PTerm -> Bool
237 quickEq (PConstant n) (PConstant n') = n == n'
238 quickEq (PRef _ n) (PRef _ n') = n == n'
239 quickEq (PApp _ t as) (PApp _ t' as')
240 | length as == length as'
241 = quickEq t t' && and (zipWith quickEq (map getTm as) (map getTm as'))
242 quickEq Placeholder Placeholder = True
243 quickEq x y = False
245 qelem :: PTerm -> [PTerm] -> Bool
246 qelem x [] = False
247 qelem x (y : ys) | x `quickEq` y = True
248 | otherwise = qelem x ys
251upd :: t -> PArg' t -> PArg' t
252upd p' p = p { getTm = p' }
254-- Check whether function and all descendants cover all cases (partial is
255-- okay, as long as it's due to recursion)
257checkAllCovering :: FC -> [Name] -> Name -> Name -> Idris ()
258checkAllCovering fc done top n | not (n `elem` done)
259 = do i <- get
260 case lookupTotal n (tt_ctxt i) of
261 [tot@(Partial NotCovering)] ->
262 do let msg = show top ++ " is " ++ show tot ++ " due to " ++ show n
263 putIState i { idris_totcheckfail = (fc, msg) : idris_totcheckfail i }
264 addIBC (IBCTotCheckErr fc msg)
265 [Partial _] ->
266 case lookupCtxt n (idris_callgraph i) of
267 [cg] -> mapM_ (checkAllCovering fc (n : done) top)
268 (map fst (calls cg))
269 _ -> return ()
270 x -> return () -- stop if total
271checkAllCovering _ _ _ _ = return ()
273-- Check if, in a given group of type declarations mut_ns,
274-- the constructor cn : ty is strictly positive,
275-- and update the context accordingly
277checkPositive :: [Name] -> (Name, Type) -> Idris Totality
278checkPositive mut_ns (cn, ty')
279 = do let ty = delazy' True ty'
280 let p = cp ty
281 i <- getIState
282 let tot = if p then Total (args ty) else Partial NotPositive
283 let ctxt' = setTotal cn tot (tt_ctxt i)
284 putIState (i { tt_ctxt = ctxt' })
285 logLvl 5 $ "Constructor " ++ show cn ++ " is " ++ show tot ++ " with " ++ show mut_ns
286 addIBC (IBCTotal cn tot)
287 return tot
288 where
289 args t = [0..length (getArgTys t)-1]
291 cp (Bind n (Pi aty _) sc) = posArg aty && cp sc
292 cp t | (P _ n' _, args) <- unApply t,
293 n' `elem` mut_ns = all noRec args
294 cp _ = True
296 posArg (Bind _ (Pi nty _) sc)
297 | (P _ n' _, args) <- unApply nty
298 = n' `notElem` mut_ns && all noRec args && posArg sc
299 posArg t | (P _ n' _, args) <- unApply t,
300 n' `elem` mut_ns = all noRec args
301 posArg _ = True
303 noRec arg = all (\x -> x `notElem` mut_ns) (allTTNames arg)
306calcProd :: IState -> FC -> Name -> [([Name], Term, Term)] -> Idris Totality
307calcProd i fc topn pats
308 = cp topn pats []
309 where
310 -- every application of n must be in an argument of a coinductive
311 -- constructor, in every function reachable from here in the
312 -- call graph.
313 cp n pats done = do patsprod <- mapM (prodRec n done) pats
314 if (and patsprod)
315 then return Productive
316 else return (Partial NotProductive)
318 prodRec :: Name -> [Name] -> ([Name], Term, Term) -> Idris Bool
319 prodRec n done _ | n `elem` done = return True
320 prodRec n done (_, _, tm) = prod n done False (delazy' True tm)
322 prod :: Name -> [Name] -> Bool -> Term -> Idris Bool
323 prod n done ok ap@(App _ _)
324 | (P nt f _, args) <- unApply ap
325 = do recOK <- checkProdRec (n:done) f
326 let ctxt = tt_ctxt i
327 let [ty] = lookupTy f ctxt -- must exist!
328 let co = cotype nt f ty in
329 if (not recOK) then return False else
330 if f == topn
331 then do argsprod <- mapM (prod n done co) args
332 return (and (ok : argsprod) )
333 else do argsprod <- mapM (prod n done co) args
334 return (and argsprod)
335 prod n done ok (App f a) = liftM2 (&&) (prod n done False f)
336 (prod n done False a)
337 prod n done ok (Bind _ (Let t v) sc)
338 = liftM2 (&&) (prod n done False v) (prod n done False v)
339 prod n done ok (Bind _ b sc) = prod n done ok sc
340 prod n done ok t = return True
342 checkProdRec :: [Name] -> Name -> Idris Bool
343 checkProdRec done f
344 = case lookupCtxt f (idris_patdefs i) of
345 [(def, _)] -> do ok <- mapM (prodRec f done) def
346 return (and ok)
347 _ -> return True -- defined elsewhere, can't call topn
349 cotype (DCon _ _ _) n ty
350 | (P _ t _, _) <- unApply (getRetTy ty)
351 = case lookupCtxt t (idris_datatypes i) of
352 [TI _ True _ _ _] -> True
353 _ -> False
354 cotype nt n ty = False
356-- Calculate the totality of a function from its patterns.
357-- Either follow the size change graph (if inductive) or check for
358-- productivity (if coinductive)
360calcTotality :: FC -> Name -> [([Name], Term, Term)] -> Idris Totality
361calcTotality fc n pats
362 = do i <- getIState
363 let opts = case lookupCtxt n (idris_flags i) of
364 [fs] -> fs
365 _ -> []
366 case mapMaybe (checkLHS i) (map (\ (_, l, r) -> l) pats) of
367 (failure : _) -> return failure
368 _ -> checkSizeChange n
369 where
370 checkLHS i (P _ fn _)
371 = case lookupTotal fn (tt_ctxt i) of
372 [Partial _] -> return (Partial (Other [fn]))
373 _ -> Nothing
374 checkLHS i (App f a) = mplus (checkLHS i f) (checkLHS i a)
375 checkLHS _ _ = Nothing
377checkTotality :: [Name] -> FC -> Name -> Idris Totality
378checkTotality path fc n
379 | n `elem` path = return (Partial (Mutual (n : path)))
380 | otherwise = do
381 t <- getTotality n
382 i <- getIState
383 updateContext (simplifyCasedef n $ getErasureInfo i)
384 ctxt <- getContext
385 i <- getIState
386 let opts = case lookupCtxt n (idris_flags i) of
387 [fs] -> fs
388 _ -> []
389 t' <- case t of
390 Unchecked ->
391 case lookupDef n ctxt of
392 [CaseOp _ _ _ _ pats _] ->
393 do t' <- if AssertTotal `elem` opts
394 then return $ Total []
395 else calcTotality fc n pats
396 setTotality n t'
397 addIBC (IBCTotal n t')
398 return t'
399 [TyDecl (DCon _ _ _) ty] ->
400 case unApply (getRetTy ty) of
401 (P _ tyn _, _) -> do
402 let ms = case lookupCtxt tyn (idris_datatypes i) of
403 [TI _ _ _ _ xs@(_:_)] -> xs
404 ts -> [tyn]
405 checkPositive ms (n, ty)
406 _-> return $ Total []
407 _ -> return $ Total []
408 x -> return x
409 case t' of
410 Total _ -> return t'
411 Productive -> return t'
412 e -> do w <- cmdOptType WarnPartial
413 if TotalFn `elem` opts
414 then do totalityError t'; return t'
415 else do when (w && not (PartialFn `elem` opts)) $
416 warnPartial n t'
417 return t'
418 where
419 totalityError t = do i <- getIState
420 let msg = show n ++ " is " ++ show t
421 putIState i { idris_totcheckfail = (fc, msg) : idris_totcheckfail i}
422 addIBC (IBCTotCheckErr fc msg)
424 warnPartial n t
425 = do i <- getIState
426 case lookupDef n (tt_ctxt i) of
427 [x] -> do
428 iWarn fc . pprintErr i . Msg $ "Warning - " ++ show n ++ " is " ++ show t
429-- ++ "\n" ++ show x
430-- let cg = lookupCtxtName Nothing n (idris_callgraph i)
431-- iputStrLn (show cg)
434checkDeclTotality :: (FC, Name) -> Idris Totality
435checkDeclTotality (fc, n)
436 = do logLvl 2 $ "Checking " ++ show n ++ " for totality"
437-- buildSCG (fc, n)
438-- logLvl 2 $ "Built SCG"
439 i <- getIState
440 let opts = case lookupCtxt n (idris_flags i) of
441 [fs] -> fs
442 _ -> []
443 when (CoveringFn `elem` opts) $ checkAllCovering fc [] n n
444 t <- checkTotality [] fc n
445 case t of
446 -- if it's not total, it can't reduce, to keep
447 -- typechecking decidable
448 p@(Partial _) -> do setAccessibility n Frozen
449 addIBC (IBCAccess n Frozen)
450 logLvl 5 $ "HIDDEN: "
451 ++ show n ++ show p
452 _ -> return ()
453 return t
456-- Calculate the size change graph for this definition
458-- SCG for a function f consists of a list of:
459-- (g, [(a1, sizechange1), (a2, sizechange2), ..., (an, sizechangen)])
461-- where g is a function called
462-- a1 ... an are the arguments of f in positions 1..n of g
463-- sizechange1 ... sizechange2 is how their size has changed wrt the input
464-- to f
465-- Nothing, if the argument is unrelated to the input
467buildSCG :: (FC, Name) -> Idris ()
468buildSCG (_, n) = do
469 ist <- getIState
470 case lookupCtxt n (idris_callgraph ist) of
471 [cg] -> case lookupDefExact n (tt_ctxt ist) of
472 Just (CaseOp _ _ _ pats _ cd) ->
473 let (args, sc) = cases_totcheck cd in
474 do logLvl 2 $ "Building SCG for " ++ show n ++ " from\n"
475 ++ show pats ++ "\n" ++ show sc
476 let newscg = buildSCG' ist (rights pats) args
477 logLvl 5 $ "SCG is: " ++ show newscg
478 addToCG n ( cg { scg = newscg } )
479 [] -> logLvl 5 $ "Could not build SCG for " ++ show n ++ "\n"
480 x -> error $ "buildSCG: " ++ show (n, x)
482delazy = delazy' False -- not lazy codata
483delazy' all t@(App f a)
484 | (P _ (UN l) _, [_, _, arg]) <- unApply t,
485 l == txt "Force" = delazy' all arg
486 | (P _ (UN l) _, [P _ (UN lty) _, _, arg]) <- unApply t,
487 l == txt "Delay" && (all || lty == txt "LazyEval") = delazy arg
488 | (P _ (UN l) _, [P _ (UN lty) _, arg]) <- unApply t,
489 l == txt "Lazy'" && (all || lty == txt "LazyEval") = delazy' all arg
490delazy' all (App f a) = App (delazy' all f) (delazy' all a)
491delazy' all (Bind n b sc) = Bind n (fmap (delazy' all) b) (delazy' all sc)
492delazy' all t = t
494data Guardedness = Toplevel | Unguarded | Guarded
495 deriving Show
497buildSCG' :: IState -> [(Term, Term)] -> [Name] -> [SCGEntry]
498buildSCG' ist pats args = nub $ concatMap scgPat pats where
499 scgPat (lhs, rhs) = let lhs' = delazy lhs
500 rhs' = delazy rhs
501 (f, pargs) = unApply (dePat lhs') in
502 findCalls Toplevel (dePat rhs') (patvars lhs') pargs
504 findCalls guarded ap@(App f a) pvs pargs
505 -- under a call to "assert_total", don't do any checking, just believe
506 -- that it is total.
507 | (P _ (UN at) _, [_, _]) <- unApply ap,
508 at == txt "assert_total" = []
509 -- under a call to "Delay LazyCodata", don't do any checking of the
510 -- immediate call, as long as the call is guarded.
511 -- Then check its arguments
512 | (P _ (UN del) _, [_,_,arg]) <- unApply ap,
513 Guarded <- guarded,
514 del == txt "Delay"
515 = let (capp, args) = unApply arg in
516 concatMap (\x -> findCalls guarded x pvs pargs) args
517 | (P _ n _, args) <- unApply ap
518 = let nguarded = case guarded of
519 Unguarded -> Unguarded
520 _ -> if isConName n (tt_ctxt ist)
521 then Guarded
522 else Unguarded in
523 mkChange n args pargs ++
524 concatMap (\x -> findCalls nguarded x pvs pargs) args
525 findCalls guarded (App f a) pvs pargs
526 = findCalls Unguarded f pvs pargs ++ findCalls Unguarded a pvs pargs
527 findCalls guarded (Bind n (Let t v) e) pvs pargs
528 = findCalls Unguarded v pvs pargs ++ findCalls guarded e (n : pvs) pargs
529 findCalls guarded (Bind n _ e) pvs pargs
530 = findCalls guarded e (n : pvs) pargs
531 findCalls guarded (P _ f _ ) pvs pargs
532 | not (f `elem` pvs) = [(f, [])]
533 findCalls _ _ _ _ = []
535 expandToArity n args
536 = case lookupTy n (tt_ctxt ist) of
537 [ty] -> expand 0 (normalise (tt_ctxt ist) [] ty) args
538 _ -> args
539 where expand i (Bind n (Pi _ _) sc) (x : xs) = x : expand (i + 1) sc xs
540 expand i (Bind n (Pi _ _) sc) [] = Just (i, Same) : expand (i + 1) sc []
541 expand i _ xs = xs
543 mkChange n args pargs = [(n, expandToArity n (sizes args))]
544 where
545 sizes [] = []
546 sizes (a : as) = checkSize a pargs 0 : sizes as
548 -- find which argument in pargs <a> is smaller than, if any
549 checkSize a (p : ps) i
550 | a == p = Just (i, Same)
551 | (P _ (UN as) _, [_,_,arg,_]) <- unApply a,
552 as == txt "assert_smaller" && arg == p
553 = Just (i, Smaller)
554 | smaller Nothing a (p, Nothing) = Just (i, Smaller)
555 | otherwise = checkSize a ps (i + 1)
556 checkSize a [] i = Nothing
558 -- the smaller thing we find must be the same type as <a>, and
559 -- not be coinductive - so carry the type of the constructor we've
560 -- gone under.
562 smaller (Just tyn) a (t, Just tyt)
563 | a == t = isInductive (fst (unApply (getRetTy tyn)))
564 (fst (unApply (getRetTy tyt)))
565 smaller ty a (ap@(App f s), _)
566 | (P (DCon _ _ _) n _, args) <- unApply ap
567 = let tyn = getType n in
568 any (smaller (ty `mplus` Just tyn) a)
569 (zip args (map toJust (getArgTys tyn)))
570 -- check higher order recursive arguments
571 smaller ty (App f s) a = smaller ty f a
572 smaller _ _ _ = False
574 toJust (n, t) = Just t
576 getType n = case lookupTy n (tt_ctxt ist) of
577 [ty] -> delazy ty -- must exist
579 isInductive (P _ nty _) (P _ nty' _) =
580 let co = case lookupCtxt nty (idris_datatypes ist) of
581 [TI _ x _ _ _] -> x
582 _ -> False in
583 nty == nty' && not co
584 isInductive _ _ = False
586 dePat (Bind x (PVar ty) sc) = dePat (instantiate (P Bound x ty) sc)
587 dePat t = t
589 patvars (Bind x (PVar _) sc) = x : patvars sc
590 patvars _ = []
592checkSizeChange :: Name -> Idris Totality
593checkSizeChange n = do
594 ist <- getIState
595 case lookupCtxt n (idris_callgraph ist) of
596 [cg] -> do let ms = mkMultiPaths ist [] (scg cg)
597 logLvl 5 ("Multipath for " ++ show n ++ ":\n" ++
598 "from " ++ show (scg cg) ++ "\n" ++
599 show (length ms) ++ "\n" ++
600 showSep "\n" (map show ms))
601 logLvl 6 (show cg)
602 -- every multipath must have an infinitely descending
603 -- thread, then the function terminates
604 -- also need to checks functions called are all total
605 -- (Unchecked is okay as we'll spot problems here)
606 let tot = map (checkMP ist (getArity ist n)) ms
607 logLvl 4 $ "Generated " ++ show (length tot) ++ " paths"
608 logLvl 6 $ "Paths for " ++ show n ++ " yield " ++ (show tot)
609 return (noPartial tot)
610 [] -> do logLvl 5 $ "No paths for " ++ show n
611 return Unchecked
612 where getArity ist n
613 = case lookupTy n (tt_ctxt ist) of
614 [ty] -> arity (normalise (tt_ctxt ist) [] ty)
615 _ -> error "Can't happen: checkSizeChange.getArity"
617type MultiPath = [SCGEntry]
619mkMultiPaths :: IState -> MultiPath -> [SCGEntry] -> [MultiPath]
620mkMultiPaths ist path [] = [reverse path]
621mkMultiPaths ist path cg
622 = concat (map extend cg)
623 where extend (nextf, args)
624 | (nextf, args) `elem` path = [ reverse ((nextf, args) : path) ]
625 | [Unchecked] <- lookupTotal nextf (tt_ctxt ist)
626 = case lookupCtxt nextf (idris_callgraph ist) of
627 [ncg] -> mkMultiPaths ist ((nextf, args) : path) (scg ncg)
628 _ -> [ reverse ((nextf, args) : path) ]
629 | otherwise = [ reverse ((nextf, args) : path) ]
631-- do (nextf, args) <- cg
632-- if ((nextf, args) `elem` path)
633-- then return (reverse ((nextf, args) : path))
634-- else case lookupCtxt nextf (idris_callgraph ist) of
635-- [ncg] -> mkMultiPaths ist ((nextf, args) : path) (scg ncg)
636-- _ -> return (reverse ((nextf, args) : path))
638-- If any route along the multipath leads to infinite descent, we're fine.
639-- Try a route beginning with every argument.
640-- If we reach a point we've been to before, but with a smaller value,
641-- that means there is an infinitely descending path from that argument.
643checkMP :: IState -> Int -> MultiPath -> Totality
644checkMP ist i mp = if i > 0
645 then let paths = (map (tryPath 0 [] mp) [0..i-1]) in
646-- trace ("Paths " ++ show paths) $
647 collapse paths
648 else tryPath 0 [] mp 0
649 where
650 tryPath' d path mp arg
651 = let res = tryPath d path mp arg in
652 trace (show mp ++ "\n" ++ show arg ++ " " ++ show res) res
654 tryPath :: Int -> [((SCGEntry, Int), Int)] -> MultiPath -> Int -> Totality
655 tryPath desc path [] _ = Total []
656-- tryPath desc path ((UN "believe_me", _) : _) arg
657-- = Partial BelieveMe
658 -- if we get to a constructor, it's fine as long as it's strictly positive
659 tryPath desc path ((f, _) : es) arg
660 | [TyDecl (DCon _ _ _) _] <- lookupDef f (tt_ctxt ist)
661 = case lookupTotal f (tt_ctxt ist) of
662 [Total _] -> Unchecked -- okay so far
663 [Partial _] -> Partial (Other [f])
664 x -> error $ "CAN'T HAPPEN: " ++ (show x)
665 | [TyDecl (TCon _ _) _] <- lookupDef f (tt_ctxt ist)
666 = Total []
667 tryPath desc path (e@(f, args) : es) arg
668 | e `elem` es && allNothing args = Partial (Mutual [f])
669 tryPath desc path (e@(f, nextargs) : es) arg
670 | Just d <- lookup (e, arg) path
671 = if desc > 0
672 then -- trace ("Descent " ++ show (desc - d) ++ " "
673 -- ++ show (path, e)) $
674 Total []
675 else Partial (Mutual (map (fst . fst . fst) path ++ [f]))
676 | e `elem` map (fst . fst) path
677 && not (f `elem` map fst es)
678 = Partial (Mutual (map (fst . fst . fst) path ++ [f]))
679 | [Unchecked] <- lookupTotal f (tt_ctxt ist) =
680 let argspos = case collapseNothing (zip nextargs [0..]) of
681 [] -> [(Nothing, 0)]
682 x -> x
683-- trace (show (argspos, nextargs, path)) $
684 pathres =
685 do (a, pos) <- argspos
686 case a of
687 Nothing -> -- don't know, but if the
688 -- rest definitely terminates without
689 -- any cycles with route so far,
690 -- then we might yet be total
691 case collapse (map (tryPath 0 (((e, arg), 0):path) es)
692 [0..length nextargs - 1]) of
693 Total _ -> return Unchecked
694 x -> return x
695 Just (nextarg, sc) ->
696 if nextarg == arg then
697 case sc of
698 Same -> return $ tryPath desc (((e, arg), desc) : path)
699 es pos
700 Smaller -> return $ tryPath (desc+1)
701 (((e, arg), desc) : path)
702 es
703 pos
704 _ -> trace ("Shouldn't happen " ++ show e) $
705 return (Partial Itself)
706 else return Unchecked in
707-- trace (show (desc, argspos, path, es, pathres)) $
708 collapse' Unchecked pathres
710 | [Total a] <- lookupTotal f (tt_ctxt ist) = Total a
711 | [Partial _] <- lookupTotal f (tt_ctxt ist) = Partial (Other [f])
712 | otherwise = Unchecked
714allNothing :: [Maybe a] -> Bool
715allNothing xs = null (collapseNothing (zip xs [0..]))
717collapseNothing :: [(Maybe a, b)] -> [(Maybe a, b)]
718collapseNothing ((Nothing, _) : xs)
719 = filter (\ (x, _) -> case x of
720 Nothing -> False
721 _ -> True) xs
722collapseNothing (x : xs) = x : collapseNothing xs
723collapseNothing [] = []
725noPartial :: [Totality] -> Totality
726noPartial (Partial p : xs) = Partial p
727noPartial (_ : xs) = noPartial xs
728noPartial [] = Total []
730collapse :: [Totality] -> Totality
731collapse xs = collapse' Unchecked xs
732collapse' def (Total r : xs) = Total r
733collapse' def (Unchecked : xs) = collapse' def xs
734collapse' def (d : xs) = collapse' d xs
735-- collapse' Unchecked [] = Total []
736collapse' def [] = def