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.
11module Core.Elaborate(module Core.Elaborate,
12 module Core.ProofState) where
20import Control.Monad.State
27-- I don't really want this here, but it's useful for the test shell
28data Command = Theorem Name Raw
34data ElabState aux = ES (ProofState, aux) String (Maybe (ElabState aux))
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
45proofFail :: Elab' aux a -> Elab' aux a
46proofFail e = do s <- get
48 OK (a, s') -> do put s'
50 Error err -> lift $ Error (ProofSearchFail err)
52saveState :: Elab' aux ()
53saveState = do e@(ES p s _) <- get
56loadState :: Elab' aux ()
57loadState = do (ES p s e) <- get
60 _ -> fail "Nothing to undo"
62erun :: FC -> Elab' aux a -> Elab' aux a
63erun f elab = do s <- get
64 case runStateT elab s of
65 OK (a, s') -> do put s'
67 Error (ProofSearchFail (At f e))
68 -> lift $ Error (ProofSearchFail (At f e))
69 Error (At f e) -> lift $ Error (At f e)
70 Error e -> lift $ Error (At f e)
72runElab :: aux -> Elab' aux a -> ProofState -> TC (a, ElabState aux)
73runElab a e ps = runStateT e (ES (ps, a) "" Nothing)
75execElab :: aux -> Elab' aux a -> ProofState -> TC (ElabState aux)
76execElab a e ps = execStateT e (ES (ps, a) "" Nothing)
78initElaborator :: Name -> Context -> Type -> ProofState
79initElaborator = newProof
81elaborate :: Context -> Name -> Type -> aux -> Elab' aux a -> TC (a, String)
82elaborate ctxt n ty d elab = do let ps = initElaborator n ctxt ty
83 (a, ES ps' str _) <- runElab d elab ps
86updateAux :: (aux -> aux) -> Elab' aux ()
87updateAux f = do ES (ps, a) l p <- get
88 put (ES (ps, f a) l p)
90getAux :: Elab' aux aux
91getAux = do ES (ps, a) _ _ <- get
94unifyLog :: Bool -> Elab' aux ()
95unifyLog log = do ES (ps, a) l p <- get
96 put (ES (ps { unifylog = log }, a) l p)
98processTactic' t = do ES (p, a) logs prev <- get
99 (p', log) <- lift $ processTactic t p
100 put (ES (p', a) (logs ++ log) prev)
103-- Some handy gadgets for pulling out bits of state
105-- get the global context
106get_context :: Elab' aux Context
107get_context = do ES p _ _ <- get
108 return (context (fst p))
111-- (should only be used for adding temporary definitions or all sorts of
112-- stuff could go wrong)
113set_context :: Context -> Elab' aux ()
114set_context ctxt = do ES (p, a) logs prev <- get
115 put (ES (p { context = ctxt }, a) logs prev)
118get_term :: Elab' aux Term
119get_term = do ES p _ _ <- get
120 return (pterm (fst p))
123update_term :: (Term -> Term) -> Elab' aux ()
124update_term f = do ES (p,a) logs prev <- get
125 let p' = p { pterm = f (pterm p) }
126 put (ES (p', a) logs prev)
128-- get the local context at the currently in focus hole
129get_env :: Elab' aux Env
130get_env = do ES p _ _ <- get
131 lift $ envAtFocus (fst p)
133get_holes :: Elab' aux [Name]
134get_holes = do ES p _ _ <- get
135 return (holes (fst p))
137get_probs :: Elab' aux Fails
138get_probs = do ES p _ _ <- get
139 return (problems (fst p))
141-- get the current goal type
142goal :: Elab' aux Type
143goal = do ES p _ _ <- get
144 b <- lift $ goalAtFocus (fst p)
147-- Get the guess at the current hole, if there is one
148get_guess :: Elab' aux Type
149get_guess = do ES p _ _ <- get
150 b <- lift $ goalAtFocus (fst p)
152 Guess t v -> return v
153 _ -> fail "Not a guess"
156get_type :: Raw -> Elab' aux Type
157get_type tm = do ctxt <- get_context
159 (val, ty) <- lift $ check ctxt env tm
162get_type_val :: Raw -> Elab' aux (Term, Type)
163get_type_val tm = do ctxt <- get_context
165 (val, ty) <- lift $ check ctxt env tm
166 return (finalise val, finalise ty)
168-- get holes we've deferred for later definition
169get_deferred :: Elab' aux [Name]
170get_deferred = do ES p _ _ <- get
171 return (deferred (fst p))
173checkInjective :: (Term, Term, Term) -> Elab' aux ()
174checkInjective (tm, l, r) = do ctxt <- get_context
175 if isInj ctxt tm then return ()
176 else lift $ tfail (NotInjective tm l r)
177 where isInj ctxt (P _ n _)
178 | isConName n ctxt = True
179 isInj ctxt (App f a) = isInj ctxt f
180 isInj ctxt (Constant _) = True
181 isInj ctxt (TType _) = True
182 isInj ctxt (Bind _ (Pi _) sc) = True
185-- get instance argument names
186get_instances :: Elab' aux [Name]
187get_instances = do ES p _ _ <- get
188 return (instances (fst p))
190-- given a desired hole name, return a unique hole name
191unique_hole = unique_hole' False
193unique_hole' :: Bool -> Name -> Elab' aux Name
194unique_hole' reusable n
196 let bs = bound_in (pterm (fst p)) ++
197 bound_in (ptype (fst p))
198 n' <- uniqueNameCtxt (context (fst p)) n (holes (fst p)
199 ++ bs ++ dontunify (fst p) ++ usedns (fst p))
201 -- Hmm: Do we need this level of uniqueness?
202 let p' = p -- if reusable then p else p { usedns = n' : usedns p }
206 bound_in (Bind n b sc) = n : bi b ++ bound_in sc
208 bi (Let t v) = bound_in t ++ bound_in v
209 bi (Guess t v) = bound_in t ++ bound_in v
210 bi b = bound_in (binderTy b)
211 bound_in (App f a) = bound_in f ++ bound_in a
214uniqueNameCtxt :: Context -> Name -> [Name] -> Elab' aux Name
215uniqueNameCtxt ctxt n hs
216 | n `elem` hs = uniqueNameCtxt ctxt (nextName n) hs
217 | [_] <- lookupTy n ctxt = uniqueNameCtxt ctxt (nextName n) hs
218 | otherwise = return n
220elog :: String -> Elab' aux ()
221elog str = do ES p logs prev <- get
222 put (ES p (logs ++ str ++ "\n") prev)
224getLog :: Elab' aux String
225getLog = do ES p logs _ <- get
228-- The primitives, from ProofState
230attack :: Elab' aux ()
231attack = processTactic' Attack
233claim :: Name -> Raw -> Elab' aux ()
234claim n t = processTactic' (Claim n t)
236exact :: Raw -> Elab' aux ()
237exact t = processTactic' (Exact t)
239fill :: Raw -> Elab' aux ()
240fill t = processTactic' (Fill t)
242match_fill :: Raw -> Elab' aux ()
243match_fill t = processTactic' (MatchFill t)
245prep_fill :: Name -> [Name] -> Elab' aux ()
246prep_fill n ns = processTactic' (PrepFill n ns)
248complete_fill :: Elab' aux ()
249complete_fill = processTactic' CompleteFill
252solve = processTactic' Solve
254start_unify :: Name -> Elab' aux ()
255start_unify n = processTactic' (StartUnify n)
257end_unify :: Elab' aux ()
258end_unify = processTactic' EndUnify
260regret :: Elab' aux ()
261regret = processTactic' Regret
263compute :: Elab' aux ()
264compute = processTactic' Compute
266hnf_compute :: Elab' aux ()
267hnf_compute = processTactic' HNF_Compute
269eval_in :: Raw -> Elab' aux ()
270eval_in t = processTactic' (EvalIn t)
272check_in :: Raw -> Elab' aux ()
273check_in t = processTactic' (CheckIn t)
275intro :: Maybe Name -> Elab' aux ()
276intro n = processTactic' (Intro n)
278introTy :: Raw -> Maybe Name -> Elab' aux ()
279introTy ty n = processTactic' (IntroTy ty n)
281forall :: Name -> Raw -> Elab' aux ()
282forall n t = processTactic' (Forall n t)
284letbind :: Name -> Raw -> Raw -> Elab' aux ()
285letbind n t v = processTactic' (LetBind n t v)
287rewrite :: Raw -> Elab' aux ()
288rewrite tm = processTactic' (Rewrite tm)
290patvar :: Name -> Elab' aux ()
291patvar n = do env <- get_env
292 if (n `elem` map fst env) then do apply (Var n) []; solve
293 else do n' <- case n of
295 MN _ _ -> unique_hole n
297 processTactic' (PatVar n')
299patbind :: Name -> Elab' aux ()
300patbind n = processTactic' (PatBind n)
302focus :: Name -> Elab' aux ()
303focus n = processTactic' (Focus n)
305movelast :: Name -> Elab' aux ()
306movelast n = processTactic' (MoveLast n)
308defer :: Name -> Elab' aux ()
309defer n = do n' <- unique_hole n
310 processTactic' (Defer n')
312deferType :: Name -> Raw -> [Name] -> Elab' aux ()
313deferType n ty ns = processTactic' (DeferType n ty ns)
315instanceArg :: Name -> Elab' aux ()
316instanceArg n = processTactic' (Instance n)
318setinj :: Name -> Elab' aux ()
319setinj n = processTactic' (SetInjective n)
321proofstate :: Elab' aux ()
322proofstate = processTactic' ProofState
324reorder_claims :: Name -> Elab' aux ()
325reorder_claims n = processTactic' (Reorder n)
328qed = do processTactic' QED
330 return (pterm (fst p))
333undo = processTactic' Undo
335prepare_apply :: Raw -> [Bool] -> Elab' aux [Name]
336prepare_apply fn imps =
340 -- let claims = getArgs ty imps
341 -- claims <- mkClaims (normalise ctxt env ty) imps []
342 claims <- mkClaims (finalise ty) imps [] (map fst env)
343 ES (p, a) s prev <- get
344 -- reverse the claims we made so that args go left to right
345 let n = length (filter not imps)
346 let (h : hs) = holes p
347 put (ES (p { holes = h : (reverse (take n hs) ++ drop n hs) }, a) s prev)
350-- (h : _) -> reorder_claims h
353 mkClaims (Bind n' (Pi t_in) sc) (i : is) claims hs =
354 do let t = rebind hs t_in
355 n <- unique_hole (mkMN n')
356-- when (null claims) (start_unify n)
357 let sc' = instantiate (P Bound n t) sc
358-- trace ("CLAIMING " ++ show (n, t) ++ " with " ++ show hs) $
361 mkClaims sc' is (n : claims) hs
362 mkClaims t [] claims _ = return (reverse claims)
365 = do ctxt <- get_context
366 case lookupTy n ctxt of
367 [] -> lift $ tfail $ NoSuchVariable n
368 _ -> fail $ "Too many arguments for " ++ show fn
369 | otherwise = fail $ "Too many arguments for " ++ show fn
371 doClaim ((i, _), n, t) = do claim n t
375 mkMN n@(UN x) = MN 1000 x
376 mkMN (NS n xs) = NS (mkMN n) xs
378 rebind hs (Bind n t sc)
379 | n `elem` hs = let n' = uniqueName n hs in
380 Bind n' (fmap (rebind hs) t) (rebind (n':hs) sc)
381 | otherwise = Bind n (fmap (rebind hs) t) (rebind (n:hs) sc)
382 rebind hs (App f a) = App (rebind hs f) (rebind hs a)
385apply, match_apply :: Raw -> [(Bool, Int)] -> Elab' aux [Name]
387match_apply = apply' match_fill
389apply' :: (Raw -> Elab' aux ()) -> Raw -> [(Bool, Int)] -> Elab' aux [Name]
390apply' fillt fn imps =
391 do args <- prepare_apply fn (map fst imps)
392 fillt (raw_apply fn (map Var args))
393 -- _Don't_ solve the arguments we're specifying by hand.
394 -- (remove from unified list before calling end_unify)
395 -- HMMM: Actually, if we get it wrong, the typechecker will complain!
399 ES (p, a) s prev <- get
400 let dont = nub $ head hs : dontunify p ++
401 if null imps then [] -- do all we can
403 map fst (filter (not.snd) (zip args (map fst imps)))
404 let (n, hunis) = -- trace ("AVOID UNIFY: " ++ show (fn, dont) ++ "\n" ++ show ptm) $
406 let unify = -- trace ("Not done " ++ show hs) $
407 dropGiven dont hunis hs
408 let notunify = -- trace ("Not done " ++ show hs) $
409 keepGiven dont hunis hs
410 put (ES (p { dontunify = dont, unified = (n, unify),
411 notunified = notunify ++ notunified p }, a) s prev)
414-- trace ("Goal " ++ show g ++ "\n" ++ show (fn, imps, unify) ++ "\n" ++ show ptm) $
417 return (map (updateUnify unify) args)
418 where updateUnify hs n = case lookup n hs of
422apply2 :: Raw -> [Maybe (Elab' aux ())] -> Elab' aux ()
424 do args <- prepare_apply fn (map isJust elabs)
425 fill (raw_apply fn (map Var args))
427 ES (p, a) s prev <- get
428 let (n, hs) = unified p
431 where elabArgs [] [] = return ()
432 elabArgs (n:ns) (Just e:es) = do focus n; e
434 elabArgs (n:ns) (_:es) = elabArgs ns es
436 isJust (Just _) = False
439apply_elab :: Name -> [Maybe (Int, Elab' aux ())] -> Elab' aux ()
441 do ty <- get_type (Var n)
444 claims <- doClaims (hnf ctxt env ty) args []
445 prep_fill n (map fst claims)
446 let eclaims = sortBy (\ (_, x) (_,y) -> priOrder x y) claims
447 elabClaims [] False claims
451 priOrder Nothing Nothing = EQ
452 priOrder Nothing _ = LT
453 priOrder _ Nothing = GT
454 priOrder (Just (x, _)) (Just (y, _)) = compare x y
456 doClaims (Bind n' (Pi t) sc) (i : is) claims =
457 do n <- unique_hole (mkMN n')
458 when (null claims) (start_unify n)
459 let sc' = instantiate (P Bound n t) sc
463 Just _ -> -- don't solve by unification as there is an explicit value
464 do ES (p, a) s prev <- get
465 put (ES (p { dontunify = n : dontunify p }, a) s prev)
466 doClaims sc' is ((n, i) : claims)
467 doClaims t [] claims = return (reverse claims)
468 doClaims _ _ _ = fail $ "Wrong number of arguments for " ++ show n
470 elabClaims failed r []
471 | null failed = return ()
472 | otherwise = if r then elabClaims [] False failed
474 elabClaims failed r ((n, Nothing) : xs) = elabClaims failed r xs
475 elabClaims failed r (e@(n, Just (_, elaboration)) : xs)
476 | r = try (do ES p _ _ <- get
477 focus n; elaboration; elabClaims failed r xs)
478 (elabClaims (e : failed) r xs)
479 | otherwise = do ES p _ _ <- get
480 focus n; elaboration; elabClaims failed r xs
483 mkMN n@(UN x) = MN 1000 x
484 mkMN (NS n ns) = NS (mkMN n) ns
486-- If the goal is not a Pi-type, invent some names and make it a pi type
487checkPiGoal :: Elab' aux ()
488checkPiGoal = do g <- goal
490 Bind _ (Pi _) _ -> return ()
491 _ -> do a <- unique_hole (MN 0 "argTy")
492 b <- unique_hole (MN 0 "retTy")
493 f <- unique_hole (MN 0 "f")
496 claim f (RBind (MN 0 "aX") (Pi (Var a)) (Var b))
503simple_app :: Elab' aux () -> Elab' aux () -> Elab' aux ()
505 do a <- unique_hole (MN 0 "argTy")
506 b <- unique_hole (MN 0 "retTy")
507 f <- unique_hole (MN 0 "f")
508 s <- unique_hole (MN 0 "s")
511 claim f (RBind (MN 0 "aX") (Pi (Var a)) (Var b))
516 -- try elaborating in both orders, since we might learn something useful
518-- try (do focus s; arg
528 -- We don't need a and b in the hole queue any more since they were just for
529 -- checking f, so discard them if they are still there. If they haven't been solved,
531 when (a `elem` hs) $ do focus a; regret
532 when (b `elem` hs) $ do focus b; regret
535-- Abstract over an argument of unknown type, giving a name for the hole
536-- which we'll fill with the argument type too.
537arg :: Name -> Name -> Elab' aux ()
538arg n tyhole = do ty <- unique_hole tyhole
542-- try a tactic, if it adds any unification problem, return an error
543no_errors :: Elab' aux () -> Elab' aux ()
548 if (length ps' > length ps) then
550 ((x,y,env,err) : _) ->
551 let env' = map (\(x, b) -> (x, binderTy b)) env in
552 lift $ tfail $ CantUnify False x y err env' 0
555-- Try a tactic, if it fails, try another
556try :: Elab' aux a -> Elab' aux a -> Elab' aux a
557try t1 t2 = try' t1 t2 False
559try' :: Elab' aux a -> Elab' aux a -> Bool -> Elab' aux a
560try' t1 t2 proofSearch
563 case prunStateT 999999 False ps t1 s of
564 OK ((v, _), s') -> do put s'
566 Error e1 -> if recoverableErr e1 then
567 do case runStateT t2 s of
568 OK (v, s') -> do put s'; return v
569 Error e2 -> if score e1 >= score e2
573 where recoverableErr err@(CantUnify r _ _ _ _ _)
574 = -- traceWhen r (show err) $
576 recoverableErr (ProofSearchFail _) = False
577 recoverableErr _ = True
579tryWhen :: Bool -> Elab' aux a -> Elab' aux a -> Elab' aux a
580tryWhen True a b = try a b
584-- Try a selection of tactics. Exactly one must work, all others must fail
585tryAll :: [(Elab' aux a, String)] -> Elab' aux a
586tryAll xs = tryAll' [] 999999 (cantResolve, 0) (map fst xs)
588 cantResolve :: Elab' aux a
589 cantResolve = lift $ tfail $ CantResolveAlts (map snd xs)
591 tryAll' :: [Elab' aux a] -> -- successes
592 Int -> -- most problems
593 (Elab' aux a, Int) -> -- smallest failure
594 [Elab' aux a] -> -- still to try
596 tryAll' [res] pmax _ [] = res
597 tryAll' (_:_) pmax _ [] = cantResolve
598 tryAll' [] pmax (f, _) [] = f
599 tryAll' cs pmax f (x:xs)
602 case prunStateT pmax True ps x s of
603 OK ((v, newps), s') ->
604 do let cs' = if (newps < pmax)
605 then [do put s'; return v]
606 else (do put s'; return v) : cs
607 tryAll' cs' newps f xs
608 Error err -> do put s
610 then tryAll' cs pmax (better err f) xs
611 else tryAll' [] pmax (better err f) xs -- give up
614 better err (f, i) = let s = score err in
615 if (s >= i) then (lift (tfail err), s)
618prunStateT pmax zok ps x s
619 = case runStateT x s of
620 OK (v, s'@(ES (p, _) _ _)) ->
621 let newps = length (problems p) - length ps
622 newpmax = if newps < 0 then 0 else newps in
623 if (newpmax > pmax || (not zok && newps > 0)) -- length ps == 0 && newpmax > 0))
624 then case reverse (problems p) of
625 ((_,_,_,e):_) -> Error e
626 else OK ((v, newpmax), s')
629qshow :: Fails -> String
630qshow fs = show (map (\ (x, y, _, _) -> (x, y)) fs)
633dumpprobs ((_,_,_,e):es) = show e ++ "\n" ++ dumpprobs es
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