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