on f01873f help sign in
Idris-dev/src/Idris/Coverage.hs
638 lines 26 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
13import Data.List
14import Data.Either
15import Data.Maybe
16import Debug.Trace
18import Control.Monad.State.Strict
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 (sMN 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 -> showTm i (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 [] 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 (showTm i) 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 (showTm i) 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 (sUN "A") Placeholder True,
170 pimp (sUN "B") Placeholder True] ++
171 [pexp l, pexp r]) o
172 otherPats o@(PDPair fc p t _ v)
173 = ops fc (sUN "Ex_intro")
174 ([pimp (sUN "a") Placeholder True,
175 pimp (sUN "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 ei)) [_,_,t,v])
195 | ei == txt "Ex_intro"
196 = PDPair fc TypeOrTerm (getTm t) Placeholder (getTm v)
197 resugar (PApp _ (PRef fc n) [_,_,l,r])
198 | n == pairCon
199 = PPair fc IsTerm (getTm l) (getTm r)
200 resugar t = t
202 dropForce force (x : xs) i | i `elem` force
203 = upd Placeholder x : dropForce force xs (i + 1)
204 dropForce force (x : xs) i = x : dropForce force xs (i + 1)
205 dropForce _ [] _ = []
208 getTy n ctxt = case lookupTy n ctxt of
209 (t : _) -> case unApply (getRetTy t) of
210 (P _ tyn _, _) -> tyn
211 x -> error $ "Can't happen getTy 1 " ++ show (n, x)
212 _ -> error "Can't happen getTy 2"
214 mkPat fc x = case lookupCtxt x (idris_implicits i) of
215 (pargs : _)
216 -> PApp fc (PRef fc x) (map (upd Placeholder) pargs)
217 _ -> error "Can't happen - genAll"
219upd p' p = p { getTm = p' }
221-- Check if, in a given type n, the constructor cn : ty is strictly positive,
222-- and update the context accordingly
224checkPositive :: Name -> (Name, Type) -> Idris ()
225checkPositive n (cn, ty')
226 = do let ty = delazy ty'
227 let p = cp ty
228 i <- getIState
229 let tot = if p then Total (args ty) else Partial NotPositive
230 let ctxt' = setTotal cn tot (tt_ctxt i)
231 putIState (i { tt_ctxt = ctxt' })
232 logLvl 5 $ "Constructor " ++ show cn ++ " is " ++ show tot
233 addIBC (IBCTotal cn tot)
234 where
235 args t = [0..length (getArgTys t)-1]
237 cp (Bind n (Pi aty) sc) = posArg aty && cp sc
238 cp t = True
240 posArg (Bind _ (Pi nty) sc)
241 | (P _ n' _, args) <- unApply nty
242 = n /= n' && posArg sc
243 posArg t = True
245calcProd :: IState -> FC -> Name -> [([Name], Term, Term)] -> Idris Totality
246calcProd i fc topn pats
247 = cp topn pats []
248 where
249 -- every application of n must be in an argument of a coinductive
250 -- constructor, in every function reachable from here in the
251 -- call graph.
252 cp n pats done = do patsprod <- mapM (prodRec n done) pats
253 if (and patsprod)
254 then return Productive
255 else return (Partial NotProductive)
257 prodRec :: Name -> [Name] -> ([Name], Term, Term) -> Idris Bool
258 prodRec n done _ | n `elem` done = return True
259 prodRec n done (_, _, tm) = prod n done False (delazy tm)
261 prod :: Name -> [Name] -> Bool -> Term -> Idris Bool
262 prod n done ok ap@(App _ _)
263 | (P nt f _, args) <- unApply ap
264 = do recOK <- checkProdRec (n:done) f
265 let ctxt = tt_ctxt i
266 let [ty] = lookupTy f ctxt -- must exist!
267 let co = cotype nt f ty in
268 if (not recOK) then return False else
269 if f == topn
270 then do argsprod <- mapM (prod n done co) args
271 return (and (ok : argsprod) )
272 else do argsprod <- mapM (prod n done co) args
273 return (and argsprod)
274 prod n done ok (App f a) = liftM2 (&&) (prod n done False f)
275 (prod n done False a)
276 prod n done ok (Bind _ (Let t v) sc)
277 = liftM2 (&&) (prod n done False v) (prod n done False v)
278 prod n done ok (Bind _ b sc) = prod n done ok sc
279 prod n done ok t = return True
281 checkProdRec :: [Name] -> Name -> Idris Bool
282 checkProdRec done f
283 = case lookupCtxt f (idris_patdefs i) of
284 [(def, _)] -> do ok <- mapM (prodRec f done) def
285 return (and ok)
286 _ -> return True -- defined elsewhere, can't call topn
288 cotype (DCon _ _) n ty
289 | (P _ t _, _) <- unApply (getRetTy ty)
290 = case lookupCtxt t (idris_datatypes i) of
291 [TI _ True _ _] -> True
292 _ -> False
293 cotype nt n ty = False
295calcTotality :: [Name] -> FC -> Name -> [([Name], Term, Term)]
296 -> Idris Totality
297calcTotality path fc n pats
298 = do i <- getIState
299 let opts = case lookupCtxt n (idris_flags i) of
300 [fs] -> fs
301 _ -> []
302 case mapMaybe (checkLHS i) (map (\ (_, l, r) -> l) pats) of
303 (failure : _) -> return failure
304 _ -> if (Coinductive `elem` opts)
305 then calcProd i fc n pats
306 else checkSizeChange n
307 where
308 checkLHS i (P _ fn _)
309 = case lookupTotal fn (tt_ctxt i) of
310 [Partial _] -> return (Partial (Other [fn]))
311 _ -> Nothing
312 checkLHS i (App f a) = mplus (checkLHS i f) (checkLHS i a)
313 checkLHS _ _ = Nothing
315checkTotality :: [Name] -> FC -> Name -> Idris Totality
316checkTotality path fc n
317 | n `elem` path = return (Partial (Mutual (n : path)))
318 | otherwise = do
319 t <- getTotality n
320 updateContext (simplifyCasedef n)
321 ctxt <- getContext
322 i <- getIState
323 let opts = case lookupCtxt n (idris_flags i) of
324 [fs] -> fs
325 _ -> []
326 t' <- case t of
327 Unchecked ->
328 case lookupDef n ctxt of
329 [CaseOp _ _ _ _ pats _] ->
330 do t' <- if AssertTotal `elem` opts
331 then return $ Total []
332 else calcTotality path fc n pats
333 setTotality n t'
334 addIBC (IBCTotal n t')
335 return t'
336 _ -> return $ Total []
337 x -> return x
338 case t' of
339 Total _ -> return t'
340 Productive -> return t'
341 e -> do w <- cmdOptType WarnPartial
342 if TotalFn `elem` opts
343 then totalityError t'
344 else do when (w && not (PartialFn `elem` opts)) $
345 warnPartial n t'
346 return t'
347 where
348 totalityError t = tclift $ tfail (At fc (Msg (show n ++ " is " ++ show t)))
350 warnPartial n t
351 = do i <- getIState
352 case lookupDef n (tt_ctxt i) of
353 [x] -> do
354 iputStrLn $ show fc ++ ":Warning - " ++ show n ++ " is " ++ show t
355-- ++ "\n" ++ show x
356-- let cg = lookupCtxtName Nothing n (idris_callgraph i)
357-- iputStrLn (show cg)
360checkDeclTotality :: (FC, Name) -> Idris Totality
361checkDeclTotality (fc, n)
362 = do logLvl 2 $ "Checking " ++ show n ++ " for totality"
363-- buildSCG (fc, n)
364-- logLvl 2 $ "Built SCG"
365 i <- getIState
366 t <- checkTotality [] fc n
367 case t of
368 -- if it's not total, it can't reduce, to keep
369 -- typechecking decidable
370 p@(Partial _) -> do setAccessibility n Frozen
371 addIBC (IBCAccess n Frozen)
372 logLvl 5 $ "HIDDEN: "
373 ++ show n ++ show p
374 _ -> return ()
375 return t
378-- Calculate the size change graph for this definition
380-- SCG for a function f consists of a list of:
381-- (g, [(a1, sizechange1), (a2, sizechange2), ..., (an, sizechangen)])
383-- where g is a function called
384-- a1 ... an are the arguments of f in positions 1..n of g
385-- sizechange1 ... sizechange2 is how their size has changed wrt the input
386-- to f
387-- Nothing, if the argument is unrelated to the input
389buildSCG :: (FC, Name) -> Idris ()
390buildSCG (_, n) = do
391 ist <- getIState
392 case lookupCtxt n (idris_callgraph ist) of
393 [cg] -> case lookupDef n (tt_ctxt ist) of
394 [CaseOp _ _ _ pats _ cd] ->
395 let (args, sc) = cases_totcheck cd in
396 do logLvl 2 $ "Building SCG for " ++ show n ++ " from\n"
397 ++ show pats ++ "\n" ++ show sc
398 let newscg = buildSCG' ist (rights pats) args
399 logLvl 5 $ show newscg
400 addToCG n ( cg { scg = newscg } )
401 [] -> logLvl 5 $ "Could not build SCG for " ++ show n ++ "\n"
402 x -> error $ "buildSCG: " ++ show (n, x)
404delazy t@(App f a)
405 | (P _ (UN l) _, [_, arg]) <- unApply t,
406 l == txt "Force" = delazy arg
407 | (P _ (UN l) _, [_, arg]) <- unApply t,
408 l == txt "Delay" = delazy arg
409 | (P _ (UN l) _, [arg]) <- unApply t,
410 l == txt "Lazy" = delazy arg
411delazy (App f a) = App (delazy f) (delazy a)
412delazy (Bind n b sc) = Bind n (fmap delazy b) (delazy sc)
413delazy t = t
415buildSCG' :: IState -> [(Term, Term)] -> [Name] -> [SCGEntry]
416buildSCG' ist pats args = nub $ concatMap scgPat pats where
417 scgPat (lhs, rhs) = let lhs' = delazy lhs
418 rhs' = delazy rhs
419 (f, pargs) = unApply (dePat lhs') in
420 findCalls (dePat rhs') (patvars lhs') pargs
422 findCalls ap@(App f a) pvs pargs
423 -- under a call to "assert_total", don't do any checking, just believe
424 -- that it is total.
425 | (P _ (UN at) _, [_, _]) <- unApply ap,
426 at == txt "assert_total" = []
427 | (P _ n _, args) <- unApply ap
428 = mkChange n args pargs ++
429 concatMap (\x -> findCalls x pvs pargs) args
430 findCalls (App f a) pvs pargs
431 = findCalls f pvs pargs ++ findCalls a pvs pargs
432 findCalls (Bind n (Let t v) e) pvs pargs
433 = findCalls v pvs pargs ++ findCalls e (n : pvs) pargs
434 findCalls (Bind n _ e) pvs pargs
435 = findCalls e (n : pvs) pargs
436 findCalls (P _ f _ ) pvs pargs
437 | not (f `elem` pvs) = [(f, [])]
438 findCalls _ _ _ = []
440 expandToArity n args
441 = case lookupTy n (tt_ctxt ist) of
442 [ty] -> expand 0 (normalise (tt_ctxt ist) [] ty) args
443 _ -> args
444 where expand i (Bind n (Pi _) sc) (x : xs) = x : expand (i + 1) sc xs
445 expand i (Bind n (Pi _) sc) [] = Just (i, Same) : expand (i + 1) sc []
446 expand i _ xs = xs
448 mkChange n args pargs = [(n, expandToArity n (sizes args))]
449 where
450 sizes [] = []
451 sizes (a : as) = checkSize a pargs 0 : sizes as
453 -- find which argument in pargs <a> is smaller than, if any
454 checkSize a (p : ps) i
455 | a == p = Just (i, Same)
456 | (P _ (UN as) _, [_,arg,_]) <- unApply a,
457 as == txt "assert_smaller" && arg == p
458 = Just (i, Smaller)
459 | smaller Nothing a (p, Nothing) = Just (i, Smaller)
460 | otherwise = checkSize a ps (i + 1)
461 checkSize a [] i = Nothing
463 -- the smaller thing we find must be the same type as <a>, and
464 -- not be coinductive - so carry the type of the constructor we've
465 -- gone under.
467 smaller (Just tyn) a (t, Just tyt)
468 | a == t = isInductive (fst (unApply (getRetTy tyn)))
469 (fst (unApply (getRetTy tyt)))
470 smaller ty a (ap@(App f s), _)
471 | (P (DCon _ _) n _, args) <- unApply ap
472 = let tyn = getType n in
473 any (smaller (ty `mplus` Just tyn) a)
474 (zip args (map toJust (getArgTys tyn)))
475 -- check higher order recursive arguments
476 smaller ty (App f s) a = smaller ty f a
477 smaller _ _ _ = False
479 toJust (n, t) = Just t
481 getType n = case lookupTy n (tt_ctxt ist) of
482 [ty] -> delazy ty -- must exist
484 isInductive (P _ nty _) (P _ nty' _) =
485 let co = case lookupCtxt nty (idris_datatypes ist) of
486 [TI _ x _ _] -> x
487 _ -> False in
488 nty == nty' && not co
489 isInductive _ _ = False
491 dePat (Bind x (PVar ty) sc) = dePat (instantiate (P Bound x ty) sc)
492 dePat t = t
494 patvars (Bind x (PVar _) sc) = x : patvars sc
495 patvars _ = []
497checkSizeChange :: Name -> Idris Totality
498checkSizeChange n = do
499 ist <- getIState
500 case lookupCtxt n (idris_callgraph ist) of
501 [cg] -> do let ms = mkMultiPaths ist [] (scg cg)
502 logLvl 5 ("Multipath for " ++ show n ++ ":\n" ++
503 "from " ++ show (scg cg) ++ "\n" ++
504 show (length ms) ++ "\n" ++
505 showSep "\n" (map show ms))
506 logLvl 6 (show cg)
507 -- every multipath must have an infinitely descending
508 -- thread, then the function terminates
509 -- also need to checks functions called are all total
510 -- (Unchecked is okay as we'll spot problems here)
511 let tot = map (checkMP ist (getArity ist n)) ms
512 logLvl 4 $ "Generated " ++ show (length tot) ++ " paths"
513 logLvl 6 $ "Paths for " ++ show n ++ " yield " ++ (show tot)
514 return (noPartial tot)
515 [] -> do logLvl 5 $ "No paths for " ++ show n
516 return Unchecked
517 where getArity ist n
518 = case lookupTy n (tt_ctxt ist) of
519 [ty] -> arity (normalise (tt_ctxt ist) [] ty)
520 _ -> error "Can't happen: checkSizeChange.getArity"
522type MultiPath = [SCGEntry]
524mkMultiPaths :: IState -> MultiPath -> [SCGEntry] -> [MultiPath]
525mkMultiPaths ist path [] = [reverse path]
526mkMultiPaths ist path cg
527 = concat (map extend cg)
528 where extend (nextf, args)
529 | (nextf, args) `elem` path = [ reverse ((nextf, args) : path) ]
530 | [Unchecked] <- lookupTotal nextf (tt_ctxt ist)
531 = case lookupCtxt nextf (idris_callgraph ist) of
532 [ncg] -> mkMultiPaths ist ((nextf, args) : path) (scg ncg)
533 _ -> [ reverse ((nextf, args) : path) ]
534 | otherwise = [ reverse ((nextf, args) : path) ]
536-- do (nextf, args) <- cg
537-- if ((nextf, args) `elem` path)
538-- then return (reverse ((nextf, args) : path))
539-- else case lookupCtxt nextf (idris_callgraph ist) of
540-- [ncg] -> mkMultiPaths ist ((nextf, args) : path) (scg ncg)
541-- _ -> return (reverse ((nextf, args) : path))
543-- If any route along the multipath leads to infinite descent, we're fine.
544-- Try a route beginning with every argument.
545-- If we reach a point we've been to before, but with a smaller value,
546-- that means there is an infinitely descending path from that argument.
548checkMP :: IState -> Int -> MultiPath -> Totality
549checkMP ist i mp = if i > 0
550 then let paths = (map (tryPath 0 [] mp) [0..i-1]) in
551-- trace ("Paths " ++ show paths) $
552 collapse paths
553 else tryPath 0 [] mp 0
554 where
555 tryPath' d path mp arg
556 = let res = tryPath d path mp arg in
557 trace (show mp ++ "\n" ++ show arg ++ " " ++ show res) res
559 tryPath :: Int -> [((SCGEntry, Int), Int)] -> MultiPath -> Int -> Totality
560 tryPath desc path [] _ = Total []
561-- tryPath desc path ((UN "believe_me", _) : _) arg
562-- = Partial BelieveMe
563 -- if we get to a constructor, it's fine as long as it's strictly positive
564 tryPath desc path ((f, _) : es) arg
565 | [TyDecl (DCon _ _) _] <- lookupDef f (tt_ctxt ist)
566 = case lookupTotal f (tt_ctxt ist) of
567 [Total _] -> Unchecked -- okay so far
568 [Partial _] -> Partial (Other [f])
569 x -> error (show x)
570 | [TyDecl (TCon _ _) _] <- lookupDef f (tt_ctxt ist)
571 = Total []
572 tryPath desc path (e@(f, args) : es) arg
573 | e `elem` es && allNothing args = Partial (Mutual [f])
574 tryPath desc path (e@(f, nextargs) : es) arg
575 | Just d <- lookup (e, arg) path
576 = if desc > 0
577 then -- trace ("Descent " ++ show (desc - d) ++ " "
578 -- ++ show (path, e)) $
579 Total []
580 else Partial (Mutual (map (fst . fst . fst) path ++ [f]))
581 | e `elem` map (fst . fst) path
582 && not (f `elem` map fst es)
583 = Partial (Mutual (map (fst . fst . fst) path ++ [f]))
584 | [Unchecked] <- lookupTotal f (tt_ctxt ist) =
585 let argspos = case collapseNothing (zip nextargs [0..]) of
586 [] -> [(Nothing, 0)]
587 x -> x
588-- trace (show (argspos, nextargs, path)) $
589 pathres =
590 do (a, pos) <- argspos
591 case a of
592 Nothing -> -- don't know, but if the
593 -- rest definitely terminates without
594 -- any cycles with route so far,
595 -- then we might yet be total
596 case collapse (map (tryPath 0 (((e, arg), 0):path) es)
597 [0..length nextargs - 1]) of
598 Total _ -> return Unchecked
599 x -> return x
600 Just (nextarg, sc) ->
601 if nextarg == arg then
602 case sc of
603 Same -> return $ tryPath desc (((e, arg), desc) : path)
604 es pos
605 Smaller -> return $ tryPath (desc+1)
606 (((e, arg), desc) : path)
607 es
608 pos
609 _ -> trace ("Shouldn't happen " ++ show e) $
610 return (Partial Itself)
611 else return Unchecked in
612-- trace (show (desc, argspos, path, es, pathres)) $
613 collapse' Unchecked pathres
615 | [Total a] <- lookupTotal f (tt_ctxt ist) = Total a
616 | [Partial _] <- lookupTotal f (tt_ctxt ist) = Partial (Other [f])
617 | otherwise = Unchecked
619allNothing xs = null (collapseNothing (zip xs [0..]))
621collapseNothing ((Nothing, _) : xs)
622 = filter (\ (x, _) -> case x of
623 Nothing -> False
624 _ -> True) xs
625collapseNothing (x : xs) = x : collapseNothing xs
626collapseNothing [] = []
628noPartial (Partial p : xs) = Partial p
629noPartial (_ : xs) = noPartial xs
630noPartial [] = Total []
632collapse xs = collapse' Unchecked xs
633collapse' def (Total r : xs) = Total r
634collapse' def (Unchecked : xs) = collapse' def xs
635collapse' def (d : xs) = collapse' d xs
636-- collapse' Unchecked [] = Total []
637collapse' def [] = def