on d9c3c21 help sign in
Idris-dev/src/Core/Elaborate.hs
655 lines 23 kB history raw
1{-# LANGUAGE MultiParamTypeClasses, FlexibleInstances, PatternGuards #-}
3{- A high level language of tactic composition, for building
4 elaborators from a high level language into the core theory.
6 This is our interface to proof construction, rather than
7 ProofState, because this gives us a language to build derived
8 tactics out of the primitives.
9-}
11module Core.Elaborate(module Core.Elaborate,
12 module Core.ProofState) where
14import Core.ProofState
15import Core.TT
16import Core.Evaluate
17import Core.Typecheck
18import Core.Unify
20import Control.Monad.State
21import Data.Char
22import Data.List
23import Debug.Trace
25import Util.Pretty
27-- I don't really want this here, but it's useful for the test shell
28data Command = Theorem Name Raw
29 | Eval Raw
30 | Quit
31 | Print Name
32 | Tac (Elab ())
34data ElabState aux = ES (ProofState, aux) String (Maybe (ElabState aux))
35 deriving Show
37type Elab' aux a = StateT (ElabState aux) TC a
38type Elab a = Elab' () a
40proof :: ElabState aux -> ProofState
41proof (ES (p, _) _ _) = p
43-- Insert a 'proofSearchFail' error if necessary to shortcut any further
44-- fruitless searching
45proofFail :: Elab' aux a -> Elab' aux a
46proofFail e = do s <- get
47 case runStateT e s of
48 OK (a, s') -> do put s'
49 return a
50 Error err -> lift $ Error (ProofSearchFail err)
52saveState :: Elab' aux ()
53saveState = do e@(ES p s _) <- get
54 put (ES p s (Just e))
56loadState :: Elab' aux ()
57loadState = do (ES p s e) <- get
58 case e of
59 Just st -> put st
60 _ -> fail "Nothing to undo"
62errAt :: String -> Name -> Elab' aux a -> Elab' aux a
63errAt thing n elab = do s <- get
64 case runStateT elab s of
65 OK (a, s') -> do put s'
66 return a
67 Error (At f e) ->
68 lift $ Error (At f (Elaborating thing n e))
69 Error e -> lift $ Error (Elaborating thing n e)
71erun :: FC -> Elab' aux a -> Elab' aux a
72erun f elab = do s <- get
73 case runStateT elab s of
74 OK (a, s') -> do put s'
75 return a
76 Error (ProofSearchFail (At f e))
77 -> lift $ Error (ProofSearchFail (At f e))
78 Error (At f e) -> lift $ Error (At f e)
79 Error e -> lift $ Error (At f e)
81runElab :: aux -> Elab' aux a -> ProofState -> TC (a, ElabState aux)
82runElab a e ps = runStateT e (ES (ps, a) "" Nothing)
84execElab :: aux -> Elab' aux a -> ProofState -> TC (ElabState aux)
85execElab a e ps = execStateT e (ES (ps, a) "" Nothing)
87initElaborator :: Name -> Context -> Type -> ProofState
88initElaborator = newProof
90elaborate :: Context -> Name -> Type -> aux -> Elab' aux a -> TC (a, String)
91elaborate ctxt n ty d elab = do let ps = initElaborator n ctxt ty
92 (a, ES ps' str _) <- runElab d elab ps
93 return (a, str)
95updateAux :: (aux -> aux) -> Elab' aux ()
96updateAux f = do ES (ps, a) l p <- get
97 put (ES (ps, f a) l p)
99getAux :: Elab' aux aux
100getAux = do ES (ps, a) _ _ <- get
101 return a
103unifyLog :: Bool -> Elab' aux ()
104unifyLog log = do ES (ps, a) l p <- get
105 put (ES (ps { unifylog = log }, a) l p)
107processTactic' t = do ES (p, a) logs prev <- get
108 (p', log) <- lift $ processTactic t p
109 put (ES (p', a) (logs ++ log) prev)
110 return ()
112-- Some handy gadgets for pulling out bits of state
114-- get the global context
115get_context :: Elab' aux Context
116get_context = do ES p _ _ <- get
117 return (context (fst p))
119-- update the context
120-- (should only be used for adding temporary definitions or all sorts of
121-- stuff could go wrong)
122set_context :: Context -> Elab' aux ()
123set_context ctxt = do ES (p, a) logs prev <- get
124 put (ES (p { context = ctxt }, a) logs prev)
126-- get the proof term
127get_term :: Elab' aux Term
128get_term = do ES p _ _ <- get
129 return (pterm (fst p))
131-- get the proof term
132update_term :: (Term -> Term) -> Elab' aux ()
133update_term f = do ES (p,a) logs prev <- get
134 let p' = p { pterm = f (pterm p) }
135 put (ES (p', a) logs prev)
137-- get the local context at the currently in focus hole
138get_env :: Elab' aux Env
139get_env = do ES p _ _ <- get
140 lift $ envAtFocus (fst p)
142get_holes :: Elab' aux [Name]
143get_holes = do ES p _ _ <- get
144 return (holes (fst p))
146get_probs :: Elab' aux Fails
147get_probs = do ES p _ _ <- get
148 return (problems (fst p))
150-- get the current goal type
151goal :: Elab' aux Type
152goal = do ES p _ _ <- get
153 b <- lift $ goalAtFocus (fst p)
154 return (binderTy b)
156-- Get the guess at the current hole, if there is one
157get_guess :: Elab' aux Type
158get_guess = do ES p _ _ <- get
159 b <- lift $ goalAtFocus (fst p)
160 case b of
161 Guess t v -> return v
162 _ -> fail "Not a guess"
164-- typecheck locally
165get_type :: Raw -> Elab' aux Type
166get_type tm = do ctxt <- get_context
167 env <- get_env
168 (val, ty) <- lift $ check ctxt env tm
169 return (finalise ty)
171get_type_val :: Raw -> Elab' aux (Term, Type)
172get_type_val tm = do ctxt <- get_context
173 env <- get_env
174 (val, ty) <- lift $ check ctxt env tm
175 return (finalise val, finalise ty)
177-- get holes we've deferred for later definition
178get_deferred :: Elab' aux [Name]
179get_deferred = do ES p _ _ <- get
180 return (deferred (fst p))
182checkInjective :: (Term, Term, Term) -> Elab' aux ()
183checkInjective (tm, l, r) = do ctxt <- get_context
184 if isInj ctxt tm then return ()
185 else lift $ tfail (NotInjective tm l r)
186 where isInj ctxt (P _ n _)
187 | isConName n ctxt = True
188 isInj ctxt (App f a) = isInj ctxt f
189 isInj ctxt (Constant _) = True
190 isInj ctxt (TType _) = True
191 isInj ctxt (Bind _ (Pi _) sc) = True
192 isInj ctxt _ = False
194-- get instance argument names
195get_instances :: Elab' aux [Name]
196get_instances = do ES p _ _ <- get
197 return (instances (fst p))
199-- given a desired hole name, return a unique hole name
200unique_hole = unique_hole' False
202unique_hole' :: Bool -> Name -> Elab' aux Name
203unique_hole' reusable n
204 = do ES p _ _ <- get
205 let bs = bound_in (pterm (fst p)) ++
206 bound_in (ptype (fst p))
207 n' <- uniqueNameCtxt (context (fst p)) n (holes (fst p)
208 ++ bs ++ dontunify (fst p) ++ usedns (fst p))
209 ES (p, a) s u <- get
210 -- Hmm: Do we need this level of uniqueness?
211 let p' = p -- if reusable then p else p { usedns = n' : usedns p }
212 put (ES (p', a) s u)
213 return n'
214 where
215 bound_in (Bind n b sc) = n : bi b ++ bound_in sc
216 where
217 bi (Let t v) = bound_in t ++ bound_in v
218 bi (Guess t v) = bound_in t ++ bound_in v
219 bi b = bound_in (binderTy b)
220 bound_in (App f a) = bound_in f ++ bound_in a
221 bound_in _ = []
223uniqueNameCtxt :: Context -> Name -> [Name] -> Elab' aux Name
224uniqueNameCtxt ctxt n hs
225 | n `elem` hs = uniqueNameCtxt ctxt (nextName n) hs
226 | [_] <- lookupTy n ctxt = uniqueNameCtxt ctxt (nextName n) hs
227 | otherwise = return n
229elog :: String -> Elab' aux ()
230elog str = do ES p logs prev <- get
231 put (ES p (logs ++ str ++ "\n") prev)
233getLog :: Elab' aux String
234getLog = do ES p logs _ <- get
235 return logs
237-- The primitives, from ProofState
239attack :: Elab' aux ()
240attack = processTactic' Attack
242claim :: Name -> Raw -> Elab' aux ()
243claim n t = processTactic' (Claim n t)
245exact :: Raw -> Elab' aux ()
246exact t = processTactic' (Exact t)
248fill :: Raw -> Elab' aux ()
249fill t = processTactic' (Fill t)
251match_fill :: Raw -> Elab' aux ()
252match_fill t = processTactic' (MatchFill t)
254prep_fill :: Name -> [Name] -> Elab' aux ()
255prep_fill n ns = processTactic' (PrepFill n ns)
257complete_fill :: Elab' aux ()
258complete_fill = processTactic' CompleteFill
260solve :: Elab' aux ()
261solve = processTactic' Solve
263start_unify :: Name -> Elab' aux ()
264start_unify n = processTactic' (StartUnify n)
266end_unify :: Elab' aux ()
267end_unify = processTactic' EndUnify
269regret :: Elab' aux ()
270regret = processTactic' Regret
272compute :: Elab' aux ()
273compute = processTactic' Compute
275computeLet :: Name -> Elab' aux ()
276computeLet n = processTactic' (ComputeLet n)
278simplify :: Elab' aux ()
279simplify = processTactic' Simplify
281hnf_compute :: Elab' aux ()
282hnf_compute = processTactic' HNF_Compute
284eval_in :: Raw -> Elab' aux ()
285eval_in t = processTactic' (EvalIn t)
287check_in :: Raw -> Elab' aux ()
288check_in t = processTactic' (CheckIn t)
290intro :: Maybe Name -> Elab' aux ()
291intro n = processTactic' (Intro n)
293introTy :: Raw -> Maybe Name -> Elab' aux ()
294introTy ty n = processTactic' (IntroTy ty n)
296forall :: Name -> Raw -> Elab' aux ()
297forall n t = processTactic' (Forall n t)
299letbind :: Name -> Raw -> Raw -> Elab' aux ()
300letbind n t v = processTactic' (LetBind n t v)
302expandLet :: Name -> Term -> Elab' aux ()
303expandLet n v = processTactic' (ExpandLet n v)
305rewrite :: Raw -> Elab' aux ()
306rewrite tm = processTactic' (Rewrite tm)
308equiv :: Raw -> Elab' aux ()
309equiv tm = processTactic' (Equiv tm)
311patvar :: Name -> Elab' aux ()
312patvar n = do env <- get_env
313 if (n `elem` map fst env) then do apply (Var n) []; solve
314 else do n' <- case n of
315 UN _ -> return n
316 MN _ _ -> unique_hole n
317 NS _ _ -> return n
318 processTactic' (PatVar n')
320patbind :: Name -> Elab' aux ()
321patbind n = processTactic' (PatBind n)
323focus :: Name -> Elab' aux ()
324focus n = processTactic' (Focus n)
326movelast :: Name -> Elab' aux ()
327movelast n = processTactic' (MoveLast n)
329defer :: Name -> Elab' aux ()
330defer n = do n' <- unique_hole n
331 processTactic' (Defer n')
333deferType :: Name -> Raw -> [Name] -> Elab' aux ()
334deferType n ty ns = processTactic' (DeferType n ty ns)
336instanceArg :: Name -> Elab' aux ()
337instanceArg n = processTactic' (Instance n)
339setinj :: Name -> Elab' aux ()
340setinj n = processTactic' (SetInjective n)
342proofstate :: Elab' aux ()
343proofstate = processTactic' ProofState
345reorder_claims :: Name -> Elab' aux ()
346reorder_claims n = processTactic' (Reorder n)
348qed :: Elab' aux Term
349qed = do processTactic' QED
350 ES p _ _ <- get
351 return (pterm (fst p))
353undo :: Elab' aux ()
354undo = processTactic' Undo
356prepare_apply :: Raw -> [Bool] -> Elab' aux [Name]
357prepare_apply fn imps =
358 do ty <- get_type fn
359 ctxt <- get_context
360 env <- get_env
361 -- let claims = getArgs ty imps
362 -- claims <- mkClaims (normalise ctxt env ty) imps []
363 claims <- mkClaims (finalise ty) imps [] (map fst env)
364 ES (p, a) s prev <- get
365 -- reverse the claims we made so that args go left to right
366 let n = length (filter not imps)
367 let (h : hs) = holes p
368 put (ES (p { holes = h : (reverse (take n hs) ++ drop n hs) }, a) s prev)
369-- case claims of
370-- [] -> return ()
371-- (h : _) -> reorder_claims h
372 return claims
373 where
374 mkClaims (Bind n' (Pi t_in) sc) (i : is) claims hs =
375 do let t = rebind hs t_in
376 n <- unique_hole (mkMN n')
377-- when (null claims) (start_unify n)
378 let sc' = instantiate (P Bound n t) sc
379-- trace ("CLAIMING " ++ show (n, t) ++ " with " ++ show hs) $
380 claim n (forget t)
381 when i (movelast n)
382 mkClaims sc' is (n : claims) hs
383 mkClaims t [] claims _ = return (reverse claims)
384 mkClaims _ _ _ _
385 | Var n <- fn
386 = do ctxt <- get_context
387 case lookupTy n ctxt of
388 [] -> lift $ tfail $ NoSuchVariable n
389 _ -> fail $ "Too many arguments for " ++ show fn
390 | otherwise = fail $ "Too many arguments for " ++ show fn
392 doClaim ((i, _), n, t) = do claim n t
393 when i (movelast n)
395 mkMN n@(MN _ _) = n
396 mkMN n@(UN x) = MN 1000 x
397 mkMN n@(SN s) = MN 1000 (show s)
398 mkMN (NS n xs) = NS (mkMN n) xs
400 rebind hs (Bind n t sc)
401 | n `elem` hs = let n' = uniqueName n hs in
402 Bind n' (fmap (rebind hs) t) (rebind (n':hs) sc)
403 | otherwise = Bind n (fmap (rebind hs) t) (rebind (n:hs) sc)
404 rebind hs (App f a) = App (rebind hs f) (rebind hs a)
405 rebind hs t = t
407apply, match_apply :: Raw -> [(Bool, Int)] -> Elab' aux [Name]
408apply = apply' fill
409match_apply = apply' match_fill
411apply' :: (Raw -> Elab' aux ()) -> Raw -> [(Bool, Int)] -> Elab' aux [Name]
412apply' fillt fn imps =
413 do args <- prepare_apply fn (map fst imps)
414 env <- get_env
415 g <- goal
416 fillt (raw_apply fn (map Var args))
417 -- _Don't_ solve the arguments we're specifying by hand.
418 -- (remove from unified list before calling end_unify)
419 -- HMMM: Actually, if we get it wrong, the typechecker will complain!
420 -- so do nothing
421 ptm <- get_term
422 hs <- get_holes
423 ES (p, a) s prev <- get
424 let dont = nub $ head hs : dontunify p ++
425 if null imps then [] -- do all we can
426 else
427 map fst (filter (not.snd) (zip args (map fst imps)))
428 let (n, hunis) = -- trace ("AVOID UNIFY: " ++ show (fn, dont) ++ "\n" ++ show ptm) $
429 unified p
430 let unify = -- trace ("Not done " ++ show hs) $
431 dropGiven dont hunis hs
432 let notunify = -- trace ("Not done " ++ show hs) $
433 keepGiven dont hunis hs
434 put (ES (p { dontunify = dont, unified = (n, unify),
435 notunified = notunify ++ notunified p }, a) s prev)
436 ptm <- get_term
437 g <- goal
438-- trace ("Goal " ++ show g ++ "\n" ++ show (fn, imps, unify) ++ "\n" ++ show ptm) $
439 end_unify
440 ptm <- get_term
441 return (map (updateUnify unify) args)
442 where updateUnify hs n = case lookup n hs of
443 Just (P _ t _) -> t
444 _ -> n
446apply2 :: Raw -> [Maybe (Elab' aux ())] -> Elab' aux ()
447apply2 fn elabs =
448 do args <- prepare_apply fn (map isJust elabs)
449 fill (raw_apply fn (map Var args))
450 elabArgs args elabs
451 ES (p, a) s prev <- get
452 let (n, hs) = unified p
453 end_unify
454 solve
455 where elabArgs [] [] = return ()
456 elabArgs (n:ns) (Just e:es) = do focus n; e
457 elabArgs ns es
458 elabArgs (n:ns) (_:es) = elabArgs ns es
460 isJust (Just _) = False
461 isJust _ = True
463apply_elab :: Name -> [Maybe (Int, Elab' aux ())] -> Elab' aux ()
464apply_elab n args =
465 do ty <- get_type (Var n)
466 ctxt <- get_context
467 env <- get_env
468 claims <- doClaims (hnf ctxt env ty) args []
469 prep_fill n (map fst claims)
470 let eclaims = sortBy (\ (_, x) (_,y) -> priOrder x y) claims
471 elabClaims [] False claims
472 complete_fill
473 end_unify
474 where
475 priOrder Nothing Nothing = EQ
476 priOrder Nothing _ = LT
477 priOrder _ Nothing = GT
478 priOrder (Just (x, _)) (Just (y, _)) = compare x y
480 doClaims (Bind n' (Pi t) sc) (i : is) claims =
481 do n <- unique_hole (mkMN n')
482 when (null claims) (start_unify n)
483 let sc' = instantiate (P Bound n t) sc
484 claim n (forget t)
485 case i of
486 Nothing -> return ()
487 Just _ -> -- don't solve by unification as there is an explicit value
488 do ES (p, a) s prev <- get
489 put (ES (p { dontunify = n : dontunify p }, a) s prev)
490 doClaims sc' is ((n, i) : claims)
491 doClaims t [] claims = return (reverse claims)
492 doClaims _ _ _ = fail $ "Wrong number of arguments for " ++ show n
494 elabClaims failed r []
495 | null failed = return ()
496 | otherwise = if r then elabClaims [] False failed
497 else return ()
498 elabClaims failed r ((n, Nothing) : xs) = elabClaims failed r xs
499 elabClaims failed r (e@(n, Just (_, elaboration)) : xs)
500 | r = try (do ES p _ _ <- get
501 focus n; elaboration; elabClaims failed r xs)
502 (elabClaims (e : failed) r xs)
503 | otherwise = do ES p _ _ <- get
504 focus n; elaboration; elabClaims failed r xs
506 mkMN n@(MN _ _) = n
507 mkMN n@(UN x) = MN 1000 x
508 mkMN (NS n ns) = NS (mkMN n) ns
510-- If the goal is not a Pi-type, invent some names and make it a pi type
511checkPiGoal :: Name -> Elab' aux ()
512checkPiGoal n
513 = do g <- goal
514 case g of
515 Bind _ (Pi _) _ -> return ()
516 _ -> do a <- unique_hole (MN 0 "pargTy")
517 b <- unique_hole (MN 0 "pretTy")
518 f <- unique_hole (MN 0 "pf")
519 claim a RType
520 claim b RType
521 claim f (RBind n (Pi (Var a)) (Var b))
522 movelast a
523 movelast b
524 fill (Var f)
525 solve
526 focus f
528simple_app :: Elab' aux () -> Elab' aux () -> String -> Elab' aux ()
529simple_app fun arg appstr =
530 do a <- unique_hole (MN 0 "argTy")
531 b <- unique_hole (MN 0 "retTy")
532 f <- unique_hole (MN 0 "f")
533 s <- unique_hole (MN 0 "s")
534 claim a RType
535 claim b RType
536 claim f (RBind (MN 0 "aX") (Pi (Var a)) (Var b))
537 tm <- get_term
538 start_unify s
539 claim s (Var a)
540 prep_fill f [s]
541 focus f; fun
542 focus s; arg
543 tm <- get_term
544 ps <- get_probs
545 complete_fill
546 hs <- get_holes
547 env <- get_env
548 -- We don't need a and b in the hole queue any more since they were
549 -- just for checking f, so discard them if they are still there.
550 -- If they haven't been solved, regret will fail
551 when (a `elem` hs) $ do focus a; regretWith (CantInferType appstr)
552 when (b `elem` hs) $ do focus b; regretWith (CantInferType appstr)
553 end_unify
554 where regretWith err = try regret
555 (lift $ tfail err)
557-- Abstract over an argument of unknown type, giving a name for the hole
558-- which we'll fill with the argument type too.
559arg :: Name -> Name -> Elab' aux ()
560arg n tyhole = do ty <- unique_hole tyhole
561 claim ty RType
562 forall n (Var ty)
564-- try a tactic, if it adds any unification problem, return an error
565no_errors :: Elab' aux () -> Elab' aux ()
566no_errors tac
567 = do ps <- get_probs
568 tac
569 ps' <- get_probs
570 if (length ps' > length ps) then
571 case reverse ps' of
572 ((x,y,env,err) : _) ->
573 let env' = map (\(x, b) -> (x, binderTy b)) env in
574 lift $ tfail $ CantUnify False x y err env' 0
575 else return ()
577-- Try a tactic, if it fails, try another
578try :: Elab' aux a -> Elab' aux a -> Elab' aux a
579try t1 t2 = try' t1 t2 False
581try' :: Elab' aux a -> Elab' aux a -> Bool -> Elab' aux a
582try' t1 t2 proofSearch
583 = do s <- get
584 ps <- get_probs
585 case prunStateT 999999 False ps t1 s of
586 OK ((v, _), s') -> do put s'
587 return v
588 Error e1 -> if recoverableErr e1 then
589 do case runStateT t2 s of
590 OK (v, s') -> do put s'; return v
591 Error e2 -> if score e1 >= score e2
592 then lift (tfail e1)
593 else lift (tfail e2)
594 else lift (tfail e1)
595 where recoverableErr err@(CantUnify r _ _ _ _ _)
596 = -- traceWhen r (show err) $
597 r || proofSearch
598 recoverableErr (ProofSearchFail _) = False
599 recoverableErr _ = True
601tryWhen :: Bool -> Elab' aux a -> Elab' aux a -> Elab' aux a
602tryWhen True a b = try a b
603tryWhen False a b = a
606-- Try a selection of tactics. Exactly one must work, all others must fail
607tryAll :: [(Elab' aux a, String)] -> Elab' aux a
608tryAll xs = tryAll' [] 999999 (cantResolve, 0) (map fst xs)
609 where
610 cantResolve :: Elab' aux a
611 cantResolve = lift $ tfail $ CantResolveAlts (map snd xs)
613 tryAll' :: [Elab' aux a] -> -- successes
614 Int -> -- most problems
615 (Elab' aux a, Int) -> -- smallest failure
616 [Elab' aux a] -> -- still to try
617 Elab' aux a
618 tryAll' [res] pmax _ [] = res
619 tryAll' (_:_) pmax _ [] = cantResolve
620 tryAll' [] pmax (f, _) [] = f
621 tryAll' cs pmax f (x:xs)
622 = do s <- get
623 ps <- get_probs
624 case prunStateT pmax True ps x s of
625 OK ((v, newps), s') ->
626 do let cs' = if (newps < pmax)
627 then [do put s'; return v]
628 else (do put s'; return v) : cs
629 tryAll' cs' newps f xs
630 Error err -> do put s
631 if (score err) < 100
632 then tryAll' cs pmax (better err f) xs
633 else tryAll' [] pmax (better err f) xs -- give up
636 better err (f, i) = let s = score err in
637 if (s >= i) then (lift (tfail err), s)
638 else (f, i)
640prunStateT pmax zok ps x s
641 = case runStateT x s of
642 OK (v, s'@(ES (p, _) _ _)) ->
643 let newps = length (problems p) - length ps
644 newpmax = if newps < 0 then 0 else newps in
645 if (newpmax > pmax || (not zok && newps > 0)) -- length ps == 0 && newpmax > 0))
646 then case reverse (problems p) of
647 ((_,_,_,e):_) -> Error e
648 else OK ((v, newpmax), s')
649 Error e -> Error e
651qshow :: Fails -> String
652qshow fs = show (map (\ (x, y, _, _) -> (x, y)) fs)
654dumpprobs [] = ""
655dumpprobs ((_,_,_,e):es) = show e ++ "\n" ++ dumpprobs es