1 (* Copyright (C) 2002, HELM Team.
3 * This file is part of HELM, an Hypertextual, Electronic
4 * Library of Mathematics, developed at the Computer Science
5 * Department, University of Bologna, Italy.
7 * HELM is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
12 * HELM is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with HELM; if not, write to the Free Software
19 * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
22 * For details, see the HELM World-Wide-Web page,
23 * http://cs.unibo.it/helm/.
30 module P = PrimitiveTactics
32 module CR = CicReduction
33 module PST = ProofEngineStructuralRules
34 module PET = ProofEngineTypes
35 module CTC = CicTypeChecker
37 module S = CicSubstitution
38 module RT = ReductionTactics
39 module PEH = ProofEngineHelpers
43 if debug then (fun x -> prerr_endline (Lazy.force x)) else (fun _ -> ())
46 (* funzione generale di rilocazione dei riferimenti locali *)
48 let relocate_term map t =
49 let rec map_xnss k xnss =
50 let imap (uri, t) = uri, map_term k t in
55 | Some t -> Some (map_term k t)
59 let imap (name, i, ty, bo) = name, i, map_term k ty, map_term (k + len) bo in
61 and map_cfs len k cfs =
62 let imap (name, ty, bo) = name, map_term k ty, map_term (k + len) bo in
64 and map_term k = function
65 | C.Rel m -> if m < k then C.Rel m else C.Rel (map (m - k))
67 | C.Implicit _ as t -> t
68 | C.Var (uri, xnss) -> C.Var (uri, map_xnss k xnss)
69 | C.Const (uri, xnss) -> C.Const (uri, map_xnss k xnss)
70 | C.MutInd (uri, tyno, xnss) -> C.MutInd (uri, tyno, map_xnss k xnss)
71 | C.MutConstruct (uri, tyno, consno, xnss) ->
72 C.MutConstruct (uri, tyno, consno, map_xnss k xnss)
73 | C.Meta (i, mss) -> C.Meta(i, map_mss k mss)
74 | C.Cast (te, ty) -> C.Cast (map_term k te, map_term k ty)
75 | C.Appl ts -> C.Appl (List.map (map_term k) ts)
76 | C.MutCase (sp, i, outty, t, pl) ->
77 C.MutCase (sp, i, map_term k outty, map_term k t, List.map (map_term k) pl)
78 | C.Prod (n, s, t) -> C.Prod (n, map_term k s, map_term (succ k) t)
79 | C.Lambda (n, s, t) -> C.Lambda (n, map_term k s, map_term (succ k) t)
80 | C.LetIn (n, s, t) -> C.LetIn (n, map_term k s, map_term (succ k) t)
81 | C.Fix (i, fs) -> C.Fix (i, map_fs (List.length fs) k fs)
82 | C.CoFix (i, cfs) -> C.CoFix (i, map_cfs (List.length cfs) k cfs)
88 (* term ha tipo t1=t2; funziona solo se t1 e t2 hanno in testa costruttori
91 let discriminate_tac ~term =
93 match LibraryObjects.true_URI () with
95 | None -> raise (PET.Fail (lazy "You need to register the default \"true\" definition first. Please use the \"default\" command")) in
97 match LibraryObjects.false_URI () with
99 | None -> raise (PET.Fail (lazy "You need to register the default \"false\" definition first. Please use the \"default\" command")) in
100 let fail msg = raise (PET.Fail (lazy ("Discriminate: " ^ msg))) in
101 let find_discriminating_consno t1 t2 =
104 | C.MutConstruct _, C.MutConstruct _ when t1 = t2 -> None
105 | C.Appl ((C.MutConstruct _ as constr1) :: args1),
106 C.Appl ((C.MutConstruct _ as constr2) :: args2)
107 when constr1 = constr2 ->
108 let rec aux_list l1 l2 =
111 | hd1 :: tl1, hd2 :: tl2 ->
112 (match aux hd1 hd2 with
113 | None -> aux_list tl1 tl2
114 | Some _ as res -> res)
115 | _ -> (* same constructor applied to a different number of args *)
119 | ((C.MutConstruct (_,_,consno1,subst1)),
120 (C.MutConstruct (_,_,consno2,subst2)))
121 | ((C.MutConstruct (_,_,consno1,subst1)),
122 (C.Appl ((C.MutConstruct (_,_,consno2,subst2)) :: _)))
123 | ((C.Appl ((C.MutConstruct (_,_,consno1,subst1)) :: _)),
124 (C.MutConstruct (_,_,consno2,subst2)))
125 | ((C.Appl ((C.MutConstruct (_,_,consno1,subst1)) :: _)),
126 (C.Appl ((C.MutConstruct (_,_,consno2,subst2)) :: _)))
127 when (consno1 <> consno2) || (subst1 <> subst2) ->
129 | _ -> fail "not a discriminable equality"
133 let mk_branches_and_outtype turi typeno consno context args =
134 (* a list of "True" except for the element in position consno which
136 match fst (CicEnvironment.get_obj CicUniv.empty_ugraph turi) with
137 | C.InductiveDefinition (ind_type_list,_,paramsno,_) ->
138 let _,_,rty,constructor_list = List.nth ind_type_list typeno in
139 let false_constr_id,_ = List.nth constructor_list (consno - 1) in
143 (* dubbio: e' corretto ridurre in questo context ??? *)
144 let red_ty = CR.whd context cty in
147 | C.Prod (_,_,target) when (k <= paramsno) ->
148 S.subst (List.nth args (k-1))
150 | C.Prod (binder,source,target) when (k > paramsno) ->
151 C.Lambda (binder, source, (aux target (k+1)))
153 if (id = false_constr_id)
154 then (C.MutInd(false_URI,0,[]))
155 else (C.MutInd(true_URI,0,[]))
157 (S.lift 1 (aux red_ty 1)))
161 let rec mk_lambdas rev_left_args =
163 0, args, C.Prod (_,so,ta) ->
165 (C.Name (incr seed; "x" ^ string_of_int !seed),
167 mk_lambdas rev_left_args (0,args,ta))
168 | 0, args, C.Sort _ ->
172 | n -> C.Rel n :: mk_rels (n - 1) in
173 let argsno = List.length args in
176 (if argsno + List.length rev_left_args > 0 then
178 (C.MutInd (turi, typeno, []) ::
180 (S.lift (argsno + 1))
181 (List.rev rev_left_args)) @
184 C.MutInd (turi,typeno,[])),
186 | 0, _, _ -> assert false (* seriously screwed up *)
187 | n, he::tl, C.Prod (_,_,ta) ->
188 mk_lambdas (he::rev_left_args)(n-1,tl,S.subst he ta)
190 assert false (* we should probably reduce in some context *)
192 mk_lambdas [] (paramsno, args, rty)
197 let discriminate'_tac ~term status =
198 let (proof, goal) = status in
199 let _,metasenv,_subst,_,_, _ = proof in
200 let _,context,_ = CicUtil.lookup_meta goal metasenv in
202 CTC.type_of_aux' metasenv context term CicUniv.empty_ugraph
205 | C.Appl [(C.MutInd (equri, 0, [])) ; tty ; t1 ; t2]
206 when LibraryObjects.is_eq_URI equri ->
207 let turi,typeno,exp_named_subst,args =
209 | (C.MutInd (turi,typeno,exp_named_subst)) ->
210 turi,typeno,exp_named_subst,[]
211 | (C.Appl (C.MutInd (turi,typeno,exp_named_subst)::args)) ->
212 turi,typeno,exp_named_subst,args
213 | _ -> fail "not a discriminable equality"
216 match find_discriminating_consno t1 t2 with
217 | Some consno -> consno
218 | None -> fail "discriminating terms are structurally equal"
220 let branches,outtype =
221 mk_branches_and_outtype turi typeno consno context args
225 ~start:(EliminationTactics.elim_type_tac (C.MutInd (false_URI, 0, [])))
230 ~pattern:(PET.conclusion_pattern None)
233 C.Lambda ( C.Name "x", tty,
234 C.MutCase (turi, typeno, outtype, (C.Rel 1), branches));
240 (EqualityTactics.rewrite_simpl_tac
241 ~direction:`RightToLeft
242 ~pattern:(PET.conclusion_pattern None)
245 (IntroductionTactics.constructor_tac ~n:1)))) status
246 | _ -> fail "not an equality"
248 PET.mk_tactic (discriminate'_tac ~term)
251 PET.Fail (lazy "Injection: not a projectable equality")
253 PET.Fail (lazy "Injection: not an equality")
254 let exn_nothingtodo =
255 PET.Fail (lazy "Nothing to do")
256 let exn_discrnonind =
257 PET.Fail (lazy "Discriminate: object is not an Inductive Definition: it's imposible")
258 let exn_injwronggoal =
259 PET.Fail (lazy "Injection: goal after cut is not correct")
261 PET.Fail (lazy "Injection: not an equality over elements of an inductive type")
264 let names = List.map (function Some (n,_) -> Some n | None -> None) ctx in
267 let injection_tac ~term ~i ~continuation =
268 let give_name seed = function
269 | C.Name _ as name -> name
270 | C.Anonymous -> C.Name (incr seed; "y" ^ string_of_int !seed)
272 let rec mk_rels = function | 0 -> [] | n -> C.Rel n :: (mk_rels (n - 1)) in
273 let injection_tac status =
274 let (proof, goal) = status in
275 (* precondizione: t1 e t2 hanno in testa lo stesso costruttore ma
276 * differiscono (o potrebbero differire?) nell'i-esimo parametro
278 let _,metasenv,_subst,_,_, _ = proof in
279 let _,context,_ = CicUtil.lookup_meta goal metasenv in
281 CTC.type_of_aux' metasenv context term CicUniv.empty_ugraph
283 debug_print (lazy ("\ninjection su : " ^ pp context termty));
284 match termty with (* an equality *)
285 | C.Appl [(C.MutInd (equri, 0, [])) ; tty ; t1 ; t2]
286 when LibraryObjects.is_eq_URI equri ->
287 let turi,typeno,ens,params =
288 match tty with (* some inductive type *)
289 | C.MutInd (turi,typeno,ens) -> turi,typeno,ens,[]
290 | C.Appl (C.MutInd (turi,typeno,ens)::params) -> turi,typeno,ens,params
291 | _ -> raise exn_noneqind
293 let t1',t2',consno = (* sono i due sottotermini che differiscono *)
295 | C.Appl ((C.MutConstruct (uri1,typeno1,consno1,ens1))::applist1),
296 C.Appl ((C.MutConstruct (uri2,typeno2,consno2,ens2))::applist2)
297 when (uri1 = uri2) && (typeno1 = typeno2) &&
298 (consno1 = consno2) && (ens1 = ens2) ->
299 (* controllo ridondante *)
300 List.nth applist1 (i-1),List.nth applist2 (i-1),consno2
303 let tty',_ = CTC.type_of_aux' metasenv context t1' CU.empty_ugraph in
304 let patterns,outtype =
305 match fst (CicEnvironment.get_obj CicUniv.empty_ugraph turi) with
306 | C.InductiveDefinition (ind_type_list,_,paramsno,_)->
307 let left_params, right_params = HExtlib.split_nth paramsno params in
308 let _,_,_,constructor_list = List.nth ind_type_list typeno in
309 let i_constr_id,_ = List.nth constructor_list (consno - 1) in
313 (function (id,cty) ->
314 let reduced_cty = CR.whd context cty in
315 let rec aux k = function
316 | C.Prod (_,_,tgt) when k <= paramsno ->
317 let left = List.nth left_params (k-1) in
318 aux (k+1) (S.subst left tgt)
319 | C.Prod (binder,source,target) when k > paramsno ->
320 let binder' = give_name seed binder in
321 C.Lambda (binder',source,(aux (k+1) target))
323 let nr_param_constr = k - paramsno - 1 in
324 if id = i_constr_id then C.Rel (k - i)
325 else S.lift nr_param_constr t1'
326 (* + 1 per liftare anche il lambda aggiunto
327 * esternamente al case *)
328 in S.lift 1 (aux 1 reduced_cty))
331 (* this code should be taken from cases_tac *)
334 let rec to_lambdas te head =
335 match CR.whd context te with
336 | C.Prod (binder,so,ta) ->
337 let binder' = give_name seed binder in
338 C.Lambda (binder',so,to_lambdas ta head)
341 let rec skip_prods params te =
342 match params, CR.whd context te with
344 | left::tl, C.Prod (_,_,ta) ->
345 skip_prods tl (S.subst left ta)
346 | _, _ -> assert false
350 List.fold_left (fun x y -> S.subst y x) tty left_params
352 (* non lift, ma subst coi left! *)
353 match S.lift 1 tty with
354 | C.MutInd _ as tty' -> tty'
356 let keep,abstract = HExtlib.split_nth (paramsno +1) l in
357 let keep = List.map (S.lift paramsno) keep in
358 C.Appl (keep@mk_rels (List.length abstract))
361 match ind_type_list with
364 (* this is in general wrong, do as in cases_tac *)
365 to_lambdas (skip_prods left_params ty)
367 (C.Name "cased", abstracted_tty,
368 (* here we should capture right parameters *)
369 (* 1 for his Lambda, one for the Lambda outside the match
370 * and then one for each to_lambda *)
371 S.lift (2+List.length right_params) tty'))
374 | _ -> raise exn_discrnonind
376 let cutted = C.Appl [C.MutInd (equri,0,[]) ; tty' ; t1' ; t2'] in
378 C.Appl [ C.Lambda (C.Name "x", tty,
379 C.MutCase (turi,typeno,outtype,C.Rel 1,patterns)) ; t1]
381 (* check if cutted and changed are well typed and if t1' ~ changed *)
384 let _,g = CTC.type_of_aux' metasenv context cutted
387 let _,g = CTC.type_of_aux' metasenv context changed g in
388 fst (CR.are_convertible ~metasenv context t1' changed g)
390 | CTC.TypeCheckerFailure _ -> false
393 PET.apply_tactic T.id_tac status (* FG: ??????? *)
397 debug_print (lazy "riempio il cut");
398 let (proof, goal) = status in
399 let _,metasenv,_subst,_,_, _ = proof in
400 let _,context,gty = CicUtil.lookup_meta goal metasenv in
401 let gty = Unshare.unshare gty in
402 let new_t1' = match gty with
403 | (C.Appl (C.MutInd (_,_,_)::_::t::_)) -> t
404 | _ -> raise exn_injwronggoal
406 debug_print (lazy ("metto: " ^ pp context changed));
407 debug_print (lazy ("al posto di: " ^ pp context new_t1'));
408 debug_print (lazy ("nel goal: " ^ pp context gty));
409 debug_print (lazy ("nel contesto:\n" ^ CicPp.ppcontext context));
410 debug_print (lazy ("e poi rewrite con: "^pp context term));
411 let tac = T.seq ~tactics:[
413 ~pattern:(None, [], Some (PEH.pattern_of ~term:gty [new_t1']))
414 (fun _ m u -> changed,m,u);
415 EqualityTactics.rewrite_simpl_tac
416 ~direction:`LeftToRight
417 ~pattern:(PET.conclusion_pattern None)
419 EqualityTactics.reflexivity_tac
421 PET.apply_tactic tac status
425 debug_print (lazy ("CUT: " ^ pp context cutted));
427 (T.thens ~start: (P.cut_tac cutted)
428 ~continuations:[continuation ~map:succ; tac term]
430 | _ -> raise exn_noneq
432 PET.mk_tactic injection_tac
434 let clear_term first_time context term =
435 let g () = if first_time then raise exn_nothingtodo else T.id_tac in
438 begin match List.nth context (pred n) with
439 | Some (C.Name id, _) -> PST.clear ~hyps:[id]
444 let simpl_in_term context = function
446 let name = match List.nth context (pred i) with
447 | Some (Cic.Name s, Cic.Def _) -> s
448 | Some (Cic.Name s, Cic.Decl _) -> s
451 RT.simpl_tac ~pattern:(None,[name,Cic.Implicit (Some `Hole)],None)
452 | _ -> raise exn_nonproj
454 let rec qnify_tac ~first_time ~map ~term ~continuation =
455 let are_convertible hd1 hd2 metasenv context =
456 fst (CR.are_convertible ~metasenv context hd1 hd2 CicUniv.empty_ugraph)
458 let qnify_tac status =
459 let (proof, goal) = status in
460 let _,metasenv,_subst, _,_, _ = proof in
461 let _,context,_ = CicUtil.lookup_meta goal metasenv in
462 let term = relocate_term map term in
464 CTC.type_of_aux' metasenv context term CicUniv.empty_ugraph
466 debug_print (lazy ("\nqnify su: " ^ pp context termty));
467 let tac = match termty with
468 | C.Appl [(C.MutInd (equri, 0, [])) ; tty ; t1 ; t2]
469 when LibraryObjects.is_eq_URI equri -> begin
470 match (CR.whd ~delta:true context tty) with
472 | C.Appl (C.MutInd _ :: _) ->
473 begin match t1,t2 with
477 T.then_ ~start:(clear_term first_time context term)
478 ~continuation:(continuation ~map:id)
479 | C.Appl (C.MutConstruct _ as mc1 :: applist1),
480 C.Appl (C.MutConstruct _ as mc2 :: applist2)
482 let rec traverse_list i l1 l2 = match l1, l2 with
484 T.then_ ~start:(clear_term first_time context term)
485 ~continuation:(continuation ~map:id)
486 | hd1 :: tl1, hd2 :: tl2 ->
487 if are_convertible hd1 hd2 metasenv context then
488 traverse_list (succ i) tl1 tl2
490 injection_tac ~i ~term ~continuation:
491 (qnify_tac ~first_time:false ~term ~continuation)
493 (* i 2 termini hanno in testa lo stesso costruttore,
494 * ma applicato a un numero diverso di termini *)
496 traverse_list 1 applist1 applist2
497 | C.MutConstruct (_,_,consno1,ens1),
498 C.MutConstruct (_,_,consno2,ens2)
499 | C.MutConstruct (_,_,consno1,ens1),
500 C.Appl ((C.MutConstruct (_,_,consno2,ens2))::_)
501 | C.Appl ((C.MutConstruct (_,_,consno1,ens1))::_),
502 C.MutConstruct (_,_,consno2,ens2)
503 | C.Appl ((C.MutConstruct (_,_,consno1,ens1))::_),
504 C.Appl ((C.MutConstruct (_,_,consno2,ens2))::_)
505 when (consno1 <> consno2) || (ens1 <> ens2) ->
506 discriminate_tac ~term
507 | _ when not first_time -> continuation ~map:id
508 | _ (* when first_time *) ->
509 T.then_ ~start:(simpl_in_term context term)
510 ~continuation:(qnify_tac ~first_time:false ~term ~map:id ~continuation)
512 | _ when not first_time -> continuation ~map:id
513 | _ (* when first_time *) -> raise exn_nonproj
515 | _ -> raise exn_nonproj
517 PET.apply_tactic tac status
519 PET.mk_tactic qnify_tac
521 (* destruct performs either injection or discriminate *)
522 (* equivalent to Coq's "analyze equality" *)
525 ~first_time:true ~map:id ~continuation:(fun ~map -> T.id_tac)