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