on b0cb4e2 help sign in
Idris-dev/src/Idris/Core/ProofState.hs
1015 lines 44 kB history raw
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) where
11import Idris.Core.Typecheck
12import Idris.Core.Evaluate
13import Idris.Core.TT
14import Idris.Core.Unify
16import Control.Monad.State.Strict
17import Control.Applicative hiding (empty)
18import Control.Arrow ((***))
19import Data.List
20import Debug.Trace
22import Util.Pretty hiding (fill)
24data ProofState = PS { thname :: Name,
25 holes :: [Name], -- holes still to be solved
26 usedns :: [Name], -- used names, don't use again
27 nextname :: Int, -- name supply
28 pterm :: Term, -- current proof term
29 ptype :: Type, -- original goal
30 dontunify :: [Name], -- explicitly given by programmer, leave it
31 unified :: (Name, [(Name, Term)]),
32 notunified :: [(Name, Term)],
33 solved :: Maybe (Name, Term),
34 problems :: Fails,
35 injective :: [Name],
36 deferred :: [Name], -- names we'll need to define
37 instances :: [Name], -- instance arguments (for type classes)
38 previous :: Maybe ProofState, -- for undo
39 context :: Context,
40 plog :: String,
41 unifylog :: Bool,
42 done :: Bool,
43 while_elaborating :: [FailContext]
44 }
46data Goal = GD { premises :: Env,
47 goalType :: Binder Term
48 }
50data Tactic = Attack
51 | Claim Name Raw
52 | Reorder Name
53 | Exact Raw
54 | Fill Raw
55 | MatchFill Raw
56 | PrepFill Name [Name]
57 | CompleteFill
58 | Regret
59 | Solve
60 | StartUnify Name
61 | EndUnify
62 | UnifyAll
63 | Compute
64 | ComputeLet Name
65 | Simplify
66 | HNF_Compute
67 | EvalIn Raw
68 | CheckIn Raw
69 | Intro (Maybe Name)
70 | IntroTy Raw (Maybe Name)
71 | Forall Name Raw
72 | LetBind Name Raw Raw
73 | ExpandLet Name Term
74 | Rewrite Raw
75 | Induction Raw
76 | CaseTac Raw
77 | Equiv Raw
78 | PatVar Name
79 | PatBind Name
80 | Focus Name
81 | Defer Name
82 | DeferType Name Raw [Name]
83 | Instance Name
84 | SetInjective Name
85 | MoveLast Name
86 | MatchProblems Bool
87 | UnifyProblems
88 | ProofState
89 | Undo
90 | QED
91 deriving Show
93-- Some utilites on proof and tactic states
95instance Show ProofState where
96 show (PS nm [] _ _ tm _ _ _ _ _ _ _ _ _ _ _ _ _ _ _)
97 = show nm ++ ": no more goals"
98 show (PS nm (h:hs) _ _ tm _ _ _ _ _ _ _ i _ _ ctxt _ _ _ _)
99 = let OK g = goal (Just h) tm
100 wkenv = premises g in
101 "Other goals: " ++ show hs ++ "\n" ++
102 showPs wkenv (reverse wkenv) ++ "\n" ++
103 "-------------------------------- (" ++ show nm ++
104 ") -------\n " ++
105 show h ++ " : " ++ showG wkenv (goalType g) ++ "\n"
106 where showPs env [] = ""
107 showPs env ((n, Let t v):bs)
108 = " " ++ show n ++ " : " ++
109 showEnv env ({- normalise ctxt env -} t) ++ " = " ++
110 showEnv env ({- normalise ctxt env -} v) ++
111 "\n" ++ showPs env bs
112 showPs env ((n, b):bs)
113 = " " ++ show n ++ " : " ++
114 showEnv env ({- normalise ctxt env -} (binderTy b)) ++
115 "\n" ++ showPs env bs
116 showG ps (Guess t v) = showEnv ps ({- normalise ctxt ps -} t) ++
117 " =?= " ++ showEnv ps v
118 showG ps b = showEnv ps (binderTy b)
120instance Pretty ProofState OutputAnnotation where
121 pretty (PS nm [] _ _ trm _ _ _ _ _ _ _ _ _ _ _ _ _ _ _) =
122 pretty nm <+> colon <+> text " no more goals."
123 pretty p@(PS nm (h:hs) _ _ tm _ _ _ _ _ _ _ i _ _ ctxt _ _ _ _) =
124 let OK g = goal (Just h) tm in
125 let wkEnv = premises g in
126 text "Other goals" <+> colon <+> pretty hs <+>
127 prettyPs wkEnv (reverse wkEnv) <+>
128 text "---------- " <+> text "Focussing on" <> colon <+> pretty nm <+> text " ----------" <+>
129 pretty h <+> colon <+> prettyGoal wkEnv (goalType g)
130 where
131 prettyGoal ps (Guess t v) =
132 prettyEnv ps t <+> text "=?=" <+> prettyEnv ps v
133 prettyGoal ps b = prettyEnv ps $ binderTy b
135 prettyPs env [] = empty
136 prettyPs env ((n, Let t v):bs) =
137 nest nestingSize (pretty n <+> colon <+>
138 prettyEnv env t <+> text "=" <+> prettyEnv env v <+>
139 nest nestingSize (prettyPs env bs))
140 prettyPs env ((n, b):bs) =
141 nest nestingSize (pretty n <+> colon <+> prettyEnv env (binderTy b) <+>
142 nest nestingSize (prettyPs env bs))
144same Nothing n = True
145same (Just x) n = x == n
147hole (Hole _) = True
148hole (Guess _ _) = True
149hole _ = False
151holeName i = sMN i "hole"
153qshow :: Fails -> String
154qshow fs = show (map (\ (x, y, _, _, _, t) -> (t, x, y)) fs)
156match_unify' :: Context -> Env -> TT Name -> TT Name ->
157 StateT TState TC [(Name, TT Name)]
158match_unify' ctxt env topx topy =
159 do ps <- get
160 let while = while_elaborating ps
161 let dont = dontunify ps
162 let inj = injective ps
163 traceWhen (unifylog ps)
164 ("Matching " ++ show (topx, topy) ++
165 " in " ++ show env ++
166 "\nHoles: " ++ show (holes ps)
167 ++ "\n"
168 ++ "\n" ++ show (pterm ps) ++ "\n\n"
169 ) $
170 case match_unify ctxt env topx topy inj (holes ps) while of
171 OK u -> do let (h, ns) = unified ps
172 put (ps { unified = (h, u ++ ns) })
173 return u
174 Error e -> do put (ps { problems = (topx, topy, env, e, while, Match) :
175 problems ps })
176 return []
177-- traceWhen (unifylog ps)
178-- ("Matched " ++ show (topx, topy) ++ " without " ++ show dont ++
179-- "\nSolved: " ++ show u
180-- ++ "\nCurrent problems:\n" ++ qshow (problems ps)
181-- -- ++ show (pterm ps)
182-- ++ "\n----------") $
184mergeSolutions :: Env -> [(Name, TT Name)] -> StateT TState TC [(Name, TT Name)]
185mergeSolutions env ns = merge [] ns
186 where
187 merge acc [] = return (reverse acc)
188 merge acc ((n, t) : ns)
189 | Just t' <- lookup n ns
190 = do ps <- get
191 let probs = problems ps
192 put (ps { problems = probs ++ [(t,t',env,Msg "New problem",
193 [], Unify)] })
194 merge acc ns
195 | otherwise = merge ((n, t): acc) ns
197unify' :: Context -> Env -> TT Name -> TT Name ->
198 StateT TState TC [(Name, TT Name)]
199unify' ctxt env topx topy =
200 do ps <- get
201 let while = while_elaborating ps
202 let dont = dontunify ps
203 let inj = injective ps
204 (u, fails) <- traceWhen (unifylog ps)
205 ("Trying " ++ show (topx, topy) ++
206 "\nNormalised " ++ show (normalise ctxt env topx,
207 normalise ctxt env topy) ++
208 " in " ++ show env ++
209 "\nHoles: " ++ show (holes ps)
210 ++ "\nInjective: " ++ show (injective ps)
211 ++ "\n") $
212 lift $ unify ctxt env topx topy inj (holes ps) while
213 let notu = filter (\ (n, t) -> case t of
214 P _ _ _ -> False
215 _ -> n `elem` dont) u
216 traceWhen (unifylog ps)
217 ("Unified " ++ show (topx, topy) ++ " without " ++ show dont ++
218 "\nSolved: " ++ show u ++ "\nNew problems: " ++ qshow fails
219 ++ "\nNot unified:\n" ++ show (notunified ps)
220 ++ "\nCurrent problems:\n" ++ qshow (problems ps)
221-- ++ show (pterm ps)
222 ++ "\n----------") $
223 do let (h, ns) = unified ps
224 -- if a metavar has multiple solutions, make a new unification
225 -- problem for each.
226 uns <- mergeSolutions env (u ++ ns)
227 ps <- get
228 let (ns', probs') = updateProblems (context ps) uns
229 (fails ++ problems ps)
230 (injective ps)
231 (holes ps)
232 let (notu', probs_notu) = mergeNotunified env (notu ++ notunified ps)
233 traceWhen (unifylog ps)
234 ("Now solved: " ++ show ns') $
235 put (ps { problems = probs' ++ probs_notu,
236 unified = (h, ns'),
237 injective = updateInj u (injective ps),
238 notunified = notu' })
239 return u
240 where updateInj ((n, a) : us) inj
241 | (P _ n' _, _) <- unApply a,
242 n `elem` inj = updateInj us (n':inj)
243 | (P _ n' _, _) <- unApply a,
244 n' `elem` inj = updateInj us (n:inj)
245 updateInj (_ : us) inj = updateInj us inj
246 updateInj [] inj = inj
248nowElaboratingPS :: FC -> Name -> Name -> ProofState -> ProofState
249nowElaboratingPS fc f arg ps = ps { while_elaborating = FailContext fc f arg : while_elaborating ps }
251dropUntil :: (a -> Bool) -> [a] -> [a]
252dropUntil p [] = []
253dropUntil p (x:xs) | p x = xs
254 | otherwise = dropUntil p xs
256doneElaboratingAppPS :: Name -> ProofState -> ProofState
257doneElaboratingAppPS f ps = let while = while_elaborating ps
258 while' = dropUntil (\ (FailContext _ f' _) -> f == f') while
259 in ps { while_elaborating = while' }
261doneElaboratingArgPS :: Name -> Name -> ProofState -> ProofState
262doneElaboratingArgPS f x ps = let while = while_elaborating ps
263 while' = dropUntil (\ (FailContext _ f' x') -> f == f' && x == x') while
264 in ps { while_elaborating = while' }
266getName :: Monad m => String -> StateT TState m Name
267getName tag = do ps <- get
268 let n = nextname ps
269 put (ps { nextname = n+1 })
270 return $ sMN n tag
272action :: Monad m => (ProofState -> ProofState) -> StateT TState m ()
273action a = do ps <- get
274 put (a ps)
276query :: Monad m => (ProofState -> r) -> StateT TState m r
277query q = do ps <- get
278 return $ q ps
280addLog :: Monad m => String -> StateT TState m ()
281addLog str = action (\ps -> ps { plog = plog ps ++ str ++ "\n" })
283newProof :: Name -> Context -> Type -> ProofState
284newProof n ctxt ty = let h = holeName 0
285 ty' = vToP ty in
286 PS n [h] [] 1 (Bind h (Hole ty')
287 (P Bound h ty')) ty [] (h, []) []
288 Nothing [] []
289 [] []
290 Nothing ctxt "" False False []
292type TState = ProofState -- [TacticAction])
293type RunTactic = Context -> Env -> Term -> StateT TState TC Term
294type Hole = Maybe Name -- Nothing = default hole, first in list in proof state
296envAtFocus :: ProofState -> TC Env
297envAtFocus ps
298 | not $ null (holes ps) = do g <- goal (Just (head (holes ps))) (pterm ps)
299 return (premises g)
300 | otherwise = fail "No holes"
302goalAtFocus :: ProofState -> TC (Binder Type)
303goalAtFocus ps
304 | not $ null (holes ps) = do g <- goal (Just (head (holes ps))) (pterm ps)
305 return (goalType g)
306 | otherwise = Error . Msg $ "No goal in " ++ show (holes ps) ++ show (pterm ps)
308goal :: Hole -> Term -> TC Goal
309goal h tm = g [] tm where
310 g env (Bind n b@(Guess _ _) sc)
311 | same h n = return $ GD env b
312 | otherwise
313 = gb env b `mplus` g ((n, b):env) sc
314 g env (Bind n b sc) | hole b && same h n = return $ GD env b
315 | otherwise
316 = g ((n, b):env) sc `mplus` gb env b
317 g env (App f a) = g env f `mplus` g env a
318 g env t = fail "Can't find hole"
320 gb env (Let t v) = g env v `mplus` g env t
321 gb env (Guess t v) = g env v `mplus` g env t
322 gb env t = g env (binderTy t)
324tactic :: Hole -> RunTactic -> StateT TState TC ()
325tactic h f = do ps <- get
326 (tm', _) <- atH (context ps) [] (pterm ps)
327 ps <- get -- might have changed while processing
328 put (ps { pterm = tm' })
329 where
330 updated o = do o' <- o
331 return (o', True)
333 ulift2 c env op a b
334 = do (b', u) <- atH c env b
335 if u then return (op a b', True)
336 else do (a', u) <- atH c env a
337 return (op a' b', u)
339 -- Search the things most likely to contain the binding first!
341 atH :: Context -> Env -> Term -> StateT TState TC (Term, Bool)
342 atH c env binder@(Bind n b@(Guess t v) sc)
343 | same h n = updated (f c env binder)
344 | otherwise
345 = do -- binder first
346 (b', u) <- ulift2 c env Guess t v
347 if u then return (Bind n b' sc, True)
348 else do (sc', u) <- atH c ((n, b) : env) sc
349 return (Bind n b' sc', u)
350 atH c env binder@(Bind n b sc)
351 | hole b && same h n = updated (f c env binder)
352 | otherwise -- scope first
353 = do (sc', u) <- atH c ((n, b) : env) sc
354 if u then return (Bind n b sc', True)
355 else do (b', u) <- atHb c env b
356 return (Bind n b' sc', u)
357 atH c env (App f a) = ulift2 c env App f a
358 atH c env t = return (t, False)
360 atHb c env (Let t v) = ulift2 c env Let t v
361 atHb c env (Guess t v) = ulift2 c env Guess t v
362 atHb c env t = do (ty', u) <- atH c env (binderTy t)
363 return (t { binderTy = ty' }, u)
365computeLet :: Context -> Name -> Term -> Term
366computeLet ctxt n tm = cl [] tm where
367 cl env (Bind n' (Let t v) sc)
368 | n' == n = let v' = normalise ctxt env v in
369 Bind n' (Let t v') sc
370 cl env (Bind n' b sc) = Bind n' (fmap (cl env) b) (cl ((n, b):env) sc)
371 cl env (App f a) = App (cl env f) (cl env a)
372 cl env t = t
374attack :: RunTactic
375attack ctxt env (Bind x (Hole t) sc)
376 = do h <- getName "hole"
377 action (\ps -> ps { holes = h : holes ps })
378 return $ Bind x (Guess t (newtm h)) sc
379 where
380 newtm h = Bind h (Hole t) (P Bound h t)
381attack ctxt env _ = fail "Not an attackable hole"
383claim :: Name -> Raw -> RunTactic
384claim n ty ctxt env t =
385 do (tyv, tyt) <- lift $ check ctxt env ty
386 lift $ isType ctxt env tyt
387 action (\ps -> let (g:gs) = holes ps in
388 ps { holes = g : n : gs } )
389 return $ Bind n (Hole tyv) t -- (weakenTm 1 t)
391reorder_claims :: RunTactic
392reorder_claims ctxt env t
393 = -- trace (showSep "\n" (map show (scvs t))) $
394 let (bs, sc) = scvs t []
395 newbs = reverse (sortB (reverse bs)) in
396 traceWhen (bs /= newbs) (show bs ++ "\n ==> \n" ++ show newbs) $
397 return (bindAll newbs sc)
398 where scvs (Bind n b@(Hole _) sc) acc = scvs sc ((n, b):acc)
399 scvs sc acc = (reverse acc, sc)
401 sortB :: [(Name, Binder (TT Name))] -> [(Name, Binder (TT Name))]
402 sortB [] = []
403 sortB (x:xs) | all (noOcc x) xs = x : sortB xs
404 | otherwise = sortB (insertB x xs)
406 insertB x [] = [x]
407 insertB x (y:ys) | all (noOcc x) (y:ys) = x : y : ys
408 | otherwise = y : insertB x ys
410 noOcc (n, _) (_, Let t v) = noOccurrence n t && noOccurrence n v
411 noOcc (n, _) (_, Guess t v) = noOccurrence n t && noOccurrence n v
412 noOcc (n, _) (_, b) = noOccurrence n (binderTy b)
414focus :: Name -> RunTactic
415focus n ctxt env t = do action (\ps -> let hs = holes ps in
416 if n `elem` hs
417 then ps { holes = n : (hs \\ [n]) }
418 else ps)
419 ps <- get
420 return t
422movelast :: Name -> RunTactic
423movelast n ctxt env t = do action (\ps -> let hs = holes ps in
424 if n `elem` hs
425 then ps { holes = (hs \\ [n]) ++ [n] }
426 else ps)
427 return t
429instanceArg :: Name -> RunTactic
430instanceArg n ctxt env (Bind x (Hole t) sc)
431 = do action (\ps -> let hs = holes ps
432 is = instances ps in
433 ps { holes = (hs \\ [x]) ++ [x],
434 instances = x:is })
435 return (Bind x (Hole t) sc)
437setinj :: Name -> RunTactic
438setinj n ctxt env (Bind x b sc)
439 = do action (\ps -> let is = injective ps in
440 ps { injective = n : is })
441 return (Bind x b sc)
443defer :: Name -> RunTactic
444defer n ctxt env (Bind x (Hole t) (P nt x' ty)) | x == x' =
445 do action (\ps -> let hs = holes ps in
446 ps { holes = hs \\ [x] })
447 return (Bind n (GHole (length env) (mkTy (reverse env) t))
448 (mkApp (P Ref n ty) (map getP (reverse env))))
449 where
450 mkTy [] t = t
451 mkTy ((n,b) : bs) t = Bind n (Pi (binderTy b)) (mkTy bs t)
453 getP (n, b) = P Bound n (binderTy b)
455-- as defer, but build the type and application explicitly
456deferType :: Name -> Raw -> [Name] -> RunTactic
457deferType n fty_in args ctxt env (Bind x (Hole t) (P nt x' ty)) | x == x' =
458 do (fty, _) <- lift $ check ctxt env fty_in
459 action (\ps -> let hs = holes ps
460 ds = deferred ps in
461 ps { holes = hs \\ [x],
462 deferred = n : ds })
463 return (Bind n (GHole 0 fty)
464 (mkApp (P Ref n ty) (map getP args)))
465 where
466 getP n = case lookup n env of
467 Just b -> P Bound n (binderTy b)
468 Nothing -> error ("deferType can't find " ++ show n)
470regret :: RunTactic
471regret ctxt env (Bind x (Hole t) sc) | noOccurrence x sc =
472 do action (\ps -> let hs = holes ps in
473 ps { holes = hs \\ [x] })
474 return sc
475regret ctxt env (Bind x (Hole t) _)
476 = fail $ show x ++ " : " ++ show t ++ " is not solved..."
478exact :: Raw -> RunTactic
479exact guess ctxt env (Bind x (Hole ty) sc) =
480 do (val, valty) <- lift $ check ctxt env guess
481 lift $ converts ctxt env valty ty
482 return $ Bind x (Guess ty val) sc
483exact _ _ _ _ = fail "Can't fill here."
485-- As exact, but attempts to solve other goals by unification
487fill :: Raw -> RunTactic
488fill guess ctxt env (Bind x (Hole ty) sc) =
489 do (val, valty) <- lift $ check ctxt env guess
490-- let valtyn = normalise ctxt env valty
491-- let tyn = normalise ctxt env ty
492 ns <- unify' ctxt env valty ty
493 ps <- get
494 let (uh, uns) = unified ps
495-- put (ps { unified = (uh, uns ++ ns) })
496-- addLog (show (uh, uns ++ ns))
497 return $ Bind x (Guess ty val) sc
498fill _ _ _ _ = fail "Can't fill here."
500-- As fill, but attempts to solve other goals by matching
502match_fill :: Raw -> RunTactic
503match_fill guess ctxt env (Bind x (Hole ty) sc) =
504 do (val, valty) <- lift $ check ctxt env guess
505-- let valtyn = normalise ctxt env valty
506-- let tyn = normalise ctxt env ty
507 ns <- match_unify' ctxt env valty ty
508 ps <- get
509 let (uh, uns) = unified ps
510-- put (ps { unified = (uh, uns ++ ns) })
511-- addLog (show (uh, uns ++ ns))
512 return $ Bind x (Guess ty val) sc
513match_fill _ _ _ _ = fail "Can't fill here."
515prep_fill :: Name -> [Name] -> RunTactic
516prep_fill f as ctxt env (Bind x (Hole ty) sc) =
517 do let val = mkApp (P Ref f Erased) (map (\n -> P Ref n Erased) as)
518 return $ Bind x (Guess ty val) sc
519prep_fill f as ctxt env t = fail $ "Can't prepare fill at " ++ show t
521complete_fill :: RunTactic
522complete_fill ctxt env (Bind x (Guess ty val) sc) =
523 do let guess = forget val
524 (val', valty) <- lift $ check ctxt env guess
525 ns <- unify' ctxt env valty ty
526 ps <- get
527 let (uh, uns) = unified ps
528-- put (ps { unified = (uh, uns ++ ns) })
529 return $ Bind x (Guess ty val) sc
530complete_fill ctxt env t = fail $ "Can't complete fill at " ++ show t
532-- When solving something in the 'dont unify' set, we should check
533-- that the guess we are solving it with unifies with the thing unification
534-- found for it, if anything.
536solve :: RunTactic
537solve ctxt env (Bind x (Guess ty val) sc)
538 = do ps <- get
539 let (uh, uns) = unified ps
540 case lookup x (notunified ps) of
541 Just tm -> -- trace ("NEED MATCH: " ++ show (tm, val)) $
542 match_unify' ctxt env tm val
543 _ -> return []
544 action (\ps -> ps { holes = holes ps \\ [x],
545 solved = Just (x, val),
546 notunified = updateNotunified [(x,val)]
547 (notunified ps),
548 instances = instances ps \\ [x] })
549 let tm' = subst x val sc in
550 return tm'
551solve _ _ h@(Bind x t sc)
552 = do ps <- get
553 case findType x sc of
554 Just t -> lift $ tfail (CantInferType (show t))
555 _ -> fail $ "Not a guess " ++ show h ++ "\n" ++ show (holes ps, pterm ps)
556 where findType x (Bind n (Let t v) sc)
557 = findType x v `mplus` findType x sc
558 findType x (Bind n t sc)
559 | P _ x' _ <- binderTy t, x == x' = Just n
560 | otherwise = findType x sc
561 findType x _ = Nothing
563introTy :: Raw -> Maybe Name -> RunTactic
564introTy ty mn ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =
565 do let n = case mn of
566 Just name -> name
567 Nothing -> x
568 let t' = case t of
569 x@(Bind y (Pi s) _) -> x
570 _ -> hnf ctxt env t
571 (tyv, tyt) <- lift $ check ctxt env ty
572-- ns <- lift $ unify ctxt env tyv t'
573 case t' of
574 Bind y (Pi s) t -> let t' = subst y (P Bound n s) t in
575 do ns <- unify' ctxt env s tyv
576 ps <- get
577 let (uh, uns) = unified ps
578-- put (ps { unified = (uh, uns ++ ns) })
579 return $ Bind n (Lam tyv) (Bind x (Hole t') (P Bound x t'))
580 _ -> lift $ tfail $ CantIntroduce t'
581introTy ty n ctxt env _ = fail "Can't introduce here."
583intro :: Maybe Name -> RunTactic
584intro mn ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =
585 do let n = case mn of
586 Just name -> name
587 Nothing -> x
588 let t' = case t of
589 x@(Bind y (Pi s) _) -> x
590 _ -> hnf ctxt env t
591 case t' of
592 Bind y (Pi s) t -> -- trace ("in type " ++ show t') $
593 let t' = subst y (P Bound n s) t in
594 return $ Bind n (Lam s) (Bind x (Hole t') (P Bound x t'))
595 _ -> lift $ tfail $ CantIntroduce t'
596intro n ctxt env _ = fail "Can't introduce here."
598forall :: Name -> Raw -> RunTactic
599forall n ty ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =
600 do (tyv, tyt) <- lift $ check ctxt env ty
601 unify' ctxt env tyt (TType (UVar 0))
602 unify' ctxt env t (TType (UVar 0))
603 return $ Bind n (Pi tyv) (Bind x (Hole t) (P Bound x t))
604forall n ty ctxt env _ = fail "Can't pi bind here"
606patvar :: Name -> RunTactic
607patvar n ctxt env (Bind x (Hole t) sc) =
608 do action (\ps -> ps { holes = holes ps \\ [x],
609 notunified = updateNotunified [(x,P Bound n t)]
610 (notunified ps),
611 injective = addInj n x (injective ps) })
612 return $ Bind n (PVar t) (subst x (P Bound n t) sc)
613 where addInj n x ps | x `elem` ps = n : ps
614 | otherwise = ps
615patvar n ctxt env tm = fail $ "Can't add pattern var at " ++ show tm
617letbind :: Name -> Raw -> Raw -> RunTactic
618letbind n ty val ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =
619 do (tyv, tyt) <- lift $ check ctxt env ty
620 (valv, valt) <- lift $ check ctxt env val
621 lift $ isType ctxt env tyt
622 return $ Bind n (Let tyv valv) (Bind x (Hole t) (P Bound x t))
623letbind n ty val ctxt env _ = fail "Can't let bind here"
625expandLet :: Name -> Term -> RunTactic
626expandLet n v ctxt env tm =
627 return $ subst n v tm
629rewrite :: Raw -> RunTactic
630rewrite tm ctxt env (Bind x (Hole t) xp@(P _ x' _)) | x == x' =
631 do (tmv, tmt) <- lift $ check ctxt env tm
632 let tmt' = normalise ctxt env tmt
633 case unApply tmt' of
634 (P _ (UN q) _, [lt,rt,l,r]) | q == txt "=" ->
635 do let p = Bind rname (Lam lt) (mkP (P Bound rname lt) r l t)
636 let newt = mkP l r l t
637 let sc = forget $ (Bind x (Hole newt)
638 (mkApp (P Ref (sUN "replace") (TType (UVal 0)))
639 [lt, l, r, p, tmv, xp]))
640 (scv, sct) <- lift $ check ctxt env sc
641 return scv
642 _ -> lift $ tfail (NotEquality tmv tmt')
643 where rname = sMN 0 "replaced"
644rewrite _ _ _ _ = fail "Can't rewrite here"
646-- To make the P for rewrite, replace syntactic occurrences of l in ty with
647-- an x, and put \x : lt in front
648mkP :: TT Name -> TT Name -> TT Name -> TT Name -> TT Name
649mkP lt l r ty | l == ty = lt
650mkP lt l r (App f a) = let f' = if (r /= f) then mkP lt l r f else f
651 a' = if (r /= a) then mkP lt l r a else a in
652 App f' a'
653mkP lt l r (Bind n b sc)
654 = let b' = mkPB b
655 sc' = if (r /= sc) then mkP lt l r sc else sc in
656 Bind n b' sc'
657 where mkPB (Let t v) = let t' = if (r /= t) then mkP lt l r t else t
658 v' = if (r /= v) then mkP lt l r v else v in
659 Let t' v'
660 mkPB b = let ty = binderTy b
661 ty' = if (r /= ty) then mkP lt l r ty else ty in
662 b { binderTy = ty' }
663mkP lt l r x = x
665casetac :: Raw -> Bool -> RunTactic
666casetac tm induction ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' = do
667 (tmv, tmt) <- lift $ check ctxt env tm
668 let tmt' = normalise ctxt env tmt
669 let (tacn, tacstr, tactt) = if induction
670 then (ElimN, "an eliminator", "induction")
671 else (CaseN, "a case function", "case analysis")
672 case unApply tmt' of
673 (P _ tnm _, tyargs) -> do
674 case lookupTy (SN (tacn tnm)) ctxt of
675 [elimTy] -> do
676 param_pos <- case lookupMetaInformation tnm ctxt of
677 [DataMI param_pos] -> return param_pos
678 m | length tyargs > 0 -> fail $ "Invalid meta information for " ++ show tnm ++ " where the metainformation is " ++ show m ++ " and definition is" ++ show (lookupDef tnm ctxt)
679 _ -> return []
680 let (params, indicies) = splitTyArgs param_pos tyargs
681 let args = getArgTys elimTy
682 let pmargs = take (length params) args
683 let args' = drop (length params) args
684 let propTy = head args'
685 let restargs = init $ tail args'
686 let consargs = take (length restargs - length indicies) $ restargs
687 let indxargs = drop (length restargs - length indicies) $ restargs
688 let scr = last $ tail args'
689 let indxnames = makeIndexNames indicies
690 currentNames <- query $ allTTNames . pterm
691 let tmnm = case tm of
692 Var nm -> uniqueNameCtxt ctxt nm currentNames
693 _ -> uniqueNameCtxt ctxt (sMN 0 "iv") currentNames
694 let tmvar = P Bound tmnm tmt'
695 prop <- replaceIndicies indxnames indicies $ Bind tmnm (Lam tmt') (mkP tmvar tmv tmvar t)
696 consargs' <- query (\ps -> map (flip (uniqueNameCtxt (context ps)) (holes ps ++ allTTNames (pterm ps)) *** uniqueBindersCtxt (context ps) (holes ps ++ allTTNames (pterm ps))) consargs)
697 let res = flip (foldr substV) params $ (substV prop $ bindConsArgs consargs' (mkApp (P Ref (SN (tacn tnm)) (TType (UVal 0)))
698 (params ++ [prop] ++ map makeConsArg consargs' ++ indicies ++ [tmv])))
699 action (\ps -> ps {holes = holes ps \\ [x]})
700 mapM_ addConsHole (reverse consargs')
701 let res' = forget $ res
702 (scv, sct) <- lift $ check ctxt env res'
703 let scv' = specialise ctxt env [] scv
704 return scv'
705 [] -> fail $ tactt ++ " needs " ++ tacstr ++ " for " ++ show tnm
706 xs -> fail $ "Multiple definitions found when searching for " ++ tacstr ++ "of " ++ show tnm
707 _ -> fail $ "Unkown type for " ++ if induction then "induction" else "case analysis"
708 where scname = sMN 0 "scarg"
709 makeConsArg (nm, ty) = P Bound nm ty
710 bindConsArgs ((nm, ty):args) v = Bind nm (Hole ty) $ bindConsArgs args v
711 bindConsArgs [] v = v
712 addConsHole (nm, ty) =
713 action (\ps -> ps { holes = nm : holes ps })
714 splitTyArgs param_pos tyargs =
715 let (params, indicies) = partition (flip elem param_pos . fst) . zip [0..] $ tyargs
716 in (map snd params, map snd indicies)
717 makeIndexNames = foldr (\_ nms -> (uniqueNameCtxt ctxt (sMN 0 "idx") nms):nms) []
718 replaceIndicies idnms idxs prop = foldM (\t (idnm, idx) -> do (idxv, idxt) <- lift $ check ctxt env (forget idx)
719 let var = P Bound idnm idxt
720 return $ Bind idnm (Lam idxt) (mkP var idxv var t)) prop $ zip idnms idxs
721induction tm induction ctxt env _ = do fail "Can't do induction here"
724equiv :: Raw -> RunTactic
725equiv tm ctxt env (Bind x (Hole t) sc) =
726 do (tmv, tmt) <- lift $ check ctxt env tm
727 lift $ converts ctxt env tmv t
728 return $ Bind x (Hole tmv) sc
729equiv tm ctxt env _ = fail "Can't equiv here"
731patbind :: Name -> RunTactic
732patbind n ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =
733 do let t' = case t of
734 x@(Bind y (PVTy s) t) -> x
735 _ -> hnf ctxt env t
736 case t' of
737 Bind y (PVTy s) t -> let t' = subst y (P Bound n s) t in
738 return $ Bind n (PVar s) (Bind x (Hole t') (P Bound x t'))
739 _ -> fail "Nothing to pattern bind"
740patbind n ctxt env _ = fail "Can't pattern bind here"
742compute :: RunTactic
743compute ctxt env (Bind x (Hole ty) sc) =
744 do return $ Bind x (Hole (normalise ctxt env ty)) sc
745compute ctxt env t = return t
747hnf_compute :: RunTactic
748hnf_compute ctxt env (Bind x (Hole ty) sc) =
749 do let ty' = hnf ctxt env ty in
750-- trace ("HNF " ++ show (ty, ty')) $
751 return $ Bind x (Hole ty') sc
752hnf_compute ctxt env t = return t
754-- reduce let bindings only
755simplify :: RunTactic
756simplify ctxt env (Bind x (Hole ty) sc) =
757 do return $ Bind x (Hole (specialise ctxt env [] ty)) sc
758simplify ctxt env t = return t
760check_in :: Raw -> RunTactic
761check_in t ctxt env tm =
762 do (val, valty) <- lift $ check ctxt env t
763 addLog (showEnv env val ++ " : " ++ showEnv env valty)
764 return tm
766eval_in :: Raw -> RunTactic
767eval_in t ctxt env tm =
768 do (val, valty) <- lift $ check ctxt env t
769 let val' = normalise ctxt env val
770 let valty' = normalise ctxt env valty
771 addLog (showEnv env val ++ " : " ++
772 showEnv env valty ++
773-- " in " ++ show env ++
774 " ==>\n " ++
775 showEnv env val' ++ " : " ++
776 showEnv env valty')
777 return tm
779start_unify :: Name -> RunTactic
780start_unify n ctxt env tm = do -- action (\ps -> ps { unified = (n, []) })
781 return tm
783tmap f (a, b, c) = (f a, b, c)
785solve_unified :: RunTactic
786solve_unified ctxt env tm =
787 do ps <- get
788 let (_, ns) = unified ps
789 let unify = dropGiven (dontunify ps) ns (holes ps)
790 action (\ps -> ps { holes = holes ps \\ map fst unify })
791 action (\ps -> ps { pterm = updateSolved unify (pterm ps) })
792 return (updateSolved unify tm)
794dropGiven du [] hs = []
795dropGiven du ((n, P Bound t ty) : us) hs
796 | n `elem` du && not (t `elem` du)
797 && n `elem` hs && t `elem` hs
798 = (t, P Bound n ty) : dropGiven du us hs
799dropGiven du (u@(n, _) : us) hs
800 | n `elem` du = dropGiven du us hs
801-- dropGiven du (u@(_, P a n ty) : us) | n `elem` du = dropGiven du us
802dropGiven du (u : us) hs = u : dropGiven du us hs
804keepGiven du [] hs = []
805keepGiven du ((n, P Bound t ty) : us) hs
806 | n `elem` du && not (t `elem` du)
807 && n `elem` hs && t `elem` hs
808 = keepGiven du us hs
809keepGiven du (u@(n, _) : us) hs
810 | n `elem` du = u : keepGiven du us hs
811keepGiven du (u : us) hs = keepGiven du us hs
813updateSolved :: [(Name, Term)] -> Term -> Term
814updateSolved xs x = updateSolved' xs x
815updateSolved' [] x = x
816updateSolved' xs (Bind n (Hole ty) t)
817 | Just v <- lookup n xs
818 = case xs of
819 [_] -> substV v $ psubst n v t -- some may be Vs! Can't assume
820 -- explicit names
821 _ -> substV v $ psubst n v (updateSolved' xs t)
822updateSolved' xs (Bind n b t)
823 | otherwise = Bind n (fmap (updateSolved' xs) b) (updateSolved' xs t)
824updateSolved' xs (App f a)
825 = App (updateSolved' xs f) (updateSolved' xs a)
826updateSolved' xs (P _ n@(MN _ _) _)
827 | Just v <- lookup n xs = v
828updateSolved' xs t = t
830updateEnv [] e = e
831updateEnv ns [] = []
832updateEnv ns ((n, b) : env) = (n, fmap (updateSolved ns) b) : updateEnv ns env
834updateError [] err = err
835updateError ns (At f e) = At f (updateError ns e)
836updateError ns (Elaborating s n e) = Elaborating s n (updateError ns e)
837updateError ns (ElaboratingArg f a env e)
838 = ElaboratingArg f a env (updateError ns e)
839updateError ns (CantUnify b l r e xs sc)
840 = CantUnify b (updateSolved ns l) (updateSolved ns r) (updateError ns e) xs sc
841updateError ns e = e
843solveInProblems x val [] = []
844solveInProblems x val ((l, r, env, err) : ps)
845 = ((psubst x val l, psubst x val r,
846 updateEnv [(x, val)] env, err) : solveInProblems x val ps)
848mergeNotunified :: Env -> [(Name, Term)] -> ([(Name, Term)], Fails)
849mergeNotunified env ns = mnu ns [] [] where
850 mnu [] ns_acc ps_acc = (reverse ns_acc, reverse ps_acc)
851 mnu ((n, t):ns) ns_acc ps_acc
852 | Just t' <- lookup n ns, t /= t'
853 = mnu ns ((n,t') : ns_acc)
854 ((t,t',env,Msg "", [],Unify) : ps_acc)
855 | otherwise = mnu ns ((n,t) : ns_acc) ps_acc
857updateNotunified [] nu = nu
858updateNotunified ns nu = up nu where
859 up [] = []
860 up ((n, t) : nus) = let t' = updateSolved ns t in
861 ((n, t') : up nus)
863updateProblems :: Context -> [(Name, TT Name)] -> Fails -> [Name] -> [Name]
864 -> ([(Name, TT Name)], Fails)
865updateProblems ctxt [] ps inj holes = ([], ps)
866updateProblems ctxt ns ps inj holes = up ns ps where
867 up ns [] = (ns, [])
868 up ns ((x, y, env, err, while, um) : ps) =
869 let x' = updateSolved ns x
870 y' = updateSolved ns y
871 err' = updateError ns err
872 env' = updateEnv ns env in
873-- trace ("Updating " ++ show (x',y')) $
874 case unify ctxt env' x' y' inj holes while of
875 OK (v, []) -> -- trace ("Added " ++ show v ++ " from " ++ show (x', y')) $
876 up (ns ++ v) ps
877 e -> -- trace ("Failed " ++ show e) $
878 let (ns', ps') = up ns ps in
879 (ns', (x',y',env',err', while, um) : ps')
881-- attempt to solve remaining problems with match_unify
882matchProblems all ns ctxt ps inj holes = up ns ps where
883 up ns [] = (ns, [])
884 up ns ((x, y, env, err, while, um) : ps)
885 | all || um == Match =
886 let x' = updateSolved ns x
887 y' = updateSolved ns y
888 err' = updateError ns err
889 env' = updateEnv ns env in
890 case match_unify ctxt env' x' y' inj holes while of
891 OK v -> -- trace ("Added " ++ show v ++ " from " ++ show (x', y')) $
892 up (ns ++ v) ps
893 _ -> let (ns', ps') = up ns ps in
894 (ns', (x', y', env', err', while, um) : ps')
895 up ns (p : ps) = let (ns', ps') = up ns ps in
896 (ns', p : ps')
898processTactic :: Tactic -> ProofState -> TC (ProofState, String)
899processTactic QED ps = case holes ps of
900 [] -> do let tm = {- normalise (context ps) [] -} (pterm ps)
901 (tm', ty', _) <- recheck (context ps) [] (forget tm) tm
902 return (ps { done = True, pterm = tm' },
903 "Proof complete: " ++ showEnv [] tm')
904 _ -> fail "Still holes to fill."
905processTactic ProofState ps = return (ps, showEnv [] (pterm ps))
906processTactic Undo ps = case previous ps of
907 Nothing -> Error . Msg $ "Nothing to undo."
908 Just pold -> return (pold, "")
909processTactic EndUnify ps
910 = let (h, ns_in) = unified ps
911 ns = dropGiven (dontunify ps) ns_in (holes ps)
912 ns' = map (\ (n, t) -> (n, updateSolved ns t)) ns
913 (ns'', probs') = updateProblems (context ps) ns' (problems ps)
914 (injective ps) (holes ps)
915 tm' = updateSolved ns'' (pterm ps) in
916 return (ps { pterm = tm',
917 unified = (h, []),
918 problems = probs',
919 notunified = updateNotunified ns'' (notunified ps),
920 holes = holes ps \\ map fst ns'' }, "")
921processTactic UnifyAll ps
922 = let tm' = updateSolved (notunified ps) (pterm ps) in
923 return (ps { pterm = tm',
924 notunified = [],
925 holes = holes ps \\ map fst (notunified ps) }, "")
926processTactic (Reorder n) ps
927 = do ps' <- execStateT (tactic (Just n) reorder_claims) ps
928 return (ps' { previous = Just ps, plog = "" }, plog ps')
929processTactic (ComputeLet n) ps
930 = return (ps { pterm = computeLet (context ps) n (pterm ps) }, "")
931processTactic UnifyProblems ps
932 = let (ns', probs') = updateProblems (context ps) []
933 (problems ps)
934 (injective ps)
935 (holes ps)
936 pterm' = updateSolved ns' (pterm ps) in
937 return (ps { pterm = pterm', solved = Nothing, problems = probs',
938 previous = Just ps, plog = "",
939 notunified = updateNotunified ns' (notunified ps),
940 holes = holes ps \\ (map fst ns') }, plog ps)
941processTactic (MatchProblems all) ps
942 = let (ns', probs') = matchProblems all [] (context ps)
943 (problems ps)
944 (injective ps)
945 (holes ps)
946 (ns'', probs'') = matchProblems all ns' (context ps)
947 probs'
948 (injective ps)
949 (holes ps)
950 pterm' = updateSolved ns'' (pterm ps) in
951 return (ps { pterm = pterm', solved = Nothing, problems = probs'',
952 previous = Just ps, plog = "",
953 notunified = updateNotunified ns'' (notunified ps),
954 holes = holes ps \\ (map fst ns'') }, plog ps)
955processTactic t ps
956 = case holes ps of
957 [] -> fail "Nothing to fill in."
958 (h:_) -> do ps' <- execStateT (process t h) ps
959 let (ns', probs')
960 = case solved ps' of
961 Just s -> traceWhen (unifylog ps')
962 ("SOLVED " ++ show s) $
963 updateProblems (context ps')
964 [s] (problems ps')
965 (injective ps')
966 (holes ps')
967 _ -> ([], problems ps')
968 -- rechecking problems may find more solutions, so
969 -- apply them here
970 let pterm'' = updateSolved ns' (pterm ps')
971 return (ps' { pterm = pterm'',
972 solved = Nothing,
973 problems = probs',
974 notunified = updateNotunified ns' (notunified ps'),
975 previous = Just ps, plog = "",
976 holes = holes ps' \\ (map fst ns')}, plog ps')
978process :: Tactic -> Name -> StateT TState TC ()
979process EndUnify _
980 = do ps <- get
981 let (h, _) = unified ps
982 tactic (Just h) solve_unified
983process t h = tactic (Just h) (mktac t)
984 where mktac Attack = attack
985 mktac (Claim n r) = claim n r
986 mktac (Exact r) = exact r
987 mktac (Fill r) = fill r
988 mktac (MatchFill r) = match_fill r
989 mktac (PrepFill n ns) = prep_fill n ns
990 mktac CompleteFill = complete_fill
991 mktac Regret = regret
992 mktac Solve = solve
993 mktac (StartUnify n) = start_unify n
994 mktac Compute = compute
995 mktac Simplify = Idris.Core.ProofState.simplify
996 mktac HNF_Compute = hnf_compute
997 mktac (Intro n) = intro n
998 mktac (IntroTy ty n) = introTy ty n
999 mktac (Forall n t) = forall n t
1000 mktac (LetBind n t v) = letbind n t v
1001 mktac (ExpandLet n b) = expandLet n b
1002 mktac (Rewrite t) = rewrite t
1003 mktac (Induction t) = casetac t True
1004 mktac (CaseTac t) = casetac t False
1005 mktac (Equiv t) = equiv t
1006 mktac (PatVar n) = patvar n
1007 mktac (PatBind n) = patbind n
1008 mktac (CheckIn r) = check_in r
1009 mktac (EvalIn r) = eval_in r
1010 mktac (Focus n) = focus n
1011 mktac (Defer n) = defer n
1012 mktac (DeferType n t a) = deferType n t a
1013 mktac (Instance n) = instanceArg n
1014 mktac (SetInjective n) = setinj n
1015 mktac (MoveLast n) = movelast n