on cd8a233 help sign in
Idris-dev/src/Idris/Coverage.hs
706 lines 30 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)
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 1 $ "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 2 $ show (length tryclauses) ++ " initially to check"
80 logLvl 1 $ showSep "\n" (map (showTm i) tryclauses)
81 let new = filter (noMatch i) (nub tryclauses)
82 logLvl 1 $ show (length new) ++ " clauses to check for impossibility"
83 logLvl 3 $ "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')
123fnub xs = fnub' [] xs
125fnub' acc (x : xs) | x `qelem` acc = fnub' acc (filter (not.(quickEq x)) xs)
126 | otherwise = fnub' (x : acc) xs
127fnub' acc [] = acc
129-- quick check for constructor equality
130quickEq :: PTerm -> PTerm -> Bool
131quickEq (PConstant n) (PConstant n') = n == n'
132quickEq (PRef _ n) (PRef _ n') = n == n'
133quickEq (PApp _ t as) (PApp _ t' as')
134 | length as == length as'
135 = quickEq t t' && and (zipWith quickEq (map getTm as) (map getTm as'))
136quickEq Placeholder Placeholder = True
137quickEq x y = False
139qelem x [] = False
140qelem x (y : ys) | x `quickEq` y = True
141 | otherwise = qelem x ys
143-- FIXME: Just look for which one is the deepest, then generate all
144-- possibilities up to that depth.
146genAll :: IState -> [PTerm] -> [PTerm]
147genAll i args
148 = case filter (/=Placeholder) $ fnub (concatMap otherPats (fnub args)) of
149 [] -> [Placeholder]
150 xs -> inventConsts xs
151 where
152 -- if they're constants, invent a new one to make sure that
153 -- constants which are not explicitly handled are covered
154 inventConsts cs@(PConstant c : _) = map PConstant (ic' (mapMaybe getConst cs))
155 where getConst (PConstant c) = Just c
156 getConst _ = Nothing
157 inventConsts xs = xs
159 -- try constants until they're not in the list.
160 -- FIXME: It is, of course, possible that someone has enumerated all
161 -- the constants and matched on them (maybe in generated code) and this
162 -- will be really slow. This is sufficiently unlikely that we won't
163 -- worry for now...
165 ic' xs@(I _ : _) = firstMissing xs (lotsOfNums I)
166 ic' xs@(BI _ : _) = firstMissing xs (lotsOfNums BI)
167 ic' xs@(Fl _ : _) = firstMissing xs (lotsOfNums Fl)
168 ic' xs@(B8 _ : _) = firstMissing xs (lotsOfNums B8)
169 ic' xs@(B16 _ : _) = firstMissing xs (lotsOfNums B16)
170 ic' xs@(B32 _ : _) = firstMissing xs (lotsOfNums B32)
171 ic' xs@(B64 _ : _) = firstMissing xs (lotsOfNums B64)
172 ic' xs@(Ch _ : _) = firstMissing xs lotsOfChars
173 ic' xs@(Str _ : _) = firstMissing xs lotsOfStrings
174 -- TODO: Bit vectors
175 -- The rest are types with only one case
176 ic' xs = xs
178 firstMissing cs (x : xs) | x `elem` cs = firstMissing cs xs
179 | otherwise = x : cs
181 lotsOfNums t = map t [0..]
182 lotsOfChars = map Ch ['a'..]
183 lotsOfStrings = map Str (map (("some string " ++).show) [1..])
185 conForm (PApp _ (PRef fc n) _) = isConName n (tt_ctxt i)
186 conForm (PRef fc n) = isConName n (tt_ctxt i)
187 conForm _ = False
189 nubMap f acc [] = acc
190 nubMap f acc (x : xs) = nubMap f (fnub' acc (f x)) xs
192 otherPats :: PTerm -> [PTerm]
193 otherPats o@(PRef fc n) = ops fc n [] o
194 otherPats o@(PApp _ (PRef fc n) xs) = ops fc n xs o
195 otherPats o@(PPair fc _ l r)
196 = ops fc pairCon
197 ([pimp (sUN "A") Placeholder True,
198 pimp (sUN "B") Placeholder True] ++
199 [pexp l, pexp r]) o
200 otherPats o@(PDPair fc p t _ v)
201 = ops fc (sUN "Ex_intro")
202 ([pimp (sUN "a") Placeholder True,
203 pimp (sUN "P") Placeholder True] ++
204 [pexp t,pexp v]) o
205 otherPats o@(PConstant c) = return o
206 otherPats arg = return Placeholder
208 ops fc n xs o
209 | (TyDecl c@(DCon _ arity) ty : _) <- lookupDef n (tt_ctxt i)
210 = do xs' <- mapM otherPats (map getExpTm xs)
211 let p = resugar (PApp fc (PRef fc n) (zipWith upd xs' xs))
212 let tyn = getTy n (tt_ctxt i)
213 case lookupCtxt tyn (idris_datatypes i) of
214 (TI ns _ _ _ : _) -> p : map (mkPat fc) (ns \\ [n])
215 _ -> [p]
216 ops fc n arg o = return Placeholder
218 getExpTm (PImp _ True _ _ _) = Placeholder -- machine inferred, no point!
219 getExpTm t = getTm t
221 -- put it back to its original form
222 resugar (PApp _ (PRef fc (UN ei)) [_,_,t,v])
223 | ei == txt "Ex_intro"
224 = PDPair fc TypeOrTerm (getTm t) Placeholder (getTm v)
225 resugar (PApp _ (PRef fc n) [_,_,l,r])
226 | n == pairCon
227 = PPair fc IsTerm (getTm l) (getTm r)
228 resugar t = t
230 dropForce force (x : xs) i | i `elem` force
231 = upd Placeholder x : dropForce force xs (i + 1)
232 dropForce force (x : xs) i = x : dropForce force xs (i + 1)
233 dropForce _ [] _ = []
236 getTy n ctxt = case lookupTy n ctxt of
237 (t : _) -> case unApply (getRetTy t) of
238 (P _ tyn _, _) -> tyn
239 x -> error $ "Can't happen getTy 1 " ++ show (n, x)
240 _ -> error "Can't happen getTy 2"
242 mkPat fc x = case lookupCtxt x (idris_implicits i) of
243 (pargs : _)
244 -> PApp fc (PRef fc x) (map (upd Placeholder) pargs)
245 _ -> error "Can't happen - genAll"
247upd p' p = p { getTm = p' }
249-- Check whether function and all descendants cover all cases (partial is
250-- okay, as long as it's due to recursion)
252checkAllCovering :: FC -> [Name] -> Name -> Name -> Idris ()
253checkAllCovering fc done top n | not (n `elem` done)
254 = do i <- get
255 case lookupTotal n (tt_ctxt i) of
256 [tot@(Partial NotCovering)] ->
257 do let msg = show top ++ " is " ++ show tot ++ " due to " ++ show n
258 addIBC (IBCTotCheckErr fc msg)
259 putIState i { idris_totcheckfail = (fc, msg) : idris_totcheckfail i }
260 _ -> return ()
261 case lookupCtxt n (idris_callgraph i) of
262 [cg] -> mapM_ (checkAllCovering fc (n : done) top)
263 (map fst (calls cg))
264 _ -> return ()
265checkAllCovering _ _ _ _ = return ()
267-- Check if, in a given type n, the constructor cn : ty is strictly positive,
268-- and update the context accordingly
270checkPositive :: Name -> (Name, Type) -> Idris ()
271checkPositive n (cn, ty')
272 = do let ty = delazy ty'
273 let p = cp ty
274 i <- getIState
275 let tot = if p then Total (args ty) else Partial NotPositive
276 let ctxt' = setTotal cn tot (tt_ctxt i)
277 putIState (i { tt_ctxt = ctxt' })
278 logLvl 5 $ "Constructor " ++ show cn ++ " is " ++ show tot
279 addIBC (IBCTotal cn tot)
280 where
281 args t = [0..length (getArgTys t)-1]
283 cp (Bind n (Pi aty) sc) = posArg aty && cp sc
284 cp t = True
286 posArg (Bind _ (Pi nty) sc)
287 | (P _ n' _, args) <- unApply nty
288 = n /= n' && posArg sc
289 posArg t = True
291calcProd :: IState -> FC -> Name -> [([Name], Term, Term)] -> Idris Totality
292calcProd i fc topn pats
293 = cp topn pats []
294 where
295 -- every application of n must be in an argument of a coinductive
296 -- constructor, in every function reachable from here in the
297 -- call graph.
298 cp n pats done = do patsprod <- mapM (prodRec n done) pats
299 if (and patsprod)
300 then return Productive
301 else return (Partial NotProductive)
303 prodRec :: Name -> [Name] -> ([Name], Term, Term) -> Idris Bool
304 prodRec n done _ | n `elem` done = return True
305 prodRec n done (_, _, tm) = prod n done False (delazy' True tm)
307 prod :: Name -> [Name] -> Bool -> Term -> Idris Bool
308 prod n done ok ap@(App _ _)
309 | (P nt f _, args) <- unApply ap
310 = do recOK <- checkProdRec (n:done) f
311 let ctxt = tt_ctxt i
312 let [ty] = lookupTy f ctxt -- must exist!
313 let co = cotype nt f ty in
314 if (not recOK) then return False else
315 if f == topn
316 then do argsprod <- mapM (prod n done co) args
317 return (and (ok : argsprod) )
318 else do argsprod <- mapM (prod n done co) args
319 return (and argsprod)
320 prod n done ok (App f a) = liftM2 (&&) (prod n done False f)
321 (prod n done False a)
322 prod n done ok (Bind _ (Let t v) sc)
323 = liftM2 (&&) (prod n done False v) (prod n done False v)
324 prod n done ok (Bind _ b sc) = prod n done ok sc
325 prod n done ok t = return True
327 checkProdRec :: [Name] -> Name -> Idris Bool
328 checkProdRec done f
329 = case lookupCtxt f (idris_patdefs i) of
330 [(def, _)] -> do ok <- mapM (prodRec f done) def
331 return (and ok)
332 _ -> return True -- defined elsewhere, can't call topn
334 cotype (DCon _ _) n ty
335 | (P _ t _, _) <- unApply (getRetTy ty)
336 = case lookupCtxt t (idris_datatypes i) of
337 [TI _ True _ _] -> True
338 _ -> False
339 cotype nt n ty = False
341-- Calculate the totality of a function from its patterns.
342-- Either follow the size change graph (if inductive) or check for
343-- productivity (if coinductive)
345calcTotality :: FC -> Name -> [([Name], Term, Term)] -> Idris Totality
346calcTotality fc n pats
347 = do i <- getIState
348 let opts = case lookupCtxt n (idris_flags i) of
349 [fs] -> fs
350 _ -> []
351 case mapMaybe (checkLHS i) (map (\ (_, l, r) -> l) pats) of
352 (failure : _) -> return failure
353 _ -> if (Coinductive `elem` opts)
354 then calcProd i fc n pats
355 else checkSizeChange n
356 where
357 checkLHS i (P _ fn _)
358 = case lookupTotal fn (tt_ctxt i) of
359 [Partial _] -> return (Partial (Other [fn]))
360 _ -> Nothing
361 checkLHS i (App f a) = mplus (checkLHS i f) (checkLHS i a)
362 checkLHS _ _ = Nothing
364checkTotality :: [Name] -> FC -> Name -> Idris Totality
365checkTotality path fc n
366 | n `elem` path = return (Partial (Mutual (n : path)))
367 | otherwise = do
368 t <- getTotality n
369 updateContext (simplifyCasedef n)
370 ctxt <- getContext
371 i <- getIState
372 let opts = case lookupCtxt n (idris_flags i) of
373 [fs] -> fs
374 _ -> []
375 t' <- case t of
376 Unchecked ->
377 case lookupDef n ctxt of
378 [CaseOp _ _ _ _ pats _] ->
379 do t' <- if AssertTotal `elem` opts
380 then return $ Total []
381 else calcTotality fc n pats
382 setTotality n t'
383 addIBC (IBCTotal n t')
384 return t'
385 _ -> return $ Total []
386 x -> return x
387 case t' of
388 Total _ -> return t'
389 Productive -> return t'
390 e -> do w <- cmdOptType WarnPartial
391 if TotalFn `elem` opts
392 then do totalityError t'; return t'
393 else do when (w && not (PartialFn `elem` opts)) $
394 warnPartial n t'
395 return t'
396 where
397 totalityError t = do i <- getIState
398 let msg = show n ++ " is " ++ show t
399 putIState i { idris_totcheckfail = (fc, msg) : idris_totcheckfail i}
400 addIBC (IBCTotCheckErr fc msg)
402 warnPartial n t
403 = do i <- getIState
404 case lookupDef n (tt_ctxt i) of
405 [x] -> do
406 iWarn fc . pprintErr i . Msg $ "Warning - " ++ show n ++ " is " ++ show t
407-- ++ "\n" ++ show x
408-- let cg = lookupCtxtName Nothing n (idris_callgraph i)
409-- iputStrLn (show cg)
412checkDeclTotality :: (FC, Name) -> Idris Totality
413checkDeclTotality (fc, n)
414 = do logLvl 2 $ "Checking " ++ show n ++ " for totality"
415-- buildSCG (fc, n)
416-- logLvl 2 $ "Built SCG"
417 i <- getIState
418 t <- checkTotality [] fc n
419 case t of
420 -- if it's not total, it can't reduce, to keep
421 -- typechecking decidable
422 p@(Partial _) -> do setAccessibility n Frozen
423 addIBC (IBCAccess n Frozen)
424 logLvl 5 $ "HIDDEN: "
425 ++ show n ++ show p
426 _ -> return ()
427 return t
430-- Calculate the size change graph for this definition
432-- SCG for a function f consists of a list of:
433-- (g, [(a1, sizechange1), (a2, sizechange2), ..., (an, sizechangen)])
435-- where g is a function called
436-- a1 ... an are the arguments of f in positions 1..n of g
437-- sizechange1 ... sizechange2 is how their size has changed wrt the input
438-- to f
439-- Nothing, if the argument is unrelated to the input
441buildSCG :: (FC, Name) -> Idris ()
442buildSCG (_, n) = do
443 ist <- getIState
444 case lookupCtxt n (idris_callgraph ist) of
445 [cg] -> case lookupDef n (tt_ctxt ist) of
446 [CaseOp _ _ _ pats _ cd] ->
447 let (args, sc) = cases_totcheck cd in
448 do logLvl 2 $ "Building SCG for " ++ show n ++ " from\n"
449 ++ show pats ++ "\n" ++ show sc
450 let newscg = buildSCG' ist (rights pats) args
451 logLvl 5 $ show newscg
452 addToCG n ( cg { scg = newscg } )
453 [] -> logLvl 5 $ "Could not build SCG for " ++ show n ++ "\n"
454 x -> error $ "buildSCG: " ++ show (n, x)
456delazy = delazy' False -- not lazy codata
457delazy' all t@(App f a)
458 | (P _ (UN l) _, [_, _, arg]) <- unApply t,
459 l == txt "Force" = delazy' all arg
460 | (P _ (UN l) _, [P _ (UN lty) _, _, arg]) <- unApply t,
461 l == txt "Delay" && (all || lty == txt "LazyEval") = delazy arg
462 | (P _ (UN l) _, [P _ (UN lty) _, arg]) <- unApply t,
463 l == txt "Lazy'" && (all || lty == txt "LazyEval") = delazy' all arg
464delazy' all (App f a) = App (delazy' all f) (delazy' all a)
465delazy' all (Bind n b sc) = Bind n (fmap (delazy' all) b) (delazy' all sc)
466delazy' all t = t
468data Guardedness = Toplevel | Unguarded | Guarded
470buildSCG' :: IState -> [(Term, Term)] -> [Name] -> [SCGEntry]
471buildSCG' ist pats args = nub $ concatMap scgPat pats where
472 scgPat (lhs, rhs) = let lhs' = delazy lhs
473 rhs' = delazy rhs
474 (f, pargs) = unApply (dePat lhs') in
475 findCalls Toplevel (dePat rhs') (patvars lhs') pargs
477 findCalls guarded ap@(App f a) pvs pargs
478 -- under a call to "assert_total", don't do any checking, just believe
479 -- that it is total.
480 | (P _ (UN at) _, [_, _]) <- unApply ap,
481 at == txt "assert_total" = []
482 -- under a call to "Delay LazyCodata", don't do any checking of the
483 -- immediate call, as long as the call is guarded.
484 -- Then check its arguments
485 | (P _ (UN del) _, [_,_,arg]) <- unApply ap,
486 guarded <- Guarded,
487 del == txt "Delay"
488 = let (capp, args) = unApply arg in
489 concatMap (\x -> findCalls Toplevel x pvs pargs) args
490 | (P _ n _, args) <- unApply ap
491 = let nguarded = case guarded of
492 Unguarded -> Unguarded
493 _ -> if isConName n (tt_ctxt ist)
494 then Guarded
495 else Unguarded in
496 mkChange n args pargs ++
497 concatMap (\x -> findCalls nguarded x pvs pargs) args
498 findCalls guarded (App f a) pvs pargs
499 = findCalls Unguarded f pvs pargs ++ findCalls Unguarded a pvs pargs
500 findCalls guarded (Bind n (Let t v) e) pvs pargs
501 = findCalls Unguarded v pvs pargs ++ findCalls guarded e (n : pvs) pargs
502 findCalls guarded (Bind n _ e) pvs pargs
503 = findCalls guarded e (n : pvs) pargs
504 findCalls guarded (P _ f _ ) pvs pargs
505 | not (f `elem` pvs) = [(f, [])]
506 findCalls _ _ _ _ = []
508 expandToArity n args
509 = case lookupTy n (tt_ctxt ist) of
510 [ty] -> expand 0 (normalise (tt_ctxt ist) [] ty) args
511 _ -> args
512 where expand i (Bind n (Pi _) sc) (x : xs) = x : expand (i + 1) sc xs
513 expand i (Bind n (Pi _) sc) [] = Just (i, Same) : expand (i + 1) sc []
514 expand i _ xs = xs
516 mkChange n args pargs = [(n, expandToArity n (sizes args))]
517 where
518 sizes [] = []
519 sizes (a : as) = checkSize a pargs 0 : sizes as
521 -- find which argument in pargs <a> is smaller than, if any
522 checkSize a (p : ps) i
523 | a == p = Just (i, Same)
524 | (P _ (UN as) _, [_,_,arg,_]) <- unApply a,
525 as == txt "assert_smaller" && arg == p
526 = Just (i, Smaller)
527 | smaller Nothing a (p, Nothing) = Just (i, Smaller)
528 | otherwise = checkSize a ps (i + 1)
529 checkSize a [] i = Nothing
531 -- the smaller thing we find must be the same type as <a>, and
532 -- not be coinductive - so carry the type of the constructor we've
533 -- gone under.
535 smaller (Just tyn) a (t, Just tyt)
536 | a == t = isInductive (fst (unApply (getRetTy tyn)))
537 (fst (unApply (getRetTy tyt)))
538 smaller ty a (ap@(App f s), _)
539 | (P (DCon _ _) n _, args) <- unApply ap
540 = let tyn = getType n in
541 any (smaller (ty `mplus` Just tyn) a)
542 (zip args (map toJust (getArgTys tyn)))
543 -- check higher order recursive arguments
544 smaller ty (App f s) a = smaller ty f a
545 smaller _ _ _ = False
547 toJust (n, t) = Just t
549 getType n = case lookupTy n (tt_ctxt ist) of
550 [ty] -> delazy ty -- must exist
552 isInductive (P _ nty _) (P _ nty' _) =
553 let co = case lookupCtxt nty (idris_datatypes ist) of
554 [TI _ x _ _] -> x
555 _ -> False in
556 nty == nty' && not co
557 isInductive _ _ = False
559 dePat (Bind x (PVar ty) sc) = dePat (instantiate (P Bound x ty) sc)
560 dePat t = t
562 patvars (Bind x (PVar _) sc) = x : patvars sc
563 patvars _ = []
565checkSizeChange :: Name -> Idris Totality
566checkSizeChange n = do
567 ist <- getIState
568 case lookupCtxt n (idris_callgraph ist) of
569 [cg] -> do let ms = mkMultiPaths ist [] (scg cg)
570 logLvl 5 ("Multipath for " ++ show n ++ ":\n" ++
571 "from " ++ show (scg cg) ++ "\n" ++
572 show (length ms) ++ "\n" ++
573 showSep "\n" (map show ms))
574 logLvl 6 (show cg)
575 -- every multipath must have an infinitely descending
576 -- thread, then the function terminates
577 -- also need to checks functions called are all total
578 -- (Unchecked is okay as we'll spot problems here)
579 let tot = map (checkMP ist (getArity ist n)) ms
580 logLvl 4 $ "Generated " ++ show (length tot) ++ " paths"
581 logLvl 6 $ "Paths for " ++ show n ++ " yield " ++ (show tot)
582 return (noPartial tot)
583 [] -> do logLvl 5 $ "No paths for " ++ show n
584 return Unchecked
585 where getArity ist n
586 = case lookupTy n (tt_ctxt ist) of
587 [ty] -> arity (normalise (tt_ctxt ist) [] ty)
588 _ -> error "Can't happen: checkSizeChange.getArity"
590type MultiPath = [SCGEntry]
592mkMultiPaths :: IState -> MultiPath -> [SCGEntry] -> [MultiPath]
593mkMultiPaths ist path [] = [reverse path]
594mkMultiPaths ist path cg
595 = concat (map extend cg)
596 where extend (nextf, args)
597 | (nextf, args) `elem` path = [ reverse ((nextf, args) : path) ]
598 | [Unchecked] <- lookupTotal nextf (tt_ctxt ist)
599 = case lookupCtxt nextf (idris_callgraph ist) of
600 [ncg] -> mkMultiPaths ist ((nextf, args) : path) (scg ncg)
601 _ -> [ reverse ((nextf, args) : path) ]
602 | otherwise = [ reverse ((nextf, args) : path) ]
604-- do (nextf, args) <- cg
605-- if ((nextf, args) `elem` path)
606-- then return (reverse ((nextf, args) : path))
607-- else case lookupCtxt nextf (idris_callgraph ist) of
608-- [ncg] -> mkMultiPaths ist ((nextf, args) : path) (scg ncg)
609-- _ -> return (reverse ((nextf, args) : path))
611-- If any route along the multipath leads to infinite descent, we're fine.
612-- Try a route beginning with every argument.
613-- If we reach a point we've been to before, but with a smaller value,
614-- that means there is an infinitely descending path from that argument.
616checkMP :: IState -> Int -> MultiPath -> Totality
617checkMP ist i mp = if i > 0
618 then let paths = (map (tryPath 0 [] mp) [0..i-1]) in
619-- trace ("Paths " ++ show paths) $
620 collapse paths
621 else tryPath 0 [] mp 0
622 where
623 tryPath' d path mp arg
624 = let res = tryPath d path mp arg in
625 trace (show mp ++ "\n" ++ show arg ++ " " ++ show res) res
627 tryPath :: Int -> [((SCGEntry, Int), Int)] -> MultiPath -> Int -> Totality
628 tryPath desc path [] _ = Total []
629-- tryPath desc path ((UN "believe_me", _) : _) arg
630-- = Partial BelieveMe
631 -- if we get to a constructor, it's fine as long as it's strictly positive
632 tryPath desc path ((f, _) : es) arg
633 | [TyDecl (DCon _ _) _] <- lookupDef f (tt_ctxt ist)
634 = case lookupTotal f (tt_ctxt ist) of
635 [Total _] -> Unchecked -- okay so far
636 [Partial _] -> Partial (Other [f])
637 x -> error (show x)
638 | [TyDecl (TCon _ _) _] <- lookupDef f (tt_ctxt ist)
639 = Total []
640 tryPath desc path (e@(f, args) : es) arg
641 | e `elem` es && allNothing args = Partial (Mutual [f])
642 tryPath desc path (e@(f, nextargs) : es) arg
643 | Just d <- lookup (e, arg) path
644 = if desc > 0
645 then -- trace ("Descent " ++ show (desc - d) ++ " "
646 -- ++ show (path, e)) $
647 Total []
648 else Partial (Mutual (map (fst . fst . fst) path ++ [f]))
649 | e `elem` map (fst . fst) path
650 && not (f `elem` map fst es)
651 = Partial (Mutual (map (fst . fst . fst) path ++ [f]))
652 | [Unchecked] <- lookupTotal f (tt_ctxt ist) =
653 let argspos = case collapseNothing (zip nextargs [0..]) of
654 [] -> [(Nothing, 0)]
655 x -> x
656-- trace (show (argspos, nextargs, path)) $
657 pathres =
658 do (a, pos) <- argspos
659 case a of
660 Nothing -> -- don't know, but if the
661 -- rest definitely terminates without
662 -- any cycles with route so far,
663 -- then we might yet be total
664 case collapse (map (tryPath 0 (((e, arg), 0):path) es)
665 [0..length nextargs - 1]) of
666 Total _ -> return Unchecked
667 x -> return x
668 Just (nextarg, sc) ->
669 if nextarg == arg then
670 case sc of
671 Same -> return $ tryPath desc (((e, arg), desc) : path)
672 es pos
673 Smaller -> return $ tryPath (desc+1)
674 (((e, arg), desc) : path)
675 es
676 pos
677 _ -> trace ("Shouldn't happen " ++ show e) $
678 return (Partial Itself)
679 else return Unchecked in
680-- trace (show (desc, argspos, path, es, pathres)) $
681 collapse' Unchecked pathres
683 | [Total a] <- lookupTotal f (tt_ctxt ist) = Total a
684 | [Partial _] <- lookupTotal f (tt_ctxt ist) = Partial (Other [f])
685 | otherwise = Unchecked
687allNothing xs = null (collapseNothing (zip xs [0..]))
689collapseNothing ((Nothing, _) : xs)
690 = filter (\ (x, _) -> case x of
691 Nothing -> False
692 _ -> True) xs
693collapseNothing (x : xs) = x : collapseNothing xs
694collapseNothing [] = []
696noPartial (Partial p : xs) = Partial p
697noPartial (_ : xs) = noPartial xs
698noPartial [] = Total []
700collapse xs = collapse' Unchecked xs
701collapse' def (Total r : xs) = Total r
702collapse' def (Unchecked : xs) = collapse' def xs
703collapse' def (d : xs) = collapse' d xs
704-- collapse' Unchecked [] = Total []
705collapse' def [] = def