1{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, PatternGuards #-}
3{- Implements a proof state, some primitive tactics for manipulating
4 proofs, and some high level commands for introducing new theorems,
5 evaluation/checking inside the proof system, etc. --}
7module Idris.Core.ProofState(ProofState(..), newProof, envAtFocus, goalAtFocus,
8 Tactic(..), Goal(..), processTactic, nowElaboratingPS, doneElaboratingAppPS,
9 doneElaboratingArgPS, dropGiven, keepGiven, getProvenance) where
11import Idris.Core.Typecheck
12import Idris.Core.Evaluate
14import Idris.Core.Unify
15import Idris.Core.ProofTerm
17import Control.Monad.State.Strict
18import Control.Applicative hiding (empty)
19import Control.Arrow ((***))
23import Util.Pretty hiding (fill)
25data ProofState = PS { thname :: Name,
26 holes :: [Name], -- ^ holes still to be solved
27 usedns :: [Name], -- ^ used names, don't use again
28 nextname :: Int, -- ^ name supply
29 pterm :: ProofTerm, -- ^ current proof term
30 ptype :: Type, -- ^ original goal
31 dontunify :: [Name], -- ^ explicitly given by programmer, leave it
32 unified :: (Name, [(Name, Term)]),
33 notunified :: [(Name, Term)],
34 dotted :: [(Name, [Name])], -- ^ dot pattern holes + environment
35 -- either hole or something in env must turn up in the 'notunified' list during elaboration
36 solved :: Maybe (Name, Term),
39 deferred :: [Name], -- ^ names we'll need to define
40 instances :: [Name], -- ^ instance arguments (for type classes)
41 autos :: [(Name, ([FailContext], [Name]))], -- ^ unsolved 'auto' implicits with their holes
42 psnames :: [Name], -- ^ Local names okay to use in proof search
43 previous :: Maybe ProofState, -- ^ for undo
45 datatypes :: Ctxt TypeInfo,
50 while_elaborating :: [FailContext]
55 | ClaimFn Name Name Raw
60 | PrepFill Name [Name]
74 | IntroTy Raw (Maybe Name)
75 | Forall Name (Maybe ImplicitInfo) Raw
76 | LetBind Name Raw Raw
86 | DeferType Name Raw [Name]
99-- Some utilites on proof and tactic states
101instance Show ProofState where
102 show ps | [] <- holes ps
103 = show (thname ps) ++ ": no more goals"
104 show ps | (h : hs) <- holes ps
107 OK g = goal (Just h) tm
108 wkenv = premises g in
109 "Other goals: " ++ show hs ++ "\n" ++
110 showPs wkenv (reverse wkenv) ++ "\n" ++
111 "-------------------------------- (" ++ show nm ++
113 show h ++ " : " ++ showG wkenv (goalType g) ++ "\n"
114 where showPs env [] = ""
115 showPs env ((n, Let t v):bs)
116 = " " ++ show n ++ " : " ++
117 showEnv env ({- normalise ctxt env -} t) ++ " = " ++
118 showEnv env ({- normalise ctxt env -} v) ++
119 "\n" ++ showPs env bs
120 showPs env ((n, b):bs)
121 = " " ++ show n ++ " : " ++
122 showEnv env ({- normalise ctxt env -} (binderTy b)) ++
123 "\n" ++ showPs env bs
124 showG ps (Guess t v) = showEnv ps ({- normalise ctxt ps -} t) ++
125 " =?= " ++ showEnv ps v
126 showG ps b = showEnv ps (binderTy b)
128instance Pretty ProofState OutputAnnotation where
129 pretty ps | [] <- holes ps =
130 pretty (thname ps) <+> colon <+> text " no more goals."
131 pretty ps | (h : hs) <- holes ps =
133 OK g = goal (Just h) tm
135 let wkEnv = premises g in
136 text "Other goals" <+> colon <+> pretty hs <+>
137 prettyPs wkEnv (reverse wkEnv) <+>
138 text "---------- " <+> text "Focussing on" <> colon <+> pretty nm <+> text " ----------" <+>
139 pretty h <+> colon <+> prettyGoal wkEnv (goalType g)
141 prettyGoal ps (Guess t v) =
142 prettyEnv ps t <+> text "=?=" <+> prettyEnv ps v
143 prettyGoal ps b = prettyEnv ps $ binderTy b
145 prettyPs env [] = empty
146 prettyPs env ((n, Let t v):bs) =
147 nest nestingSize (pretty n <+> colon <+>
148 prettyEnv env t <+> text "=" <+> prettyEnv env v <+>
149 nest nestingSize (prettyPs env bs))
150 prettyPs env ((n, b):bs) =
151 nest nestingSize (pretty n <+> colon <+> prettyEnv env (binderTy b) <+>
152 nest nestingSize (prettyPs env bs))
154holeName i = sMN i "hole"
156qshow :: Fails -> String
157qshow fs = show (map (\ (x, y, hs, env, _, _, t) -> (t, map fst env, x, y, hs)) fs)
159match_unify' :: Context -> Env ->
160 (TT Name, Maybe Provenance) ->
161 (TT Name, Maybe Provenance) ->
162 StateT TState TC [(Name, TT Name)]
163match_unify' ctxt env (topx, xfrom) (topy, yfrom) =
165 let while = while_elaborating ps
166 let dont = dontunify ps
167 let inj = injective ps
168 traceWhen (unifylog ps)
169 ("Matching " ++ show (topx, topy) ++
170 " in " ++ show env ++
171 "\nHoles: " ++ show (holes ps)
173 ++ "\n" ++ show (getProofTerm (pterm ps)) ++ "\n\n"
175 case match_unify ctxt env (topx, xfrom) (topy, yfrom) inj (holes ps) while of
176 OK u -> traceWhen (unifylog ps)
177 ("Matched " ++ show u) $
178 do let (h, ns) = unified ps
179 put (ps { unified = (h, u ++ ns) })
181 Error e -> traceWhen (unifylog ps)
182 ("No match " ++ show e) $
183 do put (ps { problems = (topx, topy, True,
184 env, e, while, Match) :
187-- traceWhen (unifylog ps)
188-- ("Matched " ++ show (topx, topy) ++ " without " ++ show dont ++
189-- "\nSolved: " ++ show u
190-- ++ "\nCurrent problems:\n" ++ qshow (problems ps)
191-- -- ++ show (pterm ps)
192-- ++ "\n----------") $
194mergeSolutions :: Env -> [(Name, TT Name)] -> StateT TState TC [(Name, TT Name)]
195mergeSolutions env ns = merge [] ns
197 merge acc [] = return (reverse acc)
198 merge acc ((n, t) : ns)
199 | Just t' <- lookup n ns
201 let probs = problems ps
202 put (ps { problems = probs ++ [(t,t',True,env,
203 CantUnify True (t, Nothing) (t', Nothing) (Msg "") (errEnv env) 0,
206 | otherwise = merge ((n, t): acc) ns
208unify' :: Context -> Env ->
209 (TT Name, Maybe Provenance) ->
210 (TT Name, Maybe Provenance) ->
211 StateT TState TC [(Name, TT Name)]
212unify' ctxt env (topx, xfrom) (topy, yfrom) =
214 let while = while_elaborating ps
215 let dont = dontunify ps
216 let inj = injective ps
217 (u, fails) <- traceWhen (unifylog ps)
218 ("Trying " ++ show (topx, topy) ++
219 "\nNormalised " ++ show (normalise ctxt env topx,
220 normalise ctxt env topy) ++
221 " in\n" ++ show env ++
222 "\nHoles: " ++ show (holes ps)
223 ++ "\nInjective: " ++ show (injective ps)
225 lift $ unify ctxt env (topx, xfrom) (topy, yfrom) inj (holes ps)
226 (map fst (notunified ps)) while
227 let notu = filter (\ (n, t) -> case t of
229 _ -> n `elem` dont) u
230 traceWhen (unifylog ps)
231 ("Unified " ++ show (topx, topy) ++ " without " ++ show dont ++
232 "\nSolved: " ++ show u ++ "\nNew problems: " ++ qshow fails
233 ++ "\nNot unified:\n" ++ show (notunified ps)
234 ++ "\nCurrent problems:\n" ++ qshow (problems ps)
237 do let (h, ns) = unified ps
238 -- solve in results (maybe unify should do this itself...)
239 let u' = map (\(n, sol) -> (n, updateSolvedTerm u sol)) u
240 -- if a metavar has multiple solutions, make a new unification
242 uns <- mergeSolutions env (u' ++ ns)
244 let (ns', probs') = updateProblems ps uns (fails ++ problems ps)
245 let (notu', probs_notu) = mergeNotunified env (holes ps) (notu ++ notunified ps)
246 traceWhen (unifylog ps)
247 ("Now solved: " ++ show ns' ++
248 "\nNow problems: " ++ qshow (probs' ++ probs_notu) ++
249 "\nNow injective: " ++ show (updateInj u (injective ps))) $
250 put (ps { problems = probs' ++ probs_notu,
252 injective = updateInj u (injective ps),
253 notunified = notu' })
255 where updateInj ((n, a) : us) inj
256 | (P _ n' _, _) <- unApply a,
257 n `elem` inj = updateInj us (n':inj)
258 | (P _ n' _, _) <- unApply a,
259 n' `elem` inj = updateInj us (n:inj)
260 updateInj (_ : us) inj = updateInj us inj
261 updateInj [] inj = inj
263nowElaboratingPS :: FC -> Name -> Name -> ProofState -> ProofState
264nowElaboratingPS fc f arg ps = ps { while_elaborating = FailContext fc f arg : while_elaborating ps }
266dropUntil :: (a -> Bool) -> [a] -> [a]
268dropUntil p (x:xs) | p x = xs
269 | otherwise = dropUntil p xs
271doneElaboratingAppPS :: Name -> ProofState -> ProofState
272doneElaboratingAppPS f ps = let while = while_elaborating ps
273 while' = dropUntil (\ (FailContext _ f' _) -> f == f') while
274 in ps { while_elaborating = while' }
276doneElaboratingArgPS :: Name -> Name -> ProofState -> ProofState
277doneElaboratingArgPS f x ps = let while = while_elaborating ps
278 while' = dropUntil (\ (FailContext _ f' x') -> f == f' && x == x') while
279 in ps { while_elaborating = while' }
281getName :: Monad m => String -> StateT TState m Name
282getName tag = do ps <- get
284 put (ps { nextname = n+1 })
287action :: Monad m => (ProofState -> ProofState) -> StateT TState m ()
288action a = do ps <- get
291query :: Monad m => (ProofState -> r) -> StateT TState m r
292query q = do ps <- get
295addLog :: Monad m => String -> StateT TState m ()
296addLog str = action (\ps -> ps { plog = plog ps ++ str ++ "\n" })
298newProof :: Name -> Context -> Ctxt TypeInfo -> Type -> ProofState
299newProof n ctxt datatypes ty =
302 in PS n [h] [] 1 (mkProofTerm (Bind h (Hole ty')
303 (P Bound h ty'))) ty [] (h, []) [] []
306 Nothing ctxt datatypes "" False False [] []
308type TState = ProofState -- [TacticAction])
309type RunTactic = RunTactic' TState
311envAtFocus :: ProofState -> TC Env
313 | not $ null (holes ps) = do g <- goal (Just (head (holes ps))) (pterm ps)
315 | otherwise = fail "No holes"
317goalAtFocus :: ProofState -> TC (Binder Type)
319 | not $ null (holes ps) = do g <- goal (Just (head (holes ps))) (pterm ps)
321 | otherwise = Error . Msg $ "No goal in " ++ show (holes ps) ++ show (getProofTerm (pterm ps))
323tactic :: Hole -> RunTactic -> StateT TState TC ()
324tactic h f = do ps <- get
325 (tm', _) <- atHole h f (context ps) [] (pterm ps)
326 ps <- get -- might have changed while processing
327 put (ps { pterm = tm' })
329computeLet :: Context -> Name -> Term -> Term
330computeLet ctxt n tm = cl [] tm where
331 cl env (Bind n' (Let t v) sc)
332 | n' == n = let v' = normalise ctxt env v in
333 Bind n' (Let t v') sc
334 cl env (Bind n' b sc) = Bind n' (fmap (cl env) b) (cl ((n, b):env) sc)
335 cl env (App s f a) = App s (cl env f) (cl env a)
339attack ctxt env (Bind x (Hole t) sc)
340 = do h <- getName "hole"
341 action (\ps -> ps { holes = h : holes ps })
342 return $ Bind x (Guess t (newtm h)) sc
344 newtm h = Bind h (Hole t) (P Bound h t)
345attack ctxt env _ = fail "Not an attackable hole"
347claim :: Name -> Raw -> RunTactic
348claim n ty ctxt env t =
349 do (tyv, tyt) <- lift $ check ctxt env ty
350 lift $ isType ctxt env tyt
351 action (\ps -> let (g:gs) = holes ps in
352 ps { holes = g : n : gs } )
353 return $ Bind n (Hole tyv) t
355-- If the current goal is 'retty', make a claim which is a function that
356-- can compute a retty from argty (i.e a claim 'argty -> retty')
357claimFn :: Name -> Name -> Raw -> RunTactic
358claimFn n bn argty ctxt env t@(Bind x (Hole retty) sc) =
359 do (tyv, tyt) <- lift $ check ctxt env argty
360 lift $ isType ctxt env tyt
361 action (\ps -> let (g:gs) = holes ps in
362 ps { holes = g : n : gs } )
363 return $ Bind n (Hole (Bind bn (Pi Nothing tyv tyt) retty)) t
364claimFn _ _ _ ctxt env _ = fail "Can't make function type here"
366reorder_claims :: RunTactic
367reorder_claims ctxt env t
368 = -- trace (showSep "\n" (map show (scvs t))) $
369 let (bs, sc) = scvs t []
370 newbs = reverse (sortB (reverse bs)) in
371 traceWhen (bs /= newbs) (show bs ++ "\n ==> \n" ++ show newbs) $
372 return (bindAll newbs sc)
373 where scvs (Bind n b@(Hole _) sc) acc = scvs sc ((n, b):acc)
374 scvs sc acc = (reverse acc, sc)
376 sortB :: [(Name, Binder (TT Name))] -> [(Name, Binder (TT Name))]
378 sortB (x:xs) | all (noOcc x) xs = x : sortB xs
379 | otherwise = sortB (insertB x xs)
382 insertB x (y:ys) | all (noOcc x) (y:ys) = x : y : ys
383 | otherwise = y : insertB x ys
385 noOcc (n, _) (_, Let t v) = noOccurrence n t && noOccurrence n v
386 noOcc (n, _) (_, Guess t v) = noOccurrence n t && noOccurrence n v
387 noOcc (n, _) (_, b) = noOccurrence n (binderTy b)
389focus :: Name -> RunTactic
390focus n ctxt env t = do action (\ps -> let hs = holes ps in
392 then ps { holes = n : (hs \\ [n]) }
397movelast :: Name -> RunTactic
398movelast n ctxt env t = do action (\ps -> let hs = holes ps in
400 then ps { holes = (hs \\ [n]) ++ [n] }
404instanceArg :: Name -> RunTactic
405instanceArg n ctxt env (Bind x (Hole t) sc)
406 = do action (\ps -> let hs = holes ps
408 ps { holes = (hs \\ [x]) ++ [x],
410 return (Bind x (Hole t) sc)
412autoArg :: Name -> RunTactic
413autoArg n ctxt env (Bind x (Hole t) sc)
414 = do action (\ps -> case lookup x (autos ps) of
417 ps { holes = (hs \\ [x]) ++ [x],
418 autos = (x, (while_elaborating ps, refsIn t)) : autos ps }
420 return (Bind x (Hole t) sc)
422setinj :: Name -> RunTactic
423setinj n ctxt env (Bind x b sc)
424 = do action (\ps -> let is = injective ps in
425 ps { injective = n : is })
428defer :: [Name] -> Name -> RunTactic
429defer dropped n ctxt env (Bind x (Hole t) (P nt x' ty)) | x == x' =
430 do let env' = filter (\(n, t) -> n `notElem` dropped) env
431 action (\ps -> let hs = holes ps in
432 ps { holes = hs \\ [x] })
434 return (Bind n (GHole (length env') (psnames ps) (mkTy (reverse env') t))
435 (mkApp (P Ref n ty) (map getP (reverse env'))))
438 mkTy ((n,b) : bs) t = Bind n (Pi Nothing (binderTy b) (TType (UVar 0))) (mkTy bs t)
440 getP (n, b) = P Bound n (binderTy b)
442-- as defer, but build the type and application explicitly
443deferType :: Name -> Raw -> [Name] -> RunTactic
444deferType n fty_in args ctxt env (Bind x (Hole t) (P nt x' ty)) | x == x' =
445 do (fty, _) <- lift $ check ctxt env fty_in
446 action (\ps -> let hs = holes ps
448 ps { holes = hs \\ [x],
450 return (Bind n (GHole 0 [] fty)
451 (mkApp (P Ref n ty) (map getP args)))
453 getP n = case lookup n env of
454 Just b -> P Bound n (binderTy b)
455 Nothing -> error ("deferType can't find " ++ show n)
458regret ctxt env (Bind x (Hole t) sc) | noOccurrence x sc =
459 do action (\ps -> let hs = holes ps in
460 ps { holes = hs \\ [x] })
462regret ctxt env (Bind x (Hole t) _)
463 = fail $ show x ++ " : " ++ show t ++ " is not solved..."
465unifyGoal :: Raw -> RunTactic
466unifyGoal tm ctxt env h@(Bind x b sc) =
467 do (tmv, _) <- lift $ check ctxt env tm
468 ns' <- unify' ctxt env (binderTy b, Nothing) (tmv, Nothing)
471exact :: Raw -> RunTactic
472exact guess ctxt env (Bind x (Hole ty) sc) =
473 do (val, valty) <- lift $ check ctxt env guess
474 lift $ converts ctxt env valty ty
475 return $ Bind x (Guess ty val) sc
476exact _ _ _ _ = fail "Can't fill here."
478-- As exact, but attempts to solve other goals by unification
480fill :: Raw -> RunTactic
481fill guess ctxt env (Bind x (Hole ty) sc) =
482 do (val, valty) <- lift $ check ctxt env guess
483-- let valtyn = normalise ctxt env valty
484-- let tyn = normalise ctxt env ty
485 ns <- unify' ctxt env (valty, Just $ SourceTerm val)
486 (ty, Just (chkPurpose val ty))
488 let (uh, uns) = unified ps
489-- put (ps { unified = (uh, uns ++ ns) })
490-- addLog (show (uh, uns ++ ns))
491 return $ Bind x (Guess ty val) sc
493 -- some expected types show up commonly in errors and indicate a
495 -- argTy -> retTy suggests a function applied to too many arguments
496 chkPurpose val (Bind _ (Pi _ (P _ (MN _ _) _) _) (P _ (MN _ _) _))
498 chkPurpose _ _ = ExpectedType
499fill _ _ _ _ = fail "Can't fill here."
501-- As fill, but attempts to solve other goals by matching
503match_fill :: Raw -> RunTactic
504match_fill guess ctxt env (Bind x (Hole ty) sc) =
505 do (val, valty) <- lift $ check ctxt env guess
506-- let valtyn = normalise ctxt env valty
507-- let tyn = normalise ctxt env ty
508 ns <- match_unify' ctxt env (valty, Just $ SourceTerm val)
509 (ty, Just ExpectedType)
511 let (uh, uns) = unified ps
512-- put (ps { unified = (uh, uns ++ ns) })
513-- addLog (show (uh, uns ++ ns))
514 return $ Bind x (Guess ty val) sc
515match_fill _ _ _ _ = fail "Can't fill here."
517prep_fill :: Name -> [Name] -> RunTactic
518prep_fill f as ctxt env (Bind x (Hole ty) sc) =
519 do let val = mkApp (P Ref f Erased) (map (\n -> P Ref n Erased) as)
520 return $ Bind x (Guess ty val) sc
521prep_fill f as ctxt env t = fail $ "Can't prepare fill at " ++ show t
523complete_fill :: RunTactic
524complete_fill ctxt env (Bind x (Guess ty val) sc) =
525 do let guess = forget val
526 (val', valty) <- lift $ check ctxt env guess
527 ns <- unify' ctxt env (valty, Just $ SourceTerm val')
528 (ty, Just ExpectedType)
530 let (uh, uns) = unified ps
531-- put (ps { unified = (uh, uns ++ ns) })
532 return $ Bind x (Guess ty val) sc
533complete_fill ctxt env t = fail $ "Can't complete fill at " ++ show t
535-- When solving something in the 'dont unify' set, we should check
536-- that the guess we are solving it with unifies with the thing unification
537-- found for it, if anything.
540solve ctxt env (Bind x (Guess ty val) sc)
542 let (uh, uns) = unified ps
544 case lookup x (notunified ps) of
545 Just tm -> -- trace ("NEED MATCH: " ++ show (x, tm, val) ++ "\nIN " ++ show (pterm ps)) $
546 do match_unify' ctxt env (tm, Just InferredVal)
550 action (\ps -> ps { holes = traceWhen (unifylog ps) ("Dropping hole " ++ show x) $
552 solved = Just (x, val),
553 dontunify = filter (/= x) (dontunify ps),
554 notunified = updateNotunified [(x,val)]
556 recents = x : recents ps,
557 instances = instances ps \\ [x],
558 dotted = dropUnified dropdots (dotted ps) })
559 let (locked, did) = tryLock (holes ps \\ [x]) (updsubst x val sc) in
561 where dropUnified ddots [] = []
562 dropUnified ddots ((x, es) : ds)
563 | x `elem` ddots || any (\e -> e `elem` ddots) es
564 = dropUnified ddots ds
565 | otherwise = (x, es) : dropUnified ddots ds
567 tryLock :: [Name] -> Term -> (Term, Bool)
568 tryLock hs tm@(App Complete _ _) = (tm, True)
569 tryLock hs tm@(App s f a) =
570 let (f', fl) = tryLock hs f
571 (a', al) = tryLock hs a in
572 if fl && al then (App Complete f' a', True)
573 else (App s f' a', False)
574 tryLock hs t@(P _ n _) = (t, not $ n `elem` hs)
575 tryLock hs t@(Bind n (Hole _) sc) = (t, False)
576 tryLock hs t@(Bind n (Guess _ _) sc) = (t, False)
577 tryLock hs t@(Bind n (Let ty val) sc)
578 = let (ty', tyl) = tryLock hs ty
579 (val', vall) = tryLock hs val
580 (sc', scl) = tryLock hs sc in
581 (Bind n (Let ty' val') sc', tyl && vall && scl)
582 tryLock hs t@(Bind n b sc)
583 = let (bt', btl) = tryLock hs (binderTy b)
584 (val', vall) = tryLock hs val
585 (sc', scl) = tryLock hs sc in
586 (Bind n (b { binderTy = bt' }) sc', btl && scl)
587 tryLock hs t = (t, True)
589solve _ _ h@(Bind x t sc)
591 case findType x sc of
592 Just t -> lift $ tfail (CantInferType (show t))
593 _ -> lift $ tfail (IncompleteTerm h)
594 where findType x (Bind n (Let t v) sc)
595 = findType x v `mplus` findType x sc
596 findType x (Bind n t sc)
597 | P _ x' _ <- binderTy t, x == x' = Just n
598 | otherwise = findType x sc
599 findType x _ = Nothing
601introTy :: Raw -> Maybe Name -> RunTactic
602introTy ty mn ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =
603 do let n = case mn of
607 x@(Bind y (Pi _ s _) _) -> x
609 (tyv, tyt) <- lift $ check ctxt env ty
610-- ns <- lift $ unify ctxt env tyv t'
612 Bind y (Pi _ s _) t -> let t' = updsubst y (P Bound n s) t in
613 do ns <- unify' ctxt env (s, Nothing) (tyv, Nothing)
615 let (uh, uns) = unified ps
616-- put (ps { unified = (uh, uns ++ ns) })
617 return $ Bind n (Lam tyv) (Bind x (Hole t') (P Bound x t'))
618 _ -> lift $ tfail $ CantIntroduce t'
619introTy ty n ctxt env _ = fail "Can't introduce here."
621intro :: Maybe Name -> RunTactic
622intro mn ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =
623 do let n = case mn of
627 x@(Bind y (Pi _ s _) _) -> x
630 Bind y (Pi _ s _) t ->
631 -- It's important that this be subst and not updsubst,
632 -- because we want to substitute even in portions of
633 -- terms that we know do not contain holes.
634 let t' = subst y (P Bound n s) t in
635 return $ Bind n (Lam s) (Bind x (Hole t') (P Bound x t'))
636 _ -> lift $ tfail $ CantIntroduce t'
637intro n ctxt env _ = fail "Can't introduce here."
639forall :: Name -> Maybe ImplicitInfo -> Raw -> RunTactic
640forall n impl ty ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =
641 do (tyv, tyt) <- lift $ check ctxt env ty
642 unify' ctxt env (tyt, Nothing) (TType (UVar 0), Nothing)
643 unify' ctxt env (t, Nothing) (TType (UVar 0), Nothing)
644 return $ Bind n (Pi impl tyv (TType (UVar 0))) (Bind x (Hole t) (P Bound x t))
645forall n impl ty ctxt env _ = fail "Can't pi bind here"
647patvar :: Name -> RunTactic
648patvar n ctxt env (Bind x (Hole t) sc) =
649 do action (\ps -> ps { holes = traceWhen (unifylog ps) ("Dropping pattern hole " ++ show x) $
651 solved = Just (x, P Bound n t),
652 dontunify = filter (/=x) (dontunify ps),
653 notunified = updateNotunified [(x,P Bound n t)]
655 injective = addInj n x (injective ps)
657 return $ Bind n (PVar t) (updsubst x (P Bound n t) sc)
658 where addInj n x ps | x `elem` ps = n : ps
660patvar n ctxt env tm = fail $ "Can't add pattern var at " ++ show tm
662letbind :: Name -> Raw -> Raw -> RunTactic
663letbind n ty val ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =
664 do (tyv, tyt) <- lift $ check ctxt env ty
665 (valv, valt) <- lift $ check ctxt env val
666 lift $ isType ctxt env tyt
667 return $ Bind n (Let tyv valv) (Bind x (Hole t) (P Bound x t))
668letbind n ty val ctxt env _ = fail "Can't let bind here"
670expandLet :: Name -> Term -> RunTactic
671expandLet n v ctxt env tm =
672 return $ updsubst n v tm
674rewrite :: Raw -> RunTactic
675rewrite tm ctxt env (Bind x (Hole t) xp@(P _ x' _)) | x == x' =
676 do (tmv, tmt) <- lift $ check ctxt env tm
677 let tmt' = normalise ctxt env tmt
679 (P _ (UN q) _, [lt,rt,l,r]) | q == txt "=" ->
680 do let p = Bind rname (Lam lt) (mkP (P Bound rname lt) r l t)
681 let newt = mkP l r l t
682 let sc = forget $ (Bind x (Hole newt)
683 (mkApp (P Ref (sUN "replace") (TType (UVal 0)))
684 [lt, l, r, p, tmv, xp]))
685 (scv, sct) <- lift $ check ctxt env sc
687 _ -> lift $ tfail (NotEquality tmv tmt')
688 where rname = sMN 0 "replaced"
689rewrite _ _ _ _ = fail "Can't rewrite here"
691-- To make the P for rewrite, replace syntactic occurrences of l in ty with
692-- an x, and put \x : lt in front
693mkP :: TT Name -> TT Name -> TT Name -> TT Name -> TT Name
694mkP lt l r ty | l == ty = lt
695mkP lt l r (App s f a) = let f' = if (r /= f) then mkP lt l r f else f
696 a' = if (r /= a) then mkP lt l r a else a in
698mkP lt l r (Bind n b sc)
700 sc' = if (r /= sc) then mkP lt l r sc else sc in
702 where mkPB (Let t v) = let t' = if (r /= t) then mkP lt l r t else t
703 v' = if (r /= v) then mkP lt l r v else v in
705 mkPB b = let ty = binderTy b
706 ty' = if (r /= ty) then mkP lt l r ty else ty in
710casetac :: Raw -> Bool -> RunTactic
711casetac tm induction ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' = do
712 (tmv, tmt) <- lift $ check ctxt env tm
713 let tmt' = normalise ctxt env tmt
714 let (tacn, tacstr, tactt) = if induction
715 then (ElimN, "eliminator", "Induction")
716 else (CaseN, "case analysis", "Case analysis")
718 (P _ tnm _, tyargs) -> do
719 case lookupTy (SN (tacn tnm)) ctxt of
721 param_pos <- case lookupMetaInformation tnm ctxt of
722 [DataMI param_pos] -> return param_pos
723 m | length tyargs > 0 -> fail $ "Invalid meta information for " ++ show tnm ++ " where the metainformation is " ++ show m ++ " and definition is" ++ show (lookupDef tnm ctxt)
725 let (params, indicies) = splitTyArgs param_pos tyargs
726 let args = getArgTys elimTy
727 let pmargs = take (length params) args
728 let args' = drop (length params) args
729 let propTy = head args'
730 let restargs = init $ tail args'
731 let consargs = take (length restargs - length indicies) $ restargs
732 let indxargs = drop (length restargs - length indicies) $ restargs
733 let scr = last $ tail args'
734 let indxnames = makeIndexNames indicies
735 currentNames <- query $ allTTNames . getProofTerm . pterm
736 let tmnm = case tm of
737 Var nm -> uniqueNameCtxt ctxt nm currentNames
738 _ -> uniqueNameCtxt ctxt (sMN 0 "iv") currentNames
739 let tmvar = P Bound tmnm tmt'
740 prop <- replaceIndicies indxnames indicies $ Bind tmnm (Lam tmt') (mkP tmvar tmv tmvar t)
741 consargs' <- query (\ps -> map (flip (uniqueNameCtxt (context ps)) (holes ps ++ allTTNames (getProofTerm (pterm ps))) *** uniqueBindersCtxt (context ps) (holes ps ++ allTTNames (getProofTerm (pterm ps)))) consargs)
742 let res = flip (foldr substV) params $ (substV prop $ bindConsArgs consargs' (mkApp (P Ref (SN (tacn tnm)) (TType (UVal 0)))
743 (params ++ [prop] ++ map makeConsArg consargs' ++ indicies ++ [tmv])))
744 action (\ps -> ps {holes = holes ps \\ [x],
745 recents = x : recents ps })
746 mapM_ addConsHole (reverse consargs')
747 let res' = forget $ res
748 (scv, sct) <- lift $ check ctxt env res'
749 let (scv', _) = specialise ctxt env [] scv
751 [] -> lift $ tfail $ NoEliminator tacstr tmt'
752 xs -> lift $ tfail $ Msg $ "Multiple definitions found when searching for " ++ tacstr ++ "of " ++ show tnm
753 _ -> lift $ tfail $ NoEliminator (if induction then "induction" else "case analysis")
755 where scname = sMN 0 "scarg"
756 makeConsArg (nm, ty) = P Bound nm ty
757 bindConsArgs ((nm, ty):args) v = Bind nm (Hole ty) $ bindConsArgs args v
758 bindConsArgs [] v = v
759 addConsHole (nm, ty) =
760 action (\ps -> ps { holes = nm : holes ps })
761 splitTyArgs param_pos tyargs =
762 let (params, indicies) = partition (flip elem param_pos . fst) . zip [0..] $ tyargs
763 in (map snd params, map snd indicies)
764 makeIndexNames = foldr (\_ nms -> (uniqueNameCtxt ctxt (sMN 0 "idx") nms):nms) []
765 replaceIndicies idnms idxs prop = foldM (\t (idnm, idx) -> do (idxv, idxt) <- lift $ check ctxt env (forget idx)
766 let var = P Bound idnm idxt
767 return $ Bind idnm (Lam idxt) (mkP var idxv var t)) prop $ zip idnms idxs
768casetac tm induction ctxt env _ = fail $ "Can't do " ++ (if induction then "induction" else "case analysis") ++ " here"
771equiv :: Raw -> RunTactic
772equiv tm ctxt env (Bind x (Hole t) sc) =
773 do (tmv, tmt) <- lift $ check ctxt env tm
774 lift $ converts ctxt env tmv t
775 return $ Bind x (Hole tmv) sc
776equiv tm ctxt env _ = fail "Can't equiv here"
778patbind :: Name -> RunTactic
779patbind n ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =
780 do let t' = case t of
781 x@(Bind y (PVTy s) t) -> x
784 Bind y (PVTy s) t -> let t' = updsubst y (P Bound n s) t in
785 return $ Bind n (PVar s) (Bind x (Hole t') (P Bound x t'))
786 _ -> fail "Nothing to pattern bind"
787patbind n ctxt env _ = fail "Can't pattern bind here"
790compute ctxt env (Bind x (Hole ty) sc) =
791 do return $ Bind x (Hole (normalise ctxt env ty)) sc
792compute ctxt env t = return t
794hnf_compute :: RunTactic
795hnf_compute ctxt env (Bind x (Hole ty) sc) =
796 do let ty' = hnf ctxt env ty in
797-- trace ("HNF " ++ show (ty, ty')) $
798 return $ Bind x (Hole ty') sc
799hnf_compute ctxt env t = return t
801-- reduce let bindings only
803simplify ctxt env (Bind x (Hole ty) sc) =
804 do return $ Bind x (Hole (fst (specialise ctxt env [] ty))) sc
805simplify ctxt env t = return t
807check_in :: Raw -> RunTactic
808check_in t ctxt env tm =
809 do (val, valty) <- lift $ check ctxt env t
810 addLog (showEnv env val ++ " : " ++ showEnv env valty)
813eval_in :: Raw -> RunTactic
814eval_in t ctxt env tm =
815 do (val, valty) <- lift $ check ctxt env t
816 let val' = normalise ctxt env val
817 let valty' = normalise ctxt env valty
818 addLog (showEnv env val ++ " : " ++
820-- " in " ++ show env ++
822 showEnv env val' ++ " : " ++
826start_unify :: Name -> RunTactic
827start_unify n ctxt env tm = do -- action (\ps -> ps { unified = (n, []) })
830tmap f (a, b, c) = (f a, b, c)
832solve_unified :: RunTactic
833solve_unified ctxt env tm =
835 let (_, ns) = unified ps
836 let unify = dropGiven (dontunify ps) ns (holes ps)
837 action (\ps -> ps { holes = traceWhen (unifylog ps) ("Dropping holes " ++ show (map fst unify)) $
838 holes ps \\ map fst unify,
839 recents = recents ps ++ map fst unify })
840 action (\ps -> ps { pterm = updateSolved unify (pterm ps) })
841 return (updateSolvedTerm unify tm)
843dropGiven du [] hs = []
844dropGiven du ((n, P Bound t ty) : us) hs
845 | n `elem` du && not (t `elem` du)
846 && n `elem` hs && t `elem` hs
847 = (t, P Bound n ty) : dropGiven du us hs
848dropGiven du (u@(n, _) : us) hs
849 | n `elem` du = dropGiven du us hs
850-- dropGiven du (u@(_, P a n ty) : us) | n `elem` du = dropGiven du us
851dropGiven du (u : us) hs = u : dropGiven du us hs
853keepGiven du [] hs = []
854keepGiven du ((n, P Bound t ty) : us) hs
855 | n `elem` du && not (t `elem` du)
856 && n `elem` hs && t `elem` hs
858keepGiven du (u@(n, _) : us) hs
859 | n `elem` du = u : keepGiven du us hs
860keepGiven du (u : us) hs = keepGiven du us hs
864updateEnv ns ((n, b) : env)
865 = (n, fmap (updateSolvedTerm ns) b) : updateEnv ns env
867updateProv ns (SourceTerm t) = SourceTerm $ updateSolvedTerm ns t
870updateError [] err = err
871updateError ns (At f e) = At f (updateError ns e)
872updateError ns (Elaborating s n e) = Elaborating s n (updateError ns e)
873updateError ns (ElaboratingArg f a env e)
874 = ElaboratingArg f a env (updateError ns e)
875updateError ns (CantUnify b (l,lp) (r,rp) e xs sc)
876 = CantUnify b (updateSolvedTerm ns l, fmap (updateProv ns) lp)
877 (updateSolvedTerm ns r, fmap (updateProv ns) rp) (updateError ns e) xs sc
881updateRes ns ((x, t) : ts) = (x, updateSolvedTerm ns t) : updateRes ns ts
883solveInProblems x val [] = []
884solveInProblems x val ((l, r, env, err) : ps)
885 = ((psubst x val l, psubst x val r,
886 updateEnv [(x, val)] env, err) : solveInProblems x val ps)
888mergeNotunified :: Env -> [Name] -> [(Name, Term)] -> ([(Name, Term)], Fails)
889mergeNotunified env holes ns = mnu ns [] [] where
890 mnu [] ns_acc ps_acc = (reverse ns_acc, reverse ps_acc)
891 mnu ((n, t):ns) ns_acc ps_acc
892 | Just t' <- lookup n ns, t /= t'
893 = mnu ns ((n,t') : ns_acc)
894 ((t,t',True, env,CantUnify True (t, Nothing) (t', Nothing) (Msg "") [] 0, [],Match) : ps_acc)
895 | otherwise = mnu ns ((n,t) : ns_acc) ps_acc
897updateNotunified [] nu = nu
898updateNotunified ns nu = up nu where
900 up ((n, t) : nus) = let t' = updateSolvedTerm ns t in
903getProvenance :: Err -> (Maybe Provenance, Maybe Provenance)
904getProvenance (CantUnify _ (_, lp) (_, rp) _ _ _) = (lp, rp)
905getProvenance _ = (Nothing, Nothing)
907setReady (x, y, _, env, err, c, at) = (x, y, True, env, err, c, at)
909updateProblems :: ProofState -> [(Name, TT Name)] -> Fails
910 -> ([(Name, TT Name)], Fails)
911-- updateProblems ctxt [] ps inj holes = ([], ps)
912updateProblems ps updates probs = rec 10 updates probs
914 -- keep trying if we make progress, but not too many times...
915 rec 0 us fs = (us, fs)
916 rec n us fs = case up us [] fs of
918 res@(us', _) | length us' == length us -> res
919 (us', fs') -> rec (n - 1) us' fs'
925 usupp = map fst (notunified ps)
928 up ns acc [] = (ns, map (updateNs ns) (reverse acc))
929 up ns acc (prob@(x, y, ready, env, err, while, um) : ps) =
930 let (x', newx) = updateSolvedTerm' ns x
931 (y', newy) = updateSolvedTerm' ns y
932 (lp, rp) = getProvenance err
933 err' = updateError ns err
934 env' = updateEnv ns env in
935 if newx || newy || ready ||
936 any (\n -> n `elem` inj) (refsIn x ++ refsIn y) then
937 case unify ctxt env' (x', lp) (y', rp) inj hs usupp while of
938 OK (v, []) -> traceWhen ulog ("DID " ++ show (x',y',ready,v,dont)) $
939 let v' = filter (\(n, _) -> n `notElem` dont) v in
941 e -> -- trace ("FAILED " ++ show (x',y',ready,e)) $
942 up ns ((x',y',False,env',err',while,um) : acc) ps
943 else -- trace ("SKIPPING " ++ show (x,y,ready)) $
944 up ns ((x',y', False, env',err', while, um) : acc) ps
946 updateNs ns (x, y, t, env, err, fc, fa)
947 = let (x', newx) = updateSolvedTerm' ns x
948 (y', newy) = updateSolvedTerm' ns y in
949 (x', y', newx || newy,
950 updateEnv ns env, updateError ns err, fc, fa)
952-- attempt to solve remaining problems with match_unify
953matchProblems :: Bool -> ProofState -> [(Name, TT Name)] -> Fails
954 -> ([(Name, TT Name)], Fails)
955matchProblems all ps updates probs = up updates probs where
961 up ns ((x, y, ready, env, err, while, um) : ps)
962 | all || um == Match =
963 let x' = updateSolvedTerm ns x
964 y' = updateSolvedTerm ns y
965 (lp, rp) = getProvenance err
966 err' = updateError ns err
967 env' = updateEnv ns env in
968 case match_unify ctxt env' (x', lp) (y', rp) inj hs while of
969 OK v -> -- trace ("Added " ++ show v ++ " from " ++ show (x', y')) $
971 _ -> let (ns', ps') = up ns ps in
972 (ns', (x', y', True, env', err', while, um) : ps')
973 up ns (p : ps) = let (ns', ps') = up ns ps in
976processTactic :: Tactic -> ProofState -> TC (ProofState, String)
977processTactic QED ps = case holes ps of
978 [] -> do let tm = {- normalise (context ps) [] -} getProofTerm (pterm ps)
979 (tm', ty', _) <- recheck (context ps) [] (forget tm) tm
980 return (ps { done = True, pterm = mkProofTerm tm' },
981 "Proof complete: " ++ showEnv [] tm')
982 _ -> fail "Still holes to fill."
983processTactic ProofState ps = return (ps, showEnv [] (getProofTerm (pterm ps)))
984processTactic Undo ps = case previous ps of
985 Nothing -> Error . Msg $ "Nothing to undo."
986 Just pold -> return (pold, "")
987processTactic EndUnify ps
988 = let (h, ns_in) = unified ps
989 ns = dropGiven (dontunify ps) ns_in (holes ps)
990 ns' = map (\ (n, t) -> (n, updateSolvedTerm ns t)) ns
991 (ns'', probs') = updateProblems ps ns' (problems ps)
992 tm' = updateSolved ns'' (pterm ps) in
993 traceWhen (unifylog ps) ("(EndUnify) Dropping holes: " ++ show (map fst ns'')) $
994 return (ps { pterm = tm',
997 notunified = updateNotunified ns'' (notunified ps),
998 recents = recents ps ++ map fst ns'',
999 holes = holes ps \\ map fst ns'' }, "")
1000processTactic UnifyAll ps
1001 = let tm' = updateSolved (notunified ps) (pterm ps) in
1002 return (ps { pterm = tm',
1004 recents = recents ps ++ map fst (notunified ps),
1005 holes = holes ps \\ map fst (notunified ps) }, "")
1006processTactic (Reorder n) ps
1007 = do ps' <- execStateT (tactic (Just n) reorder_claims) ps
1008 return (ps' { previous = Just ps, plog = "" }, plog ps')
1009processTactic (ComputeLet n) ps
1010 = return (ps { pterm = mkProofTerm $
1011 computeLet (context ps) n
1012 (getProofTerm (pterm ps)) }, "")
1013processTactic UnifyProblems ps
1014 = do let (ns', probs') = updateProblems ps [] (map setReady (problems ps))
1015 pterm' = updateSolved ns' (pterm ps)
1016 traceWhen (unifylog ps) ("(UnifyProblems) Dropping holes: " ++ show (map fst ns')) $
1017 return (ps { pterm = pterm', solved = Nothing, problems = probs',
1018 previous = Just ps, plog = "",
1019 notunified = updateNotunified ns' (notunified ps),
1020 recents = recents ps ++ map fst ns',
1021 dotted = filter (notIn ns') (dotted ps),
1022 holes = holes ps \\ (map fst ns') }, plog ps)
1023 where notIn ns (h, _) = h `notElem` map fst ns
1024processTactic (MatchProblems all) ps
1025 = do let (ns', probs') = matchProblems all ps [] (map setReady (problems ps))
1026 (ns'', probs'') = matchProblems all ps ns' probs'
1027 pterm' = orderUpdateSolved ns'' (resetProofTerm (pterm ps))
1028 traceWhen (unifylog ps) ("(MatchProblems) Dropping holes: " ++ show ns'') $
1029 return (ps { pterm = pterm', solved = Nothing, problems = probs'',
1030 previous = Just ps, plog = "",
1031 notunified = updateNotunified ns'' (notunified ps),
1032 recents = recents ps ++ map fst ns'',
1033 holes = holes ps \\ (map fst ns'') }, plog ps)
1035 orderUpdateSolved [] t = t
1036 orderUpdateSolved (n : ns) t = orderUpdateSolved ns (updateSolved [n] t)
1040 Focus _ -> return (ps, "") -- harmless to refocus when done, since
1041 -- 'focus' doesn't fail
1042 _ -> fail $ "Nothing to fill in."
1043 (h:_) -> do ps' <- execStateT (process t h) ps
1045 = case solved ps' of
1046 Just s -> traceWhen (unifylog ps)
1047 ("SOLVED " ++ show s ++ " " ++ show (dontunify ps')) $
1048 updateProblems ps' [s] (problems ps')
1049 _ -> ([], problems ps')
1050 -- rechecking problems may find more solutions, so
1052 let ns' = dropGiven (dontunify ps') ns_in (holes ps')
1053 let pterm'' = updateSolved ns' (pterm ps')
1054 traceWhen (unifylog ps)
1055 ("Updated problems after solve " ++ qshow probs' ++ "\n" ++
1056 "(Toplevel) Dropping holes: " ++ show (map fst ns') ++ "\n" ++
1057 "Holes were: " ++ show (holes ps')) $
1058 return (ps' { pterm = pterm'',
1061 notunified = updateNotunified ns' (notunified ps'),
1062 previous = Just ps, plog = "",
1063 recents = recents ps' ++ map fst ns',
1064 holes = holes ps' \\ (map fst ns')
1067process :: Tactic -> Name -> StateT TState TC ()
1070 let (h, _) = unified ps
1071 tactic (Just h) solve_unified
1072process t h = tactic (Just h) (mktac t)
1073 where mktac Attack = attack
1074 mktac (Claim n r) = claim n r
1075 mktac (ClaimFn n bn r) = claimFn n bn r
1076 mktac (Exact r) = exact r
1077 mktac (Fill r) = fill r
1078 mktac (MatchFill r) = match_fill r
1079 mktac (PrepFill n ns) = prep_fill n ns
1080 mktac CompleteFill = complete_fill
1082 mktac (StartUnify n) = start_unify n
1083 mktac Compute = compute
1084 mktac Simplify = Idris.Core.ProofState.simplify
1085 mktac HNF_Compute = hnf_compute
1086 mktac (Intro n) = intro n
1087 mktac (IntroTy ty n) = introTy ty n
1088 mktac (Forall n i t) = forall n i t
1089 mktac (LetBind n t v) = letbind n t v
1090 mktac (ExpandLet n b) = expandLet n b
1091 mktac (Rewrite t) = rewrite t
1092 mktac (Induction t) = casetac t True
1093 mktac (CaseTac t) = casetac t False
1094 mktac (Equiv t) = equiv t
1095 mktac (PatVar n) = patvar n
1096 mktac (PatBind n) = patbind n
1097 mktac (CheckIn r) = check_in r
1098 mktac (EvalIn r) = eval_in r
1099 mktac (Focus n) = focus n
1100 mktac (Defer ns n) = defer ns n
1101 mktac (DeferType n t a) = deferType n t a
1102 mktac (Instance n) = instanceArg n
1103 mktac (AutoArg n) = autoArg n
1104 mktac (SetInjective n) = setinj n
1105 mktac (MoveLast n) = movelast n
1106 mktac (UnifyGoal r) = unifyGoal r
keysesc to close
- j k
- move down, up
- enter
- open
- esc
- back, or up a level
- 1 2 3 4
- readme, files, commits, refs
- /
- filter
- y
- copy the clone command
- c
- compare the chosen commit with another (or shift-click both)
- ?
- show or hide this list