2Module : Idris.Core.ProofState
3Description : Proof state implementation.
6Maintainer : The Idris Community.
8Implements a proof state, some primitive tactics for manipulating
9proofs, and some high level commands for introducing new theorems,
10evaluation/checking inside the proof system, etc.
13{-# LANGUAGE FlexibleContexts, FlexibleInstances, MultiParamTypeClasses,
15module Idris.Core.ProofState(
16 ProofState(..), newProof, envAtFocus, goalAtFocus
17 , Tactic(..), Goal(..), processTactic, nowElaboratingPS
18 , doneElaboratingAppPS, doneElaboratingArgPS, dropGiven
19 , keepGiven, getProvenance
22import Idris.Core.Evaluate
23import Idris.Core.ProofTerm
25import Idris.Core.Typecheck
26import Idris.Core.Unify
29import Util.Pretty hiding (fill)
31import Control.Arrow ((***))
32import Control.Monad.State.Strict
35data ProofState = PS { thname :: Name,
36 holes :: [Name], -- ^ holes still to be solved
37 usedns :: [Name], -- ^ used names, don't use again
38 nextname :: Int, -- ^ name supply, for locally unique names
39 global_nextname :: Int, -- ^ a mirror of the global name supply,
40 -- for generating things like type tags
42 pterm :: ProofTerm, -- ^ current proof term
43 ptype :: Type, -- ^ original goal
44 dontunify :: [Name], -- ^ explicitly given by programmer, leave it
45 unified :: (Name, [(Name, Term)]),
46 notunified :: [(Name, Term)],
47 dotted :: [(Name, [Name])], -- ^ dot pattern holes + environment
48 -- either hole or something in env must turn up in the 'notunified' list during elaboration
49 solved :: Maybe (Name, Term),
52 deferred :: [Name], -- ^ names we'll need to define
53 implementations :: [Name], -- ^ implementation arguments (for interfaces)
54 autos :: [(Name, ([FailContext], [Name]))], -- ^ unsolved 'auto' implicits with their holes
55 psnames :: [Name], -- ^ Local names okay to use in proof search
56 previous :: Maybe ProofState, -- ^ for undo
58 datatypes :: Ctxt TypeInfo,
63 while_elaborating :: [FailContext],
64 constraint_ns :: String
69 | ClaimFn Name Name Raw
74 | PrepFill Name [Name]
89 | IntroTy Raw (Maybe Name)
90 | Forall Name RigCount (Maybe ImplicitInfo) Raw
91 | LetBind Name RigCount Raw Raw
98 | PatBind Name RigCount
100 | Defer [Name] [Name] Name
101 | DeferType Name Raw [Name]
102 | Implementation Name
115-- Some utilites on proof and tactic states
117instance Show ProofState where
118 show ps | [] <- holes ps
119 = show (thname ps) ++ ": no more goals"
120 show ps | (h : hs) <- holes ps
123 OK g = goal (Just h) tm
124 wkenv = premises g in
125 "Other goals: " ++ show hs ++ "\n" ++
126 showPs wkenv (reverse wkenv) ++ "\n" ++
127 "-------------------------------- (" ++ show nm ++
129 show h ++ " : " ++ showG wkenv (goalType g) ++ "\n"
130 where showPs env [] = ""
131 showPs env ((n, _, Let _ t v):bs)
132 = " " ++ show n ++ " : " ++
133 showEnv env ({- normalise ctxt env -} t) ++ " = " ++
134 showEnv env ({- normalise ctxt env -} v) ++
135 "\n" ++ showPs env bs
136 showPs env ((n, _, b):bs)
137 = " " ++ show n ++ " : " ++
138 showEnv env ({- normalise ctxt env -} (binderTy b)) ++
139 "\n" ++ showPs env bs
140 showG ps (Guess t v) = showEnv ps ({- normalise ctxt ps -} t) ++
141 " =?= " ++ showEnv ps v
142 showG ps b = showEnv ps (binderTy b)
144instance Pretty ProofState OutputAnnotation where
145 pretty ps | [] <- holes ps =
146 pretty (thname ps) <+> colon <+> text " no more goals."
147 pretty ps | (h : hs) <- holes ps =
149 OK g = goal (Just h) tm
151 let wkEnv = premises g in
152 text "Other goals" <+> colon <+> pretty hs <+>
153 prettyPs wkEnv (reverse wkEnv) <+>
154 text "---------- " <+> text "Focussing on" <> colon <+> pretty nm <+> text " ----------" <+>
155 pretty h <+> colon <+> prettyGoal wkEnv (goalType g)
157 prettyGoal ps (Guess t v) =
158 prettyEnv ps t <+> text "=?=" <+> prettyEnv ps v
159 prettyGoal ps b = prettyEnv ps $ binderTy b
161 prettyPs env [] = empty
162 prettyPs env ((n, _, Let _ t v):bs) =
163 nest nestingSize (pretty n <+> colon <+>
164 prettyEnv env t <+> text "=" <+> prettyEnv env v <+>
165 nest nestingSize (prettyPs env bs))
166 prettyPs env ((n, _, b):bs) =
167 nest nestingSize (pretty n <+> colon <+> prettyEnv env (binderTy b) <+>
168 nest nestingSize (prettyPs env bs))
170holeName i = sMN i "hole"
172qshow :: Fails -> String
173qshow fs = show (map (\ (x, y, hs, env, _, _, t) -> (t, map fstEnv env, x, y, hs)) fs)
175match_unify' :: Context -> Env ->
176 (TT Name, Maybe Provenance) ->
177 (TT Name, Maybe Provenance) ->
178 StateT TState TC [(Name, TT Name)]
179match_unify' ctxt env (topx, xfrom) (topy, yfrom) =
181 let while = while_elaborating ps
182 let inj = injective ps
183 traceWhen (unifylog ps)
184 ("Matching " ++ show (topx, topy) ++
185 " in " ++ show env ++
186 "\nHoles: " ++ show (holes ps)
188 ++ "\n" ++ show (getProofTerm (pterm ps)) ++ "\n\n"
190 case match_unify ctxt env (topx, xfrom) (topy, yfrom) inj (holes ps) while of
191 OK u -> traceWhen (unifylog ps)
192 ("Matched " ++ show u) $
193 do let (h, ns) = unified ps
194 put (ps { unified = (h, u ++ ns) })
196 Error e -> traceWhen (unifylog ps)
197 ("No match " ++ show e) $
198 do put (ps { problems = (topx, topy, True,
199 env, e, while, Match) :
202-- traceWhen (unifylog ps)
203-- ("Matched " ++ show (topx, topy) ++ " without " ++ show dont ++
204-- "\nSolved: " ++ show u
205-- ++ "\nCurrent problems:\n" ++ qshow (problems ps)
206-- -- ++ show (pterm ps)
207-- ++ "\n----------") $
209mergeSolutions :: Env -> [(Name, TT Name)] -> StateT TState TC [(Name, TT Name)]
210mergeSolutions env ns = merge [] ns
212 merge acc [] = return (reverse acc)
213 merge acc ((n, t) : ns)
214 | Just t' <- lookup n ns
216 let probs = problems ps
217 put (ps { problems = probs ++ [(t,t',True,env,
218 CantUnify True (t, Nothing) (t', Nothing) (Msg "") (errEnv env) 0,
221 | otherwise = merge ((n, t): acc) ns
223dropSwaps :: [(Name, TT Name)] -> [(Name, TT Name)]
225dropSwaps (p@(x, P _ y _) : xs) | solvedIn y x xs = dropSwaps xs
226 where solvedIn _ _ [] = False
227 solvedIn y x ((y', P _ x' _) : xs) | y == y' && x == x' = True
228 solvedIn y x (_ : xs) = solvedIn y x xs
229dropSwaps (p : xs) = p : dropSwaps xs
231unify' :: Context -> Env ->
232 (TT Name, Maybe Provenance) ->
233 (TT Name, Maybe Provenance) ->
234 StateT TState TC [(Name, TT Name)]
235unify' ctxt env (topx, xfrom) (topy, yfrom) =
237 let while = while_elaborating ps
238 let dont = dontunify ps
239 let inj = injective ps
240 (u, fails) <- traceWhen (unifylog ps)
241 ("Trying " ++ show (topx, topy) ++
242 "\nNormalised " ++ show (normalise ctxt env topx,
243 normalise ctxt env topy) ++
244 " in\n" ++ show env ++
245 "\nHoles: " ++ show (holes ps)
246 ++ "\nInjective: " ++ show (injective ps)
248 lift $ unify ctxt env (topx, xfrom) (topy, yfrom) inj (holes ps)
249 (map fst (notunified ps)) while
250 let notu = filter (\ (n, t) -> case t of
252 _ -> n `elem` dont) u
253 traceWhen (unifylog ps)
254 ("Unified " ++ show (topx, topy) ++ " without " ++ show dont ++
255 "\nSolved: " ++ show u ++ "\nNew problems: " ++ qshow fails
256 ++ "\nNot unified:\n" ++ show (notunified ps)
257 ++ "\nCurrent problems:\n" ++ qshow (problems ps)
260 do let (h, ns) = unified ps
261 -- solve in results (maybe unify should do this itself...)
262 let u' = map (\(n, sol) -> (n, updateSolvedTerm u sol)) u
263 -- if a metavar has multiple solutions, make a new unification
265 uns <- mergeSolutions env (u' ++ ns)
267 let (ns_p, probs') = updateProblems ps uns (fails ++ problems ps)
268 let ns' = dropSwaps ns_p
269 let (notu', probs_notu) = mergeNotunified env (holes ps) (notu ++ notunified ps)
270 traceWhen (unifylog ps)
271 ("Now solved: " ++ show ns' ++
272 "\nNow problems: " ++ qshow (probs' ++ probs_notu) ++
273 "\nNow injective: " ++ show (updateInj u (injective ps))) $
274 put (ps { problems = probs' ++ probs_notu,
276 injective = updateInj u (injective ps),
277 notunified = notu' })
279 where updateInj ((n, a) : us) inj
280 | (P _ n' _, _) <- unApply a,
281 n `elem` inj = updateInj us (n':inj)
282 | (P _ n' _, _) <- unApply a,
283 n' `elem` inj = updateInj us (n:inj)
284 updateInj (_ : us) inj = updateInj us inj
285 updateInj [] inj = inj
287nowElaboratingPS :: FC -> Name -> Name -> ProofState -> ProofState
288nowElaboratingPS fc f arg ps = ps { while_elaborating = FailContext fc f arg : while_elaborating ps }
290dropUntil :: (a -> Bool) -> [a] -> [a]
292dropUntil p (x:xs) | p x = xs
293 | otherwise = dropUntil p xs
295doneElaboratingAppPS :: Name -> ProofState -> ProofState
296doneElaboratingAppPS f ps = let while = while_elaborating ps
297 while' = dropUntil (\ (FailContext _ f' _) -> f == f') while
298 in ps { while_elaborating = while' }
300doneElaboratingArgPS :: Name -> Name -> ProofState -> ProofState
301doneElaboratingArgPS f x ps = let while = while_elaborating ps
302 while' = dropUntil (\ (FailContext _ f' x') -> f == f' && x == x') while
303 in ps { while_elaborating = while' }
305getName :: Monad m => String -> StateT TState m Name
306getName tag = do ps <- get
308 put (ps { nextname = n+1 })
311action :: Monad m => (ProofState -> ProofState) -> StateT TState m ()
312action a = do ps <- get
315query :: Monad m => (ProofState -> r) -> StateT TState m r
316query q = do ps <- get
319addLog :: Monad m => String -> StateT TState m ()
320addLog str = action (\ps -> ps { plog = plog ps ++ str ++ "\n" })
322newProof :: Name -- ^ the name of what's to be elaborated
323 -> String -- ^ current source file
324 -> Context -- ^ the current global context
325 -> Ctxt TypeInfo -- ^ the value of the idris_datatypes field of IState
326 -> Int -- ^ the value of the idris_name field of IState
327 -> Type -- ^ the goal type
329newProof n tcns ctxt datatypes globalNames ty =
332 in PS n [h] [] 1 globalNames (mkProofTerm (Bind h (Hole ty')
333 (P Bound h ty'))) ty [] (h, []) [] []
336 Nothing ctxt datatypes "" False False [] [] tcns
338type TState = ProofState -- [TacticAction])
339type RunTactic = RunTactic' TState
341envAtFocus :: ProofState -> TC Env
343 | not $ null (holes ps) = do g <- goal (Just (head (holes ps))) (pterm ps)
345 | otherwise = fail $ "No holes in " ++ show (getProofTerm (pterm ps))
347goalAtFocus :: ProofState -> TC (Binder Type)
349 | not $ null (holes ps) = do g <- goal (Just (head (holes ps))) (pterm ps)
351 | otherwise = Error . Msg $ "No goal in " ++ show (holes ps) ++ show (getProofTerm (pterm ps))
353tactic :: Hole -> RunTactic -> StateT TState TC ()
354tactic h f = do ps <- get
355 (tm', _) <- atHole h f (context ps) [] (pterm ps)
356 ps <- get -- might have changed while processing
357 put (ps { pterm = tm' })
359computeLet :: Context -> Name -> Term -> Term
360computeLet ctxt n tm = cl [] tm where
361 cl env (Bind n' (Let r t v) sc)
362 | n' == n = let v' = normalise ctxt env v in
363 Bind n' (Let r t v') sc
364 cl env (Bind n' b sc) = Bind n' (fmap (cl env) b) (cl ((n, Rig0, b):env) sc)
365 cl env (App s f a) = App s (cl env f) (cl env a)
369attack ctxt env (Bind x (Hole t) sc)
370 = do h <- getName "hole"
371 action (\ps -> ps { holes = h : holes ps })
372 return $ Bind x (Guess t (newtm h)) sc
374 newtm h = Bind h (Hole t) (P Bound h t)
375attack ctxt env _ = fail "Not an attackable hole"
377claim :: Name -> Raw -> RunTactic
378claim n ty ctxt env t =
379 do (tyv, tyt) <- lift $ check ctxt env ty
380 lift $ isType ctxt env tyt
381 action (\ps -> let (g:gs) = holes ps in
382 ps { holes = g : n : gs } )
383 return $ Bind n (Hole tyv) t
385-- If the current goal is 'retty', make a claim which is a function that
386-- can compute a retty from argty (i.e a claim 'argty -> retty')
387claimFn :: Name -> Name -> Raw -> RunTactic
388claimFn n bn argty ctxt env t@(Bind x (Hole retty) sc) =
389 do (tyv, tyt) <- lift $ check ctxt env argty
390 lift $ isType ctxt env tyt
391 action (\ps -> let (g:gs) = holes ps in
392 ps { holes = g : n : gs } )
393 return $ Bind n (Hole (Bind bn (Pi RigW Nothing tyv tyt) retty)) t
394claimFn _ _ _ ctxt env _ = fail "Can't make function type here"
396reorder_claims :: RunTactic
397reorder_claims ctxt env t
398 = -- trace (showSep "\n" (map show (scvs t))) $
399 let (bs, sc) = scvs t []
400 newbs = reverse (sortB (reverse bs)) in
401 traceWhen (bs /= newbs) (show bs ++ "\n ==> \n" ++ show newbs) $
402 return (bindAll newbs sc)
403 where scvs (Bind n b@(Hole _) sc) acc = scvs sc ((n, b):acc)
404 scvs sc acc = (reverse acc, sc)
406 sortB :: [(Name, Binder (TT Name))] -> [(Name, Binder (TT Name))]
408 sortB (x:xs) | all (noOcc x) xs = x : sortB xs
409 | otherwise = sortB (insertB x xs)
412 insertB x (y:ys) | all (noOcc x) (y:ys) = x : y : ys
413 | otherwise = y : insertB x ys
415 noOcc (n, _) (_, Let _ t v) = noOccurrence n t && noOccurrence n v
416 noOcc (n, _) (_, Guess t v) = noOccurrence n t && noOccurrence n v
417 noOcc (n, _) (_, b) = noOccurrence n (binderTy b)
419focus :: Name -> RunTactic
420focus n ctxt env t = do action (\ps -> let hs = holes ps in
422 then ps { holes = n : (hs \\ [n]) }
427movelast :: Name -> RunTactic
428movelast n ctxt env t = do action (\ps -> let hs = holes ps in
430 then ps { holes = (hs \\ [n]) ++ [n] }
434implementationArg :: Name -> RunTactic
435implementationArg n ctxt env (Bind x (Hole t) sc)
436 = do action (\ps -> let hs = holes ps
437 is = implementations ps in
438 ps { holes = (hs \\ [x]) ++ [x],
439 implementations = x:is })
440 return (Bind x (Hole t) sc)
441implementationArg n ctxt env _
442 = fail "The current focus is not a hole."
444autoArg :: Name -> RunTactic
445autoArg n ctxt env (Bind x (Hole t) sc)
446 = do action (\ps -> case lookup x (autos ps) of
449 ps { holes = (hs \\ [x]) ++ [x],
450 autos = (x, (while_elaborating ps, refsIn t)) : autos ps }
452 return (Bind x (Hole t) sc)
454 = fail "The current focus not a hole."
456setinj :: Name -> RunTactic
457setinj n ctxt env (Bind x b sc)
458 = do action (\ps -> let is = injective ps in
459 ps { injective = n : is })
462defer :: [Name] -> [Name] -> Name -> RunTactic
463defer dropped linused n ctxt env (Bind x (Hole t) (P nt x' ty)) | x == x' =
464 do let env' = filter (\(n, _, t) -> n `notElem` dropped) env
465 action (\ps -> let hs = holes ps in
466 ps { usedns = n : usedns ps,
469 return (Bind n (GHole (length env') (psnames ps) (mkTy (reverse env') t))
470 (mkApp (P Ref n ty) (map getP (reverse env'))))
473 mkTy ((n,rig,b) : bs) t = Bind n (Pi (setRig rig n) Nothing (binderTy b) (TType (UVar [] 0))) (mkTy bs t)
475 setRig Rig1 n | n `elem` linused = Rig0
478 getP (n, rig, b) = P Bound n (binderTy b)
479defer dropped linused n ctxt env _ = fail "Can't defer a non-hole focus."
481-- as defer, but build the type and application explicitly
482deferType :: Name -> Raw -> [Name] -> RunTactic
483deferType n fty_in args ctxt env (Bind x (Hole t) (P nt x' ty)) | x == x' =
484 do (fty, _) <- lift $ check ctxt env fty_in
485 action (\ps -> let hs = holes ps
487 ps { holes = hs \\ [x],
489 return (Bind n (GHole 0 [] fty)
490 (mkApp (P Ref n ty) (map getP args)))
492 getP n = case lookupBinder n env of
493 Just b -> P Bound n (binderTy b)
494 Nothing -> error ("deferType can't find " ++ show n)
495deferType _ _ _ _ _ _ = fail "Can't defer a non-hole focus."
497unifyGoal :: Raw -> RunTactic
498unifyGoal tm ctxt env h@(Bind x b sc) =
499 do (tmv, _) <- lift $ check ctxt env tm
500 ns' <- unify' ctxt env (binderTy b, Nothing) (tmv, Nothing)
502unifyGoal _ _ _ _ = fail "The focus is not a binder."
504unifyTerms :: Raw -> Raw -> RunTactic
505unifyTerms tm1 tm2 ctxt env h =
506 do (tm1v, _) <- lift $ check ctxt env tm1
507 (tm2v, _) <- lift $ check ctxt env tm2
508 ns' <- unify' ctxt env (tm1v, Nothing) (tm2v, Nothing)
511exact :: Raw -> RunTactic
512exact guess ctxt env (Bind x (Hole ty) sc) =
513 do (val, valty) <- lift $ check ctxt env guess
514 lift $ converts ctxt env valty ty
515 return $ Bind x (Guess ty val) sc
516exact _ _ _ _ = fail "Can't fill here."
518-- As exact, but attempts to solve other goals by unification
520fill :: Raw -> RunTactic
521fill guess ctxt env (Bind x (Hole ty) sc) =
522 do (val, valty) <- lift $ check ctxt env guess
523 unify' ctxt env (valty, Just $ SourceTerm val)
524 (ty, Just (chkPurpose val ty))
525 return $ Bind x (Guess ty val) sc
527 -- some expected types show up commonly in errors and indicate a
529 -- argTy -> retTy suggests a function applied to too many arguments
530 chkPurpose val (Bind _ (Pi _ _ (P _ (MN _ _) _) _) (P _ (MN _ _) _))
532 chkPurpose _ _ = ExpectedType
533fill _ _ _ _ = fail "Can't fill here."
535-- As fill, but attempts to solve other goals by matching
537match_fill :: Raw -> RunTactic
538match_fill guess ctxt env (Bind x (Hole ty) sc) =
539 do (val, valty) <- lift $ check ctxt env guess
540 match_unify' ctxt env (valty, Just $ SourceTerm val)
541 (ty, Just ExpectedType)
542 return $ Bind x (Guess ty val) sc
543match_fill _ _ _ _ = fail "Can't fill here."
545prep_fill :: Name -> [Name] -> RunTactic
546prep_fill f as ctxt env (Bind x (Hole ty) sc) =
547 do let val = mkApp (P Ref f Erased) (map (\n -> P Ref n Erased) as)
548 return $ Bind x (Guess ty val) sc
549prep_fill f as ctxt env t = fail $ "Can't prepare fill at " ++ show t
551complete_fill :: RunTactic
552complete_fill ctxt env (Bind x (Guess ty val) sc) =
553 do let guess = forget val
554 (val', valty) <- lift $ check ctxt env guess
555 unify' ctxt env (valty, Just $ SourceTerm val')
556 (ty, Just ExpectedType)
557 return $ Bind x (Guess ty val) sc
558complete_fill ctxt env t = fail $ "Can't complete fill at " ++ show t
560-- When solving something in the 'dont unify' set, we should check
561-- that the guess we are solving it with unifies with the thing unification
562-- found for it, if anything.
565solve ctxt env (Bind x (Guess ty val) sc)
568 case lookup x (notunified ps) of
569 Just tm -> -- trace ("NEED MATCH: " ++ show (x, tm, val) ++ "\nIN " ++ show (pterm ps)) $
570 do match_unify' ctxt env (tm, Just InferredVal)
574 action (\ps -> ps { holes = traceWhen (unifylog ps) ("Dropping hole " ++ show x) $
576 solved = Just (x, val),
577 dontunify = filter (/= x) (dontunify ps),
578 notunified = updateNotunified [(x,val)]
580 recents = x : recents ps,
581 implementations = implementations ps \\ [x],
582 dotted = dropUnified dropdots (dotted ps) })
583 let (locked, _) = tryLock (holes ps \\ [x]) (updsubst x val sc) in
585 where dropUnified ddots [] = []
586 dropUnified ddots ((x, es) : ds)
587 | x `elem` ddots || any (\e -> e `elem` ddots) es
588 = dropUnified ddots ds
589 | otherwise = (x, es) : dropUnified ddots ds
591 tryLock :: [Name] -> Term -> (Term, Bool)
592 tryLock hs tm@(App Complete _ _) = (tm, True)
593 tryLock hs tm@(App s f a) =
594 let (f', fl) = tryLock hs f
595 (a', al) = tryLock hs a in
596 if fl && al then (App Complete f' a', True)
597 else (App s f' a', False)
598 tryLock hs t@(P _ n _) = (t, not $ n `elem` hs)
599 tryLock hs t@(Bind n (Hole _) sc) = (t, False)
600 tryLock hs t@(Bind n (Guess _ _) sc) = (t, False)
601 tryLock hs t@(Bind n (Let r ty val) sc)
602 = let (ty', tyl) = tryLock hs ty
603 (val', vall) = tryLock hs val
604 (sc', scl) = tryLock hs sc in
605 (Bind n (Let r ty' val') sc', tyl && vall && scl)
606 tryLock hs t@(Bind n b sc)
607 = let (bt', btl) = tryLock hs (binderTy b)
608 (sc', scl) = tryLock hs sc in
609 (Bind n (b { binderTy = bt' }) sc', btl && scl)
610 tryLock hs t = (t, True)
612solve _ _ h@(Bind x t sc)
614 case findType x sc of
615 Just t -> lift $ tfail (CantInferType (show t))
616 _ -> lift $ tfail (IncompleteTerm h)
617 where findType x (Bind n (Let r t v) sc)
618 = findType x v `mplus` findType x sc
619 findType x (Bind n t sc)
620 | P _ x' _ <- binderTy t, x == x' = Just n
621 | otherwise = findType x sc
622 findType x _ = Nothing
624introTy :: Raw -> Maybe Name -> RunTactic
625introTy ty mn ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =
626 do let n = case mn of
630 x@(Bind y (Pi _ _ s _) _) -> x
631 _ -> normalise ctxt env t
632 (tyv, tyt) <- lift $ check ctxt env ty
634 Bind y (Pi rig _ s _) t -> let t' = updsubst y (P Bound n s) t in
635 do unify' ctxt env (s, Nothing) (tyv, Nothing)
636 return $ Bind n (Lam rig tyv) (Bind x (Hole t') (P Bound x t'))
637 _ -> lift $ tfail $ CantIntroduce t'
638introTy ty n ctxt env _ = fail "Can't introduce here."
640intro :: Maybe Name -> RunTactic
641intro mn ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =
642 do let t' = case t of
643 x@(Bind y (Pi _ _ s _) _) -> x
644 _ -> normalise ctxt env t
646 Bind y (Pi rig _ s _) t ->
650 -- It's important that this be subst and not updsubst,
651 -- because we want to substitute even in portions of
652 -- terms that we know do not contain holes.
653 t' = subst y (P Bound n s) t
654 in return $ Bind n (Lam rig s) (Bind x (Hole t') (P Bound x t'))
655 _ -> lift $ tfail $ CantIntroduce t'
656intro n ctxt env _ = fail "Can't introduce here."
658forall :: Name -> RigCount -> Maybe ImplicitInfo -> Raw -> RunTactic
659forall n rig impl ty ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =
660 do (tyv, tyt) <- lift $ check ctxt env ty
661 unify' ctxt env (tyt, Nothing) (TType (UVar [] 0), Nothing)
662 unify' ctxt env (t, Nothing) (TType (UVar [] 0), Nothing)
663 return $ Bind n (Pi rig impl tyv (TType (UVar [] 0))) (Bind x (Hole t) (P Bound x t))
664forall n rig impl ty ctxt env _ = fail "Can't pi bind here"
666patvar :: Name -> RunTactic
667patvar n ctxt env (Bind x (Hole t) sc) =
668 do action (\ps -> ps { holes = traceWhen (unifylog ps) ("Dropping pattern hole " ++ show x) $
670 solved = Just (x, P Bound n t),
671 dontunify = filter (/=x) (dontunify ps),
672 notunified = updateNotunified [(x,P Bound n t)]
674 injective = addInj n x (injective ps)
676 return $ Bind n (PVar RigW t) (updsubst x (P Bound n t) sc)
677 where addInj n x ps | x `elem` ps = n : ps
679patvar n ctxt env tm = fail $ "Can't add pattern var at " ++ show tm
681letbind :: Name -> RigCount -> Raw -> Raw -> RunTactic
682letbind n rig ty val ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =
683 do (tyv, tyt) <- lift $ check ctxt env ty
684 (valv, valt) <- lift $ check ctxt env val
685 lift $ isType ctxt env tyt
686 return $ Bind n (Let rig tyv valv) (Bind x (Hole t) (P Bound x t))
687letbind n rig ty val ctxt env _ = fail "Can't let bind here"
689expandLet :: Name -> Term -> RunTactic
690expandLet n v ctxt env tm =
691 return $ updsubst n v tm
693rewrite :: Raw -> RunTactic
694rewrite tm ctxt env (Bind x (Hole t) xp@(P _ x' _)) | x == x' =
695 do (tmv, tmt) <- lift $ check ctxt env tm
696 let tmt' = normalise ctxt env tmt
698 (P _ (UN q) _, [lt,rt,l,r]) | q == txt "=" ->
699 do let p = Bind rname (Lam RigW lt) (mkP (P Bound rname lt) r l t)
700 let newt = mkP l r l t
701 let sc = forget $ (Bind x (Hole newt)
702 (mkApp (P Ref (sUN "replace") (TType (UVal 0)))
703 [lt, l, r, p, tmv, xp]))
704 (scv, sct) <- lift $ check ctxt env sc
706 _ -> lift $ tfail (NotEquality tmv tmt')
707 where rname = sMN 0 "replaced"
708rewrite _ _ _ _ = fail "Can't rewrite here"
710-- To make the P for rewrite, replace syntactic occurrences of l in ty with
711-- an x, and put \x : lt in front
712mkP :: TT Name -> TT Name -> TT Name -> TT Name -> TT Name
713mkP lt l r ty | l == ty = lt
714mkP lt l r (App s f a) = let f' = if (r /= f) then mkP lt l r f else f
715 a' = if (r /= a) then mkP lt l r a else a in
717mkP lt l r (Bind n b sc)
719 sc' = if (r /= sc) then mkP lt l r sc else sc in
721 where mkPB (Let c t v) = let t' = if (r /= t) then mkP lt l r t else t
722 v' = if (r /= v) then mkP lt l r v else v in
724 mkPB b = let ty = binderTy b
725 ty' = if (r /= ty) then mkP lt l r ty else ty in
729casetac :: Raw -> Bool -> RunTactic
730casetac tm induction ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' = do
731 (tmv, tmt) <- lift $ check ctxt env tm
732 let tmt' = normalise ctxt env tmt
733 let (tacn, tacstr, _) = if induction
734 then (ElimN, "eliminator", "Induction")
735 else (CaseN (FC' emptyFC), "case analysis", "Case analysis")
737 (P _ tnm _, tyargs) -> do
738 case lookupTy (SN (tacn tnm)) ctxt of
740 param_pos <- case lookupMetaInformation tnm ctxt of
741 [DataMI param_pos] -> return param_pos
742 m | not (null tyargs) -> fail $ "Invalid meta information for " ++ show tnm ++ " where the metainformation is " ++ show m ++ " and definition is" ++ show (lookupDef tnm ctxt)
744 let (params, indicies) = splitTyArgs param_pos tyargs
745 let args = getArgTys elimTy
746 let args' = drop (length params) args
747 let restargs = init $ tail args'
748 let consargs = take (length restargs - length indicies) restargs
749 let indxnames = makeIndexNames indicies
750 currentNames <- query $ allTTNames . getProofTerm . pterm
751 let tmnm = case tm of
752 Var nm -> uniqueNameCtxt ctxt nm currentNames
753 _ -> uniqueNameCtxt ctxt (sMN 0 "iv") currentNames
754 let tmvar = P Bound tmnm tmt'
755 prop <- replaceIndicies indxnames indicies $ Bind tmnm (Lam RigW tmt') (mkP tmvar tmv tmvar t)
756 consargs' <- query (\ps -> map (flip (uniqueNameCtxt (context ps)) (holes ps ++ allTTNames (getProofTerm (pterm ps))) *** uniqueBindersCtxt (context ps) (holes ps ++ allTTNames (getProofTerm (pterm ps)))) consargs)
757 let res = flip (foldr substV) params $ (substV prop $ bindConsArgs consargs' (mkApp (P Ref (SN (tacn tnm)) (TType (UVal 0)))
758 (params ++ [prop] ++ map makeConsArg consargs' ++ indicies ++ [tmv])))
759 action (\ps -> ps {holes = holes ps \\ [x],
760 recents = x : recents ps })
761 mapM_ addConsHole (reverse consargs')
762 let res' = forget res
763 (scv, sct) <- lift $ check ctxt env res'
764 let (scv', _) = specialise ctxt env [] scv
766 [] -> lift $ tfail $ NoEliminator tacstr tmt'
767 xs -> lift $ tfail $ Msg $ "Multiple definitions found when searching for " ++ tacstr ++ "of " ++ show tnm
768 _ -> lift $ tfail $ NoEliminator (if induction then "induction" else "case analysis")
770 where makeConsArg (nm, ty) = P Bound nm ty
771 bindConsArgs ((nm, ty):args) v = Bind nm (Hole ty) $ bindConsArgs args v
772 bindConsArgs [] v = v
773 addConsHole (nm, ty) =
774 action (\ps -> ps { holes = nm : holes ps })
775 splitTyArgs param_pos tyargs =
776 let (params, indicies) = partition (flip elem param_pos . fst) . zip [0..] $ tyargs
777 in (map snd params, map snd indicies)
778 makeIndexNames = foldr (\_ nms -> (uniqueNameCtxt ctxt (sMN 0 "idx") nms):nms) []
779 replaceIndicies idnms idxs prop = foldM (\t (idnm, idx) -> do (idxv, idxt) <- lift $ check ctxt env (forget idx)
780 let var = P Bound idnm idxt
781 return $ Bind idnm (Lam RigW idxt) (mkP var idxv var t)) prop $ zip idnms idxs
782casetac tm induction ctxt env _ = fail $ "Can't do " ++ (if induction then "induction" else "case analysis") ++ " here"
785equiv :: Raw -> RunTactic
786equiv tm ctxt env (Bind x (Hole t) sc) =
787 do (tmv, tmt) <- lift $ check ctxt env tm
788 lift $ converts ctxt env tmv t
789 return $ Bind x (Hole tmv) sc
790equiv tm ctxt env _ = fail "Can't equiv here"
792patbind :: Name -> RigCount -> RunTactic
793patbind n rig ctxt env (Bind x (Hole t) (P _ x' _)) | x == x' =
794 do let t' = case t of
795 x@(Bind y (PVTy s) t) -> x
796 _ -> normalise ctxt env t
798 Bind y (PVTy s) t -> let t' = updsubst y (P Bound n s) t in
799 return $ Bind n (PVar rig s) (Bind x (Hole t') (P Bound x t'))
800 _ -> fail "Nothing to pattern bind"
801patbind n _ ctxt env _ = fail "Can't pattern bind here"
804compute ctxt env (Bind x (Hole ty) sc) =
805 do return $ Bind x (Hole (normalise ctxt env ty)) sc
806compute ctxt env t = return t
808whnf_compute :: RunTactic
809whnf_compute ctxt env (Bind x (Hole ty) sc) =
810 do let ty' = whnf ctxt env ty in
811 return $ Bind x (Hole ty') sc
812whnf_compute ctxt env t = return t
814whnf_compute_args :: RunTactic
815whnf_compute_args ctxt env (Bind x (Hole ty) sc) =
816 do let ty' = whnfArgs ctxt env ty in
817 return $ Bind x (Hole ty') sc
818whnf_compute_args ctxt env t = return t
820-- reduce let bindings only
822simplify ctxt env (Bind x (Hole ty) sc) =
823 do return $ Bind x (Hole (fst (specialise ctxt env [] ty))) sc
824simplify ctxt env t = return t
826check_in :: Raw -> RunTactic
827check_in t ctxt env tm =
828 do (val, valty) <- lift $ check ctxt env t
829 addLog (showEnv env val ++ " : " ++ showEnv env valty)
832eval_in :: Raw -> RunTactic
833eval_in t ctxt env tm =
834 do (val, valty) <- lift $ check ctxt env t
835 let val' = normalise ctxt env val
836 let valty' = normalise ctxt env valty
837 addLog (showEnv env val ++ " : " ++
839-- " in " ++ show env ++
841 showEnv env val' ++ " : " ++
845start_unify :: Name -> RunTactic
846start_unify n ctxt env tm = do -- action (\ps -> ps { unified = (n, []) })
849solve_unified :: RunTactic
850solve_unified ctxt env tm =
852 let (_, ns) = unified ps
853 let unify = dropGiven (dontunify ps) ns (holes ps)
854 action (\ps -> ps { holes = traceWhen (unifylog ps) ("Dropping holes " ++ show (map fst unify)) $
855 holes ps \\ map fst unify,
856 recents = recents ps ++ map fst unify })
857 action (\ps -> ps { pterm = updateSolved unify (pterm ps) })
858 return (updateSolvedTerm unify tm)
860dropGiven du [] hs = []
861dropGiven du ((n, P Bound t ty) : us) hs
862 | n `elem` du && not (t `elem` du)
863 && n `elem` hs && t `elem` hs
864 = (t, P Bound n ty) : dropGiven du us hs
865dropGiven du (u@(n, _) : us) hs
866 | n `elem` du = dropGiven du us hs
867-- dropGiven du (u@(_, P a n ty) : us) | n `elem` du = dropGiven du us
868dropGiven du (u : us) hs = u : dropGiven du us hs
870keepGiven du [] hs = []
871keepGiven du ((n, P Bound t ty) : us) hs
872 | n `elem` du && not (t `elem` du)
873 && n `elem` hs && t `elem` hs
875keepGiven du (u@(n, _) : us) hs
876 | n `elem` du = u : keepGiven du us hs
877keepGiven du (u : us) hs = keepGiven du us hs
881updateEnv ns ((n, rig, b) : env)
882 = (n, rig, fmap (updateSolvedTerm ns) b) : updateEnv ns env
884updateProv ns (SourceTerm t) = SourceTerm $ updateSolvedTerm ns t
887updateError [] err = err
888updateError ns (At f e) = At f (updateError ns e)
889updateError ns (Elaborating s n ty e) = Elaborating s n ty (updateError ns e)
890updateError ns (ElaboratingArg f a env e)
891 = ElaboratingArg f a env (updateError ns e)
892updateError ns (CantUnify b (l,lp) (r,rp) e xs sc)
893 = CantUnify b (updateSolvedTerm ns l, fmap (updateProv ns) lp)
894 (updateSolvedTerm ns r, fmap (updateProv ns) rp) (updateError ns e) xs sc
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)
961orderUpdateSolved :: [(Name, Term)] -> ProofTerm -> (ProofTerm, [Name])
962orderUpdateSolved ns tm = update [] ns tm
964 update done [] t = (t, done)
965 update done ((n, P _ n' _) : ns) t | n == n' = update done ns t
966 update done (n : ns) t = update (fst n : done)
967 (map (updateMatch n) ns)
970 -- Update the later solutions too
971 updateMatch n (x, tm) = (x, updateSolvedTerm [n] tm)
973-- attempt to solve remaining problems with match_unify
974matchProblems :: Bool -> ProofState -> [(Name, TT Name)] -> Fails
975 -> ([(Name, TT Name)], Fails)
976matchProblems all ps updates probs = up updates probs where
982 up ns ((x, y, ready, env, err, while, um) : ps)
983 | all || um == Match =
984 let x' = updateSolvedTerm ns x
985 y' = updateSolvedTerm ns y
986 (lp, rp) = getProvenance err
987 err' = updateError ns err
988 env' = updateEnv ns env in
989 case match_unify ctxt env' (x', lp) (y', rp) inj hs while of
990 OK v -> -- trace ("Added " ++ show v ++ " from " ++ show (x', y')) $
992 _ -> let (ns', ps') = up ns ps in
993 (ns', (x', y', True, env', err', while, um) : ps')
994 up ns (p : ps) = let (ns', ps') = up ns ps in
997processTactic :: Tactic -> ProofState -> TC (ProofState, String)
998processTactic QED ps = case holes ps of
999 [] -> do let tm = {- normalise (context ps) [] -} getProofTerm (pterm ps)
1000 (tm', ty', _) <- recheck (constraint_ns ps) (context ps) [] (forget tm) tm
1001 return (ps { done = True, pterm = mkProofTerm tm' },
1002 "Proof complete: " ++ showEnv [] tm')
1003 _ -> fail "Still holes to fill."
1004processTactic ProofState ps = return (ps, showEnv [] (getProofTerm (pterm ps)))
1005processTactic Undo ps = case previous ps of
1006 Nothing -> Error . Msg $ "Nothing to undo."
1007 Just pold -> return (pold, "")
1008processTactic EndUnify ps
1009 = let (h, ns_in) = unified ps
1010 ns = dropGiven (dontunify ps) ns_in (holes ps)
1011 ns' = map (\ (n, t) -> (n, updateSolvedTerm ns t)) ns
1012 (ns'', probs') = updateProblems ps ns' (problems ps)
1013 tm' = updateSolved ns'' (pterm ps) in
1014 traceWhen (unifylog ps) ("(EndUnify) Dropping holes: " ++ show (map fst ns'')) $
1015 return (ps { pterm = tm',
1018 notunified = updateNotunified ns'' (notunified ps),
1019 recents = recents ps ++ map fst ns'',
1020 holes = holes ps \\ map fst ns'' }, "")
1021processTactic UnifyAll ps
1022 = let tm' = updateSolved (notunified ps) (pterm ps) in
1023 return (ps { pterm = tm',
1025 recents = recents ps ++ map fst (notunified ps),
1026 holes = holes ps \\ map fst (notunified ps) }, "")
1027processTactic (Reorder n) ps
1028 = do ps' <- execStateT (tactic (Just n) reorder_claims) ps
1029 return (ps' { previous = Just ps, plog = "" }, plog ps')
1030processTactic (ComputeLet n) ps
1031 = return (ps { pterm = mkProofTerm $
1032 computeLet (context ps) n
1033 (getProofTerm (pterm ps)) }, "")
1034processTactic UnifyProblems ps
1035 = do let (ns', probs') = updateProblems ps [] (map setReady (problems ps))
1036 (pterm', dropped) = orderUpdateSolved ns' (pterm ps)
1037 traceWhen (unifylog ps) ("(UnifyProblems) Dropping holes: " ++ show dropped) $
1038 return (ps { pterm = pterm', solved = Nothing, problems = probs',
1039 previous = Just ps, plog = "",
1040 notunified = updateNotunified ns' (notunified ps),
1041 recents = recents ps ++ dropped,
1042 dotted = filter (notIn ns') (dotted ps),
1043 holes = holes ps \\ dropped }, plog ps)
1044 where notIn ns (h, _) = h `notElem` map fst ns
1045processTactic (MatchProblems all) ps
1046 = do let (ns', probs') = matchProblems all ps [] (map setReady (problems ps))
1047 (ns'', probs'') = matchProblems all ps ns' probs'
1048 (pterm', dropped) = orderUpdateSolved ns'' (resetProofTerm (pterm ps))
1049 traceWhen (unifylog ps) ("(MatchProblems) Dropping holes: " ++ show dropped) $
1050 return (ps { pterm = pterm', solved = Nothing, problems = probs'',
1051 previous = Just ps, plog = "",
1052 notunified = updateNotunified ns'' (notunified ps),
1053 recents = recents ps ++ dropped,
1054 holes = holes ps \\ dropped }, plog ps)
1058 Focus _ -> return (ps, "") -- harmless to refocus when done, since
1059 -- 'focus' doesn't fail
1060 _ -> fail $ "Proof done, nothing to run tactic on: " ++ show t ++
1061 "\n" ++ show (getProofTerm (pterm ps))
1062 (h:_) -> do ps' <- execStateT (process t h) ps
1064 = case solved ps' of
1065 Just s -> traceWhen (unifylog ps)
1066 ("SOLVED " ++ show s ++ " " ++ show (dontunify ps')) $
1067 updateProblems ps' [s] (problems ps')
1068 _ -> ([], problems ps')
1069 -- rechecking problems may find more solutions, so
1071 let ns' = dropGiven (dontunify ps') ns_in (holes ps')
1072 let pterm'' = updateSolved ns' (pterm ps')
1073 traceWhen (unifylog ps)
1074 ("Updated problems after solve " ++ qshow probs' ++ "\n" ++
1075 "(Toplevel) Dropping holes: " ++ show (map fst ns') ++ "\n" ++
1076 "Holes were: " ++ show (holes ps')) $
1077 return (ps' { pterm = pterm'',
1080 notunified = updateNotunified ns' (notunified ps'),
1081 previous = Just ps, plog = "",
1082 recents = recents ps' ++ map fst ns',
1083 holes = holes ps' \\ (map fst ns')
1086process :: Tactic -> Name -> StateT TState TC ()
1089 let (h, _) = unified ps
1090 tactic (Just h) solve_unified
1091process t h = tactic (Just h) (mktac t)
1092 where mktac Attack = attack
1093 mktac (Claim n r) = claim n r
1094 mktac (ClaimFn n bn r) = claimFn n bn r
1095 mktac (Exact r) = exact r
1096 mktac (Fill r) = fill r
1097 mktac (MatchFill r) = match_fill r
1098 mktac (PrepFill n ns) = prep_fill n ns
1099 mktac CompleteFill = complete_fill
1101 mktac (StartUnify n) = start_unify n
1102 mktac Compute = compute
1103 mktac Simplify = Idris.Core.ProofState.simplify
1104 mktac WHNF_Compute = whnf_compute
1105 mktac WHNF_ComputeArgs = whnf_compute_args
1106 mktac (Intro n) = intro n
1107 mktac (IntroTy ty n) = introTy ty n
1108 mktac (Forall n r i t) = forall n r i t
1109 mktac (LetBind n r t v) = letbind n r t v
1110 mktac (ExpandLet n b) = expandLet n b
1111 mktac (Rewrite t) = rewrite t
1112 mktac (Induction t) = casetac t True
1113 mktac (CaseTac t) = casetac t False
1114 mktac (Equiv t) = equiv t
1115 mktac (PatVar n) = patvar n
1116 mktac (PatBind n rig) = patbind n rig
1117 mktac (CheckIn r) = check_in r
1118 mktac (EvalIn r) = eval_in r
1119 mktac (Focus n) = focus n
1120 mktac (Defer ns ls n) = defer ns ls n
1121 mktac (DeferType n t a) = deferType n t a
1122 mktac (Implementation n)= implementationArg n
1123 mktac (AutoArg n) = autoArg n
1124 mktac (SetInjective n) = setinj n
1125 mktac (MoveLast n) = movelast n
1126 mktac (UnifyGoal r) = unifyGoal r
1127 mktac (UnifyTerms x y) = unifyTerms x y
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