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)
411instanceArg n ctxt env _
412 = fail "The current focus is not a hole."
414autoArg :: Name -> RunTactic
415autoArg n ctxt env (Bind x (Hole t) sc)
416 = do action (\ps -> case lookup x (autos ps) of
419 ps { holes = (hs \\ [x]) ++ [x],
420 autos = (x, (while_elaborating ps, refsIn t)) : autos ps }
422 return (Bind x (Hole t) sc)
424 = fail "The current focus not a hole."
426setinj :: Name -> RunTactic
427setinj n ctxt env (Bind x b sc)
428 = do action (\ps -> let is = injective ps in
429 ps { injective = n : is })
432defer :: [Name] -> Name -> RunTactic
433defer dropped n ctxt env (Bind x (Hole t) (P nt x' ty)) | x == x' =
434 do let env' = filter (\(n, t) -> n `notElem` dropped) env
435 action (\ps -> let hs = holes ps in
436 ps { usedns = n : usedns ps,
439 return (Bind n (GHole (length env') (psnames ps) (mkTy (reverse env') t))
440 (mkApp (P Ref n ty) (map getP (reverse env'))))
443 mkTy ((n,b) : bs) t = Bind n (Pi Nothing (binderTy b) (TType (UVar 0))) (mkTy bs t)
445 getP (n, b) = P Bound n (binderTy b)
446defer dropped n ctxt env _ = fail "Can't defer a non-hole focus."
448-- as defer, but build the type and application explicitly
449deferType :: Name -> Raw -> [Name] -> RunTactic
450deferType n fty_in args ctxt env (Bind x (Hole t) (P nt x' ty)) | x == x' =
451 do (fty, _) <- lift $ check ctxt env fty_in
452 action (\ps -> let hs = holes ps
454 ps { holes = hs \\ [x],
456 return (Bind n (GHole 0 [] fty)
457 (mkApp (P Ref n ty) (map getP args)))
459 getP n = case lookup n env of
460 Just b -> P Bound n (binderTy b)
461 Nothing -> error ("deferType can't find " ++ show n)
462deferType _ _ _ _ _ _ = fail "Can't defer a non-hole focus."
465regret ctxt env (Bind x (Hole t) sc) | noOccurrence x sc =
466 do action (\ps -> let hs = holes ps in
467 ps { holes = hs \\ [x] })
469regret ctxt env (Bind x (Hole t) _)
470 = fail $ show x ++ " : " ++ show t ++ " is not solved..."
471regret _ _ _ = fail "The current focus is not a hole."
473unifyGoal :: Raw -> RunTactic
474unifyGoal tm ctxt env h@(Bind x b sc) =
475 do (tmv, _) <- lift $ check ctxt env tm
476 ns' <- unify' ctxt env (binderTy b, Nothing) (tmv, Nothing)
478unifyGoal _ _ _ _ = fail "The focus is not a binder."
480exact :: Raw -> RunTactic
481exact guess ctxt env (Bind x (Hole ty) sc) =
482 do (val, valty) <- lift $ check ctxt env guess
483 lift $ converts ctxt env valty ty
484 return $ Bind x (Guess ty val) sc
485exact _ _ _ _ = fail "Can't fill here."
487-- As exact, but attempts to solve other goals by unification
489fill :: Raw -> RunTactic
490fill guess ctxt env (Bind x (Hole ty) sc) =
491 do (val, valty) <- lift $ check ctxt env guess
492-- let valtyn = normalise ctxt env valty
493-- let tyn = normalise ctxt env ty
494 ns <- unify' ctxt env (valty, Just $ SourceTerm val)
495 (ty, Just (chkPurpose val ty))
497 let (uh, uns) = unified ps
498-- put (ps { unified = (uh, uns ++ ns) })
499-- addLog (show (uh, uns ++ ns))
500 return $ Bind x (Guess ty val) sc
502 -- some expected types show up commonly in errors and indicate a
504 -- argTy -> retTy suggests a function applied to too many arguments
505 chkPurpose val (Bind _ (Pi _ (P _ (MN _ _) _) _) (P _ (MN _ _) _))
507 chkPurpose _ _ = ExpectedType
508fill _ _ _ _ = fail "Can't fill here."
510-- As fill, but attempts to solve other goals by matching
512match_fill :: Raw -> RunTactic
513match_fill guess ctxt env (Bind x (Hole ty) sc) =
514 do (val, valty) <- lift $ check ctxt env guess
515-- let valtyn = normalise ctxt env valty
516-- let tyn = normalise ctxt env ty
517 ns <- match_unify' ctxt env (valty, Just $ SourceTerm val)
518 (ty, Just ExpectedType)
520 let (uh, uns) = unified ps
521-- put (ps { unified = (uh, uns ++ ns) })
522-- addLog (show (uh, uns ++ ns))
523 return $ Bind x (Guess ty val) sc
524match_fill _ _ _ _ = fail "Can't fill here."
526prep_fill :: Name -> [Name] -> RunTactic
527prep_fill f as ctxt env (Bind x (Hole ty) sc) =
528 do let val = mkApp (P Ref f Erased) (map (\n -> P Ref n Erased) as)
529 return $ Bind x (Guess ty val) sc
530prep_fill f as ctxt env t = fail $ "Can't prepare fill at " ++ show t
532complete_fill :: RunTactic
533complete_fill ctxt env (Bind x (Guess ty val) sc) =
534 do let guess = forget val
535 (val', valty) <- lift $ check ctxt env guess
536 ns <- unify' ctxt env (valty, Just $ SourceTerm val')
537 (ty, Just ExpectedType)
539 let (uh, uns) = unified ps
540-- put (ps { unified = (uh, uns ++ ns) })
541 return $ Bind x (Guess ty val) sc
542complete_fill ctxt env t = fail $ "Can't complete fill at " ++ show t
544-- When solving something in the 'dont unify' set, we should check
545-- that the guess we are solving it with unifies with the thing unification
546-- found for it, if anything.
549solve ctxt env (Bind x (Guess ty val) sc)
551 let (uh, uns) = unified ps
553 case lookup x (notunified ps) of
554 Just tm -> -- trace ("NEED MATCH: " ++ show (x, tm, val) ++ "\nIN " ++ show (pterm ps)) $
555 do match_unify' ctxt env (tm, Just InferredVal)
559 action (\ps -> ps { holes = traceWhen (unifylog ps) ("Dropping hole " ++ show x) $
561 solved = Just (x, val),
562 dontunify = filter (/= x) (dontunify ps),
563 notunified = updateNotunified [(x,val)]
565 recents = x : recents ps,
566 instances = instances ps \\ [x],
567 dotted = dropUnified dropdots (dotted ps) })
568 let (locked, did) = tryLock (holes ps \\ [x]) (updsubst x val sc) in
570 where dropUnified ddots [] = []
571 dropUnified ddots ((x, es) : ds)
572 | x `elem` ddots || any (\e -> e `elem` ddots) es
573 = dropUnified ddots ds
574 | otherwise = (x, es) : dropUnified ddots ds
576 tryLock :: [Name] -> Term -> (Term, Bool)
577 tryLock hs tm@(App Complete _ _) = (tm, True)
578 tryLock hs tm@(App s f a) =
579 let (f', fl) = tryLock hs f
580 (a', al) = tryLock hs a in
581 if fl && al then (App Complete f' a', True)
582 else (App s f' a', False)
583 tryLock hs t@(P _ n _) = (t, not $ n `elem` hs)
584 tryLock hs t@(Bind n (Hole _) sc) = (t, False)
585 tryLock hs t@(Bind n (Guess _ _) sc) = (t, False)
586 tryLock hs t@(Bind n (Let ty val) sc)
587 = let (ty', tyl) = tryLock hs ty
588 (val', vall) = tryLock hs val
589 (sc', scl) = tryLock hs sc in
590 (Bind n (Let ty' val') sc', tyl && vall && scl)
591 tryLock hs t@(Bind n b sc)
592 = let (bt', btl) = tryLock hs (binderTy b)
593 (val', vall) = tryLock hs val
594 (sc', scl) = tryLock hs sc in
595 (Bind n (b { binderTy = bt' }) sc', btl && scl)
596 tryLock hs t = (t, True)
598solve _ _ h@(Bind x t sc)
600 case findType x sc of
601 Just t -> lift $ tfail (CantInferType (show t))
602 _ -> lift $ tfail (IncompleteTerm h)
603 where findType x (Bind n (Let t v) sc)
604 = findType x v `mplus` findType x sc
605 findType x (Bind n t sc)
606 | P _ x' _ <- binderTy t, x == x' = Just n
607 | otherwise = findType x sc
608 findType x _ = Nothing
610introTy :: Raw -> Maybe Name -> RunTactic
611introTy ty mn ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =
612 do let n = case mn of
616 x@(Bind y (Pi _ s _) _) -> x
618 (tyv, tyt) <- lift $ check ctxt env ty
619-- ns <- lift $ unify ctxt env tyv t'
621 Bind y (Pi _ s _) t -> let t' = updsubst y (P Bound n s) t in
622 do ns <- unify' ctxt env (s, Nothing) (tyv, Nothing)
624 let (uh, uns) = unified ps
625-- put (ps { unified = (uh, uns ++ ns) })
626 return $ Bind n (Lam tyv) (Bind x (Hole t') (P Bound x t'))
627 _ -> lift $ tfail $ CantIntroduce t'
628introTy ty n ctxt env _ = fail "Can't introduce here."
630intro :: Maybe Name -> RunTactic
631intro mn ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =
632 do let t' = case t of
633 x@(Bind y (Pi _ s _) _) -> x
636 Bind y (Pi _ s _) t ->
640 -- It's important that this be subst and not updsubst,
641 -- because we want to substitute even in portions of
642 -- terms that we know do not contain holes.
643 t' = subst y (P Bound n s) t
644 in return $ Bind n (Lam s) (Bind x (Hole t') (P Bound x t'))
645 _ -> lift $ tfail $ CantIntroduce t'
646intro n ctxt env _ = fail "Can't introduce here."
648forall :: Name -> Maybe ImplicitInfo -> Raw -> RunTactic
649forall n impl ty ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =
650 do (tyv, tyt) <- lift $ check ctxt env ty
651 unify' ctxt env (tyt, Nothing) (TType (UVar 0), Nothing)
652 unify' ctxt env (t, Nothing) (TType (UVar 0), Nothing)
653 return $ Bind n (Pi impl tyv (TType (UVar 0))) (Bind x (Hole t) (P Bound x t))
654forall n impl ty ctxt env _ = fail "Can't pi bind here"
656patvar :: Name -> RunTactic
657patvar n ctxt env (Bind x (Hole t) sc) =
658 do action (\ps -> ps { holes = traceWhen (unifylog ps) ("Dropping pattern hole " ++ show x) $
660 solved = Just (x, P Bound n t),
661 dontunify = filter (/=x) (dontunify ps),
662 notunified = updateNotunified [(x,P Bound n t)]
664 injective = addInj n x (injective ps)
666 return $ Bind n (PVar t) (updsubst x (P Bound n t) sc)
667 where addInj n x ps | x `elem` ps = n : ps
669patvar n ctxt env tm = fail $ "Can't add pattern var at " ++ show tm
671letbind :: Name -> Raw -> Raw -> RunTactic
672letbind n ty val ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =
673 do (tyv, tyt) <- lift $ check ctxt env ty
674 (valv, valt) <- lift $ check ctxt env val
675 lift $ isType ctxt env tyt
676 return $ Bind n (Let tyv valv) (Bind x (Hole t) (P Bound x t))
677letbind n ty val ctxt env _ = fail "Can't let bind here"
679expandLet :: Name -> Term -> RunTactic
680expandLet n v ctxt env tm =
681 return $ updsubst n v tm
683rewrite :: Raw -> RunTactic
684rewrite tm ctxt env (Bind x (Hole t) xp@(P _ x' _)) | x == x' =
685 do (tmv, tmt) <- lift $ check ctxt env tm
686 let tmt' = normalise ctxt env tmt
688 (P _ (UN q) _, [lt,rt,l,r]) | q == txt "=" ->
689 do let p = Bind rname (Lam lt) (mkP (P Bound rname lt) r l t)
690 let newt = mkP l r l t
691 let sc = forget $ (Bind x (Hole newt)
692 (mkApp (P Ref (sUN "replace") (TType (UVal 0)))
693 [lt, l, r, p, tmv, xp]))
694 (scv, sct) <- lift $ check ctxt env sc
696 _ -> lift $ tfail (NotEquality tmv tmt')
697 where rname = sMN 0 "replaced"
698rewrite _ _ _ _ = fail "Can't rewrite here"
700-- To make the P for rewrite, replace syntactic occurrences of l in ty with
701-- an x, and put \x : lt in front
702mkP :: TT Name -> TT Name -> TT Name -> TT Name -> TT Name
703mkP lt l r ty | l == ty = lt
704mkP lt l r (App s f a) = let f' = if (r /= f) then mkP lt l r f else f
705 a' = if (r /= a) then mkP lt l r a else a in
707mkP lt l r (Bind n b sc)
709 sc' = if (r /= sc) then mkP lt l r sc else sc in
711 where mkPB (Let t v) = let t' = if (r /= t) then mkP lt l r t else t
712 v' = if (r /= v) then mkP lt l r v else v in
714 mkPB b = let ty = binderTy b
715 ty' = if (r /= ty) then mkP lt l r ty else ty in
719casetac :: Raw -> Bool -> RunTactic
720casetac tm induction ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' = do
721 (tmv, tmt) <- lift $ check ctxt env tm
722 let tmt' = normalise ctxt env tmt
723 let (tacn, tacstr, tactt) = if induction
724 then (ElimN, "eliminator", "Induction")
725 else (CaseN (FC' emptyFC), "case analysis", "Case analysis")
727 (P _ tnm _, tyargs) -> do
728 case lookupTy (SN (tacn tnm)) ctxt of
730 param_pos <- case lookupMetaInformation tnm ctxt of
731 [DataMI param_pos] -> return param_pos
732 m | length tyargs > 0 -> fail $ "Invalid meta information for " ++ show tnm ++ " where the metainformation is " ++ show m ++ " and definition is" ++ show (lookupDef tnm ctxt)
734 let (params, indicies) = splitTyArgs param_pos tyargs
735 let args = getArgTys elimTy
736 let pmargs = take (length params) args
737 let args' = drop (length params) args
738 let propTy = head args'
739 let restargs = init $ tail args'
740 let consargs = take (length restargs - length indicies) $ restargs
741 let indxargs = drop (length restargs - length indicies) $ restargs
742 let scr = last $ tail args'
743 let indxnames = makeIndexNames indicies
744 currentNames <- query $ allTTNames . getProofTerm . pterm
745 let tmnm = case tm of
746 Var nm -> uniqueNameCtxt ctxt nm currentNames
747 _ -> uniqueNameCtxt ctxt (sMN 0 "iv") currentNames
748 let tmvar = P Bound tmnm tmt'
749 prop <- replaceIndicies indxnames indicies $ Bind tmnm (Lam tmt') (mkP tmvar tmv tmvar t)
750 consargs' <- query (\ps -> map (flip (uniqueNameCtxt (context ps)) (holes ps ++ allTTNames (getProofTerm (pterm ps))) *** uniqueBindersCtxt (context ps) (holes ps ++ allTTNames (getProofTerm (pterm ps)))) consargs)
751 let res = flip (foldr substV) params $ (substV prop $ bindConsArgs consargs' (mkApp (P Ref (SN (tacn tnm)) (TType (UVal 0)))
752 (params ++ [prop] ++ map makeConsArg consargs' ++ indicies ++ [tmv])))
753 action (\ps -> ps {holes = holes ps \\ [x],
754 recents = x : recents ps })
755 mapM_ addConsHole (reverse consargs')
756 let res' = forget $ res
757 (scv, sct) <- lift $ check ctxt env res'
758 let (scv', _) = specialise ctxt env [] scv
760 [] -> lift $ tfail $ NoEliminator tacstr tmt'
761 xs -> lift $ tfail $ Msg $ "Multiple definitions found when searching for " ++ tacstr ++ "of " ++ show tnm
762 _ -> lift $ tfail $ NoEliminator (if induction then "induction" else "case analysis")
764 where scname = sMN 0 "scarg"
765 makeConsArg (nm, ty) = P Bound nm ty
766 bindConsArgs ((nm, ty):args) v = Bind nm (Hole ty) $ bindConsArgs args v
767 bindConsArgs [] v = v
768 addConsHole (nm, ty) =
769 action (\ps -> ps { holes = nm : holes ps })
770 splitTyArgs param_pos tyargs =
771 let (params, indicies) = partition (flip elem param_pos . fst) . zip [0..] $ tyargs
772 in (map snd params, map snd indicies)
773 makeIndexNames = foldr (\_ nms -> (uniqueNameCtxt ctxt (sMN 0 "idx") nms):nms) []
774 replaceIndicies idnms idxs prop = foldM (\t (idnm, idx) -> do (idxv, idxt) <- lift $ check ctxt env (forget idx)
775 let var = P Bound idnm idxt
776 return $ Bind idnm (Lam idxt) (mkP var idxv var t)) prop $ zip idnms idxs
777casetac tm induction ctxt env _ = fail $ "Can't do " ++ (if induction then "induction" else "case analysis") ++ " here"
780equiv :: Raw -> RunTactic
781equiv tm ctxt env (Bind x (Hole t) sc) =
782 do (tmv, tmt) <- lift $ check ctxt env tm
783 lift $ converts ctxt env tmv t
784 return $ Bind x (Hole tmv) sc
785equiv tm ctxt env _ = fail "Can't equiv here"
787patbind :: Name -> RunTactic
788patbind n ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =
789 do let t' = case t of
790 x@(Bind y (PVTy s) t) -> x
793 Bind y (PVTy s) t -> let t' = updsubst y (P Bound n s) t in
794 return $ Bind n (PVar s) (Bind x (Hole t') (P Bound x t'))
795 _ -> fail "Nothing to pattern bind"
796patbind n ctxt env _ = fail "Can't pattern bind here"
799compute ctxt env (Bind x (Hole ty) sc) =
800 do return $ Bind x (Hole (normalise ctxt env ty)) sc
801compute ctxt env t = return t
803hnf_compute :: RunTactic
804hnf_compute ctxt env (Bind x (Hole ty) sc) =
805 do let ty' = hnf ctxt env ty in
806-- trace ("HNF " ++ show (ty, ty')) $
807 return $ Bind x (Hole ty') sc
808hnf_compute ctxt env t = return t
810-- reduce let bindings only
812simplify ctxt env (Bind x (Hole ty) sc) =
813 do return $ Bind x (Hole (fst (specialise ctxt env [] ty))) sc
814simplify ctxt env t = return t
816check_in :: Raw -> RunTactic
817check_in t ctxt env tm =
818 do (val, valty) <- lift $ check ctxt env t
819 addLog (showEnv env val ++ " : " ++ showEnv env valty)
822eval_in :: Raw -> RunTactic
823eval_in t ctxt env tm =
824 do (val, valty) <- lift $ check ctxt env t
825 let val' = normalise ctxt env val
826 let valty' = normalise ctxt env valty
827 addLog (showEnv env val ++ " : " ++
829-- " in " ++ show env ++
831 showEnv env val' ++ " : " ++
835start_unify :: Name -> RunTactic
836start_unify n ctxt env tm = do -- action (\ps -> ps { unified = (n, []) })
839tmap f (a, b, c) = (f a, b, c)
841solve_unified :: RunTactic
842solve_unified ctxt env tm =
844 let (_, ns) = unified ps
845 let unify = dropGiven (dontunify ps) ns (holes ps)
846 action (\ps -> ps { holes = traceWhen (unifylog ps) ("Dropping holes " ++ show (map fst unify)) $
847 holes ps \\ map fst unify,
848 recents = recents ps ++ map fst unify })
849 action (\ps -> ps { pterm = updateSolved unify (pterm ps) })
850 return (updateSolvedTerm unify tm)
852dropGiven du [] hs = []
853dropGiven du ((n, P Bound t ty) : us) hs
854 | n `elem` du && not (t `elem` du)
855 && n `elem` hs && t `elem` hs
856 = (t, P Bound n ty) : dropGiven du us hs
857dropGiven du (u@(n, _) : us) hs
858 | n `elem` du = dropGiven du us hs
859-- dropGiven du (u@(_, P a n ty) : us) | n `elem` du = dropGiven du us
860dropGiven du (u : us) hs = u : dropGiven du us hs
862keepGiven du [] hs = []
863keepGiven du ((n, P Bound t ty) : us) hs
864 | n `elem` du && not (t `elem` du)
865 && n `elem` hs && t `elem` hs
867keepGiven du (u@(n, _) : us) hs
868 | n `elem` du = u : keepGiven du us hs
869keepGiven du (u : us) hs = keepGiven du us hs
873updateEnv ns ((n, b) : env)
874 = (n, fmap (updateSolvedTerm ns) b) : updateEnv ns env
876updateProv ns (SourceTerm t) = SourceTerm $ updateSolvedTerm ns t
879updateError [] err = err
880updateError ns (At f e) = At f (updateError ns e)
881updateError ns (Elaborating s n e) = Elaborating s n (updateError ns e)
882updateError ns (ElaboratingArg f a env e)
883 = ElaboratingArg f a env (updateError ns e)
884updateError ns (CantUnify b (l,lp) (r,rp) e xs sc)
885 = CantUnify b (updateSolvedTerm ns l, fmap (updateProv ns) lp)
886 (updateSolvedTerm ns r, fmap (updateProv ns) rp) (updateError ns e) xs sc
890updateRes ns ((x, t) : ts) = (x, updateSolvedTerm ns t) : updateRes ns ts
892solveInProblems x val [] = []
893solveInProblems x val ((l, r, env, err) : ps)
894 = ((psubst x val l, psubst x val r,
895 updateEnv [(x, val)] env, err) : solveInProblems x val ps)
897mergeNotunified :: Env -> [Name] -> [(Name, Term)] -> ([(Name, Term)], Fails)
898mergeNotunified env holes ns = mnu ns [] [] where
899 mnu [] ns_acc ps_acc = (reverse ns_acc, reverse ps_acc)
900 mnu ((n, t):ns) ns_acc ps_acc
901 | Just t' <- lookup n ns, t /= t'
902 = mnu ns ((n,t') : ns_acc)
903 ((t,t',True, env,CantUnify True (t, Nothing) (t', Nothing) (Msg "") [] 0, [],Match) : ps_acc)
904 | otherwise = mnu ns ((n,t) : ns_acc) ps_acc
906updateNotunified [] nu = nu
907updateNotunified ns nu = up nu where
909 up ((n, t) : nus) = let t' = updateSolvedTerm ns t in
912getProvenance :: Err -> (Maybe Provenance, Maybe Provenance)
913getProvenance (CantUnify _ (_, lp) (_, rp) _ _ _) = (lp, rp)
914getProvenance _ = (Nothing, Nothing)
916setReady (x, y, _, env, err, c, at) = (x, y, True, env, err, c, at)
918updateProblems :: ProofState -> [(Name, TT Name)] -> Fails
919 -> ([(Name, TT Name)], Fails)
920-- updateProblems ctxt [] ps inj holes = ([], ps)
921updateProblems ps updates probs = rec 10 updates probs
923 -- keep trying if we make progress, but not too many times...
924 rec 0 us fs = (us, fs)
925 rec n us fs = case up us [] fs of
927 res@(us', _) | length us' == length us -> res
928 (us', fs') -> rec (n - 1) us' fs'
934 usupp = map fst (notunified ps)
937 up ns acc [] = (ns, map (updateNs ns) (reverse acc))
938 up ns acc (prob@(x, y, ready, env, err, while, um) : ps) =
939 let (x', newx) = updateSolvedTerm' ns x
940 (y', newy) = updateSolvedTerm' ns y
941 (lp, rp) = getProvenance err
942 err' = updateError ns err
943 env' = updateEnv ns env in
944 if newx || newy || ready ||
945 any (\n -> n `elem` inj) (refsIn x ++ refsIn y) then
946 case unify ctxt env' (x', lp) (y', rp) inj hs usupp while of
947 OK (v, []) -> traceWhen ulog ("DID " ++ show (x',y',ready,v,dont)) $
948 let v' = filter (\(n, _) -> n `notElem` dont) v in
950 e -> -- trace ("FAILED " ++ show (x',y',ready,e)) $
951 up ns ((x',y',False,env',err',while,um) : acc) ps
952 else -- trace ("SKIPPING " ++ show (x,y,ready)) $
953 up ns ((x',y', False, env',err', while, um) : acc) ps
955 updateNs ns (x, y, t, env, err, fc, fa)
956 = let (x', newx) = updateSolvedTerm' ns x
957 (y', newy) = updateSolvedTerm' ns y in
958 (x', y', newx || newy,
959 updateEnv ns env, updateError ns err, fc, fa)
961-- attempt to solve remaining problems with match_unify
962matchProblems :: Bool -> ProofState -> [(Name, TT Name)] -> Fails
963 -> ([(Name, TT Name)], Fails)
964matchProblems all ps updates probs = up updates probs where
970 up ns ((x, y, ready, env, err, while, um) : ps)
971 | all || um == Match =
972 let x' = updateSolvedTerm ns x
973 y' = updateSolvedTerm ns y
974 (lp, rp) = getProvenance err
975 err' = updateError ns err
976 env' = updateEnv ns env in
977 case match_unify ctxt env' (x', lp) (y', rp) inj hs while of
978 OK v -> -- trace ("Added " ++ show v ++ " from " ++ show (x', y')) $
980 _ -> let (ns', ps') = up ns ps in
981 (ns', (x', y', True, env', err', while, um) : ps')
982 up ns (p : ps) = let (ns', ps') = up ns ps in
985processTactic :: Tactic -> ProofState -> TC (ProofState, String)
986processTactic QED ps = case holes ps of
987 [] -> do let tm = {- normalise (context ps) [] -} getProofTerm (pterm ps)
988 (tm', ty', _) <- recheck (context ps) [] (forget tm) tm
989 return (ps { done = True, pterm = mkProofTerm tm' },
990 "Proof complete: " ++ showEnv [] tm')
991 _ -> fail "Still holes to fill."
992processTactic ProofState ps = return (ps, showEnv [] (getProofTerm (pterm ps)))
993processTactic Undo ps = case previous ps of
994 Nothing -> Error . Msg $ "Nothing to undo."
995 Just pold -> return (pold, "")
996processTactic EndUnify ps
997 = let (h, ns_in) = unified ps
998 ns = dropGiven (dontunify ps) ns_in (holes ps)
999 ns' = map (\ (n, t) -> (n, updateSolvedTerm ns t)) ns
1000 (ns'', probs') = updateProblems ps ns' (problems ps)
1001 tm' = updateSolved ns'' (pterm ps) in
1002 traceWhen (unifylog ps) ("(EndUnify) Dropping holes: " ++ show (map fst ns'')) $
1003 return (ps { pterm = tm',
1006 notunified = updateNotunified ns'' (notunified ps),
1007 recents = recents ps ++ map fst ns'',
1008 holes = holes ps \\ map fst ns'' }, "")
1009processTactic UnifyAll ps
1010 = let tm' = updateSolved (notunified ps) (pterm ps) in
1011 return (ps { pterm = tm',
1013 recents = recents ps ++ map fst (notunified ps),
1014 holes = holes ps \\ map fst (notunified ps) }, "")
1015processTactic (Reorder n) ps
1016 = do ps' <- execStateT (tactic (Just n) reorder_claims) ps
1017 return (ps' { previous = Just ps, plog = "" }, plog ps')
1018processTactic (ComputeLet n) ps
1019 = return (ps { pterm = mkProofTerm $
1020 computeLet (context ps) n
1021 (getProofTerm (pterm ps)) }, "")
1022processTactic UnifyProblems ps
1023 = do let (ns', probs') = updateProblems ps [] (map setReady (problems ps))
1024 pterm' = updateSolved ns' (pterm ps)
1025 traceWhen (unifylog ps) ("(UnifyProblems) Dropping holes: " ++ show (map fst ns')) $
1026 return (ps { pterm = pterm', solved = Nothing, problems = probs',
1027 previous = Just ps, plog = "",
1028 notunified = updateNotunified ns' (notunified ps),
1029 recents = recents ps ++ map fst ns',
1030 dotted = filter (notIn ns') (dotted ps),
1031 holes = holes ps \\ (map fst ns') }, plog ps)
1032 where notIn ns (h, _) = h `notElem` map fst ns
1033processTactic (MatchProblems all) ps
1034 = do let (ns', probs') = matchProblems all ps [] (map setReady (problems ps))
1035 (ns'', probs'') = matchProblems all ps ns' probs'
1036 pterm' = orderUpdateSolved ns'' (resetProofTerm (pterm ps))
1037 traceWhen (unifylog ps) ("(MatchProblems) Dropping holes: " ++ show ns'') $
1038 return (ps { pterm = pterm', solved = Nothing, problems = probs'',
1039 previous = Just ps, plog = "",
1040 notunified = updateNotunified ns'' (notunified ps),
1041 recents = recents ps ++ map fst ns'',
1042 holes = holes ps \\ (map fst ns'') }, plog ps)
1044 orderUpdateSolved [] t = t
1045 orderUpdateSolved (n : ns) t = orderUpdateSolved ns (updateSolved [n] t)
1049 Focus _ -> return (ps, "") -- harmless to refocus when done, since
1050 -- 'focus' doesn't fail
1051 _ -> fail $ "Nothing to fill in."
1052 (h:_) -> do ps' <- execStateT (process t h) ps
1054 = case solved ps' of
1055 Just s -> traceWhen (unifylog ps)
1056 ("SOLVED " ++ show s ++ " " ++ show (dontunify ps')) $
1057 updateProblems ps' [s] (problems ps')
1058 _ -> ([], problems ps')
1059 -- rechecking problems may find more solutions, so
1061 let ns' = dropGiven (dontunify ps') ns_in (holes ps')
1062 let pterm'' = updateSolved ns' (pterm ps')
1063 traceWhen (unifylog ps)
1064 ("Updated problems after solve " ++ qshow probs' ++ "\n" ++
1065 "(Toplevel) Dropping holes: " ++ show (map fst ns') ++ "\n" ++
1066 "Holes were: " ++ show (holes ps')) $
1067 return (ps' { pterm = pterm'',
1070 notunified = updateNotunified ns' (notunified ps'),
1071 previous = Just ps, plog = "",
1072 recents = recents ps' ++ map fst ns',
1073 holes = holes ps' \\ (map fst ns')
1076process :: Tactic -> Name -> StateT TState TC ()
1079 let (h, _) = unified ps
1080 tactic (Just h) solve_unified
1081process t h = tactic (Just h) (mktac t)
1082 where mktac Attack = attack
1083 mktac (Claim n r) = claim n r
1084 mktac (ClaimFn n bn r) = claimFn n bn r
1085 mktac (Exact r) = exact r
1086 mktac (Fill r) = fill r
1087 mktac (MatchFill r) = match_fill r
1088 mktac (PrepFill n ns) = prep_fill n ns
1089 mktac CompleteFill = complete_fill
1091 mktac (StartUnify n) = start_unify n
1092 mktac Compute = compute
1093 mktac Simplify = Idris.Core.ProofState.simplify
1094 mktac HNF_Compute = hnf_compute
1095 mktac (Intro n) = intro n
1096 mktac (IntroTy ty n) = introTy ty n
1097 mktac (Forall n i t) = forall n i t
1098 mktac (LetBind n t v) = letbind n t v
1099 mktac (ExpandLet n b) = expandLet n b
1100 mktac (Rewrite t) = rewrite t
1101 mktac (Induction t) = casetac t True
1102 mktac (CaseTac t) = casetac t False
1103 mktac (Equiv t) = equiv t
1104 mktac (PatVar n) = patvar n
1105 mktac (PatBind n) = patbind n
1106 mktac (CheckIn r) = check_in r
1107 mktac (EvalIn r) = eval_in r
1108 mktac (Focus n) = focus n
1109 mktac (Defer ns n) = defer ns n
1110 mktac (DeferType n t a) = deferType n t a
1111 mktac (Instance n) = instanceArg n
1112 mktac (AutoArg n) = autoArg n
1113 mktac (SetInjective n) = setinj n
1114 mktac (MoveLast n) = movelast n
1115 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