]> matita.cs.unibo.it Git - helm.git/blob - helm/ocaml/tactics/ring.ml
first moogle template checkin
[helm.git] / helm / ocaml / tactics / ring.ml
1 (* Copyright (C) 2002, HELM Team.
2  * 
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.
6  * 
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.
11  * 
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.
16  *
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,
20  * MA  02111-1307, USA.
21  * 
22  * For details, see the HELM World-Wide-Web page,
23  * http://cs.unibo.it/helm/.
24  *)
25
26 open CicReduction
27 open PrimitiveTactics
28 open ProofEngineTypes
29 open UriManager
30
31 open HelmLibraryObjects
32
33 (** DEBUGGING *)
34
35   (** perform debugging output? *)
36 let debug = false
37
38   (** debugging print *)
39 let warn s =
40   if debug then
41     prerr_endline ("RING WARNING: " ^ s)
42
43 (** CIC URIS *)
44
45 (**
46   Note: For constructors URIs aren't really URIs but rather triples of
47   the form (uri, typeno, consno).  This discrepancy is to preserver an
48   uniformity of invocation of "mkXXX" functions.
49 *)
50
51 let equality_is_a_congruence_A =
52  uri_of_string "cic:/Coq/Init/Logic/Logic_lemmas/equality/A.var"
53 let equality_is_a_congruence_x =
54  uri_of_string "cic:/Coq/Init/Logic/Logic_lemmas/equality/x.var"
55 let equality_is_a_congruence_y =
56  uri_of_string "cic:/Coq/Init/Logic/Logic_lemmas/equality/y.var"
57
58 let apolynomial_uri =
59   uri_of_string "cic:/Coq/ring/Ring_abstract/apolynomial.ind"
60 let apvar_uri = (apolynomial_uri, 0, 1)
61 let ap0_uri = (apolynomial_uri, 0, 2)
62 let ap1_uri = (apolynomial_uri, 0, 3)
63 let applus_uri = (apolynomial_uri, 0, 4)
64 let apmult_uri = (apolynomial_uri, 0, 5)
65 let apopp_uri = (apolynomial_uri, 0, 6)
66
67 let quote_varmap_A_uri = uri_of_string "cic:/Coq/ring/Quote/variables_map/A.var"
68 let varmap_uri = uri_of_string "cic:/Coq/ring/Quote/varmap.ind"
69 let empty_vm_uri = (varmap_uri, 0, 1)
70 let node_vm_uri = (varmap_uri, 0, 2)
71 let varmap_find_uri = uri_of_string "cic:/Coq/ring/Quote/varmap_find.con"
72 let index_uri = uri_of_string "cic:/Coq/ring/Quote/index.ind"
73 let left_idx_uri = (index_uri, 0, 1)
74 let right_idx_uri = (index_uri, 0, 2)
75 let end_idx_uri = (index_uri, 0, 3)
76
77 let abstract_rings_A_uri =
78  uri_of_string "cic:/Coq/ring/Ring_abstract/abstract_rings/A.var"
79 let abstract_rings_Aplus_uri =
80  uri_of_string "cic:/Coq/ring/Ring_abstract/abstract_rings/Aplus.var"
81 let abstract_rings_Amult_uri =
82  uri_of_string "cic:/Coq/ring/Ring_abstract/abstract_rings/Amult.var"
83 let abstract_rings_Aone_uri =
84  uri_of_string "cic:/Coq/ring/Ring_abstract/abstract_rings/Aone.var"
85 let abstract_rings_Azero_uri =
86  uri_of_string "cic:/Coq/ring/Ring_abstract/abstract_rings/Azero.var"
87 let abstract_rings_Aopp_uri =
88  uri_of_string "cic:/Coq/ring/Ring_abstract/abstract_rings/Aopp.var"
89 let abstract_rings_Aeq_uri =
90  uri_of_string "cic:/Coq/ring/Ring_abstract/abstract_rings/Aeq.var"
91 let abstract_rings_vm_uri =
92  uri_of_string "cic:/Coq/ring/Ring_abstract/abstract_rings/vm.var"
93 let abstract_rings_T_uri =
94  uri_of_string "cic:/Coq/ring/Ring_abstract/abstract_rings/T.var"
95 let interp_ap_uri = uri_of_string "cic:/Coq/ring/Ring_abstract/interp_ap.con"
96 let interp_sacs_uri =
97   uri_of_string "cic:/Coq/ring/Ring_abstract/interp_sacs.con"
98 let apolynomial_normalize_uri =
99   uri_of_string "cic:/Coq/ring/Ring_abstract/apolynomial_normalize.con"
100 let apolynomial_normalize_ok_uri =
101   uri_of_string "cic:/Coq/ring/Ring_abstract/apolynomial_normalize_ok.con"
102
103 (** CIC PREDICATES *)
104
105   (**
106     check whether a term is a constant or not, if argument "uri" is given and is
107     not "None" also check if the constant correspond to the given one or not
108   *)
109 let cic_is_const ?(uri: uri option = None) term =
110   match uri with
111   | None ->
112       (match term with
113         | Cic.Const _ -> true
114         | _ -> false)
115   | Some realuri ->
116       (match term with
117         | Cic.Const (u, _) when (eq u realuri) -> true
118         | _ -> false)
119
120 (** PROOF AND GOAL ACCESSORS *)
121
122   (**
123     @param proof a proof
124     @return the uri of a given proof
125   *)
126 let uri_of_proof ~proof:(uri, _, _, _) = uri
127
128   (**
129     @param status current proof engine status
130     @raise Failure if proof is None
131     @return current goal's metasenv
132   *)
133 let metasenv_of_status ((_,m,_,_), _) = m
134
135   (**
136     @param status a proof engine status
137     @raise Failure when proof or goal are None
138     @return context corresponding to current goal
139   *)
140 let context_of_status status =
141   let (proof, goal) = status in
142   let metasenv = metasenv_of_status status in
143   let _, context, _ = CicUtil.lookup_meta goal metasenv in
144    context
145
146 (** CIC TERM CONSTRUCTORS *)
147
148   (**
149     Create a Cic term consisting of a constant
150     @param uri URI of the constant
151     @proof current proof
152     @exp_named_subst explicit named substitution
153   *)
154 let mkConst ~uri ~exp_named_subst =
155   Cic.Const (uri, exp_named_subst)
156
157   (**
158     Create a Cic term consisting of a constructor
159     @param uri triple <uri, typeno, consno> where uri is the uri of an inductive
160     type, typeno is the type number in a mutind structure (0 based), consno is
161     the constructor number (1 based)
162     @exp_named_subst explicit named substitution
163   *)
164 let mkCtor ~uri:(uri, typeno, consno) ~exp_named_subst =
165  Cic.MutConstruct (uri, typeno, consno, exp_named_subst)
166
167   (**
168     Create a Cic term consisting of a type member of a mutual induction
169     @param uri pair <uri, typeno> where uri is the uri of a mutual inductive
170     type and typeno is the type number (0 based) in the mutual induction
171     @exp_named_subst explicit named substitution
172   *)
173 let mkMutInd ~uri:(uri, typeno) ~exp_named_subst =
174  Cic.MutInd (uri, typeno, exp_named_subst)
175
176 (** EXCEPTIONS *)
177
178   (**
179     raised when the current goal is not ringable; a goal is ringable when is an
180     equality on reals (@see r_uri)
181   *)
182 exception GoalUnringable
183
184 (** RING's FUNCTIONS LIBRARY *)
185
186   (**
187     Check whether the ring tactic can be applied on a given term (i.e. that is
188     an equality on reals)
189     @param term to be tested
190     @return true if the term is ringable, false otherwise
191   *)
192 let ringable =
193   let is_equality = function
194     | Cic.MutInd (uri, 0, []) when (eq uri Logic.eq_URI) -> true
195     | _ -> false
196   in
197   let is_real = function
198     | Cic.Const (uri, _) when (eq uri Reals.r_URI) -> true
199     | _ -> false
200   in
201   function
202     | Cic.Appl (app::set::_::_::[]) when (is_equality app && is_real set) ->
203         warn "Goal Ringable!";
204         true
205     | _ ->
206         warn "Goal Not Ringable :-((";
207         false
208
209   (**
210     split an equality goal of the form "t1 = t2" in its two subterms t1 and t2
211     after checking that the goal is ringable
212     @param goal the current goal
213     @return a pair (t1,t2) that are two sides of the equality goal
214     @raise GoalUnringable if the goal isn't ringable
215   *)
216 let split_eq = function
217   | (Cic.Appl (_::_::t1::t2::[])) as term when ringable term ->
218         warn ("<term1>" ^ (CicPp.ppterm t1) ^ "</term1>");
219         warn ("<term2>" ^ (CicPp.ppterm t2) ^ "</term2>");
220         (t1, t2)
221   | _ -> raise GoalUnringable
222
223   (**
224     @param i an integer index representing a 1 based number of node in a binary
225     search tree counted in a fbs manner (i.e.: 1 is the root, 2 is the left
226     child of the root (if any), 3 is the right child of the root (if any), 4 is
227     the left child of the left child of the root (if any), ....)
228     @param proof the current proof
229     @return an index representing the same node in a varmap (@see varmap_uri),
230     the returned index is as defined in index (@see index_uri)
231   *)
232 let path_of_int n =
233   let rec digits_of_int n =
234     if n=1 then [] else (n mod 2 = 1)::(digits_of_int (n lsr 1))
235   in
236   List.fold_right
237     (fun digit path ->
238       Cic.Appl [
239         mkCtor (if (digit = true) then right_idx_uri else left_idx_uri) [];
240         path])
241     (List.rev (digits_of_int n)) (* remove leading true (i.e. digit 1) *)
242     (mkCtor end_idx_uri [])
243
244   (**
245     Build a variable map (@see varmap_uri) from a variables array.
246     A variable map is almost a binary tree so this function receiving a var list
247     like [v;w;x;y;z] will build a varmap of shape:       v
248                                                         / \
249                                                        w   x
250                                                       / \
251                                                      y   z
252     @param vars variables array
253     @return a cic term representing the variable map containing vars variables
254   *)
255 let btree_of_array ~vars =
256   let r = Reals.r in
257   let empty_vm_r = mkCtor empty_vm_uri [quote_varmap_A_uri,r] in
258   let node_vm_r = mkCtor node_vm_uri [quote_varmap_A_uri,r] in
259   let size = Array.length vars in
260   let halfsize = size lsr 1 in
261   let rec aux n =   (* build the btree starting from position n *)
262       (*
263         n is the position in the vars array _1_based_ in order to access
264         left and right child using (n*2, n*2+1) trick
265       *)
266     if n > size then
267       empty_vm_r
268     else if n > halfsize then  (* no more children *)
269       Cic.Appl [node_vm_r; vars.(n-1); empty_vm_r; empty_vm_r]
270     else  (* still children *)
271       Cic.Appl [node_vm_r; vars.(n-1); aux (n*2); aux (n*2+1)]
272   in
273   aux 1
274
275   (**
276     abstraction function:
277     concrete polynoms       ----->      (abstract polynoms, varmap)
278     @param terms list of conrete polynoms
279     @return a pair <aterms, varmap> where aterms is a list of abstract polynoms
280     and varmap is the variable map needed to interpret them
281   *)
282 let abstract_poly ~terms =
283   let varhash = Hashtbl.create 19 in (* vars hash, to speed up lookup *)
284   let varlist = ref [] in  (* vars list in reverse order *)
285   let counter = ref 1 in  (* index of next new variable *)
286   let rec aux = function  (* TODO not tail recursive *)
287     (* "bop" -> binary operator | "uop" -> unary operator *)
288     | Cic.Appl (bop::t1::t2::[])
289       when (cic_is_const ~uri:(Some Reals.rplus_URI) bop) -> (* +. *)
290         Cic.Appl [mkCtor applus_uri []; aux t1; aux t2]
291     | Cic.Appl (bop::t1::t2::[])
292       when (cic_is_const ~uri:(Some Reals.rmult_URI) bop) -> (* *. *)
293         Cic.Appl [mkCtor apmult_uri []; aux t1; aux t2]
294     | Cic.Appl (uop::t::[])
295       when (cic_is_const ~uri:(Some Reals.ropp_URI) uop) -> (* ~-. *)
296         Cic.Appl [mkCtor apopp_uri []; aux t]
297     | t when (cic_is_const ~uri:(Some Reals.r0_URI) t) -> (* 0. *)
298         mkCtor ap0_uri []
299     | t when (cic_is_const ~uri:(Some Reals.r1_URI) t) -> (* 1. *)
300         mkCtor ap1_uri []
301     | t ->  (* variable *)
302       try
303         Hashtbl.find varhash t (* use an old var *)
304       with Not_found -> begin (* create a new var *)
305         let newvar =
306           Cic.Appl [mkCtor apvar_uri []; path_of_int !counter]
307         in
308         incr counter;
309         varlist := t :: !varlist;
310         Hashtbl.add varhash t newvar;
311         newvar
312       end
313   in
314   let aterms = List.map aux terms in  (* abstract vars *)
315   let varmap =  (* build varmap *)
316     btree_of_array ~vars:(Array.of_list (List.rev !varlist))
317   in
318   (aterms, varmap)
319
320   (**
321     given a list of abstract terms (i.e. apolynomials) build the ring "segments"
322     that is triples like (t', t'', t''') where
323           t'    = interp_ap(varmap, at)
324           t''   = interp_sacs(varmap, (apolynomial_normalize at))
325           t'''  = apolynomial_normalize_ok(varmap, at)
326     at is the abstract term built from t, t is a single member of aterms
327   *)
328 let build_segments ~terms =
329   let theory_args_subst varmap =
330    [abstract_rings_A_uri, Reals.r ;
331     abstract_rings_Aplus_uri, Reals.rplus ;
332     abstract_rings_Amult_uri, Reals.rmult ;
333     abstract_rings_Aone_uri, Reals.r1 ;
334     abstract_rings_Azero_uri, Reals.r0 ;
335     abstract_rings_Aopp_uri, Reals.ropp ;
336     abstract_rings_vm_uri, varmap] in
337   let theory_args_subst' eq varmap t =
338    [abstract_rings_A_uri, Reals.r ;
339     abstract_rings_Aplus_uri, Reals.rplus ;
340     abstract_rings_Amult_uri, Reals.rmult ;
341     abstract_rings_Aone_uri, Reals.r1 ;
342     abstract_rings_Azero_uri, Reals.r0 ;
343     abstract_rings_Aopp_uri, Reals.ropp ;
344     abstract_rings_Aeq_uri, eq ;
345     abstract_rings_vm_uri, varmap ;
346     abstract_rings_T_uri, t] in
347   let interp_ap varmap =
348    mkConst interp_ap_uri (theory_args_subst varmap) in
349   let interp_sacs varmap =
350    mkConst interp_sacs_uri (theory_args_subst varmap) in
351   let apolynomial_normalize = mkConst apolynomial_normalize_uri [] in
352   let apolynomial_normalize_ok eq varmap t =
353    mkConst apolynomial_normalize_ok_uri (theory_args_subst' eq varmap t) in
354   let lxy_false =   (** Cic funcion "fun (x,y):R -> false" *)
355     Cic.Lambda (Cic.Anonymous, Reals.r,
356       Cic.Lambda (Cic.Anonymous, Reals.r, Datatypes.falseb))
357   in
358   let (aterms, varmap) = abstract_poly ~terms in  (* abstract polys *)
359   List.map    (* build ring segments *)
360    (fun t ->
361      Cic.Appl [interp_ap varmap ; t],
362      Cic.Appl (
363        [interp_sacs varmap ; Cic.Appl [apolynomial_normalize; t]]),
364      Cic.Appl [apolynomial_normalize_ok lxy_false varmap Reals.rtheory ; t]
365    ) aterms
366
367
368 let status_of_single_goal_tactic_result =
369  function
370     proof,[goal] -> proof,goal
371   | _ ->
372     raise (Fail "status_of_single_goal_tactic_result: the tactic did not produce exactly a new goal")
373
374 (* Galla: spostata in variousTactics.ml 
375   (**
376     auxiliary tactic "elim_type"
377     @param status current proof engine status
378     @param term term to cut
379   *)
380 let elim_type_tac ~term status =
381   warn "in Ring.elim_type_tac";
382   Tacticals.thens ~start:(cut_tac ~term)
383    ~continuations:[elim_simpl_intros_tac ~term:(Cic.Rel 1) ; Tacticals.id_tac] status
384 *)
385
386   (**
387     auxiliary tactic, use elim_type and try to close 2nd subgoal using proof
388     @param status current proof engine status
389     @param term term to cut
390     @param proof term used to prove second subgoal generated by elim_type
391   *)
392 let elim_type2_tac ~term ~proof status =
393   let module E = EliminationTactics in
394   warn "in Ring.elim_type2";
395   Tacticals.thens ~start:(E.elim_type_tac ~term)
396    ~continuations:[Tacticals.id_tac ; exact_tac ~term:proof] status
397
398 (* Galla: spostata in variousTactics.ml
399   (**
400     Reflexivity tactic, try to solve current goal using "refl_eqT"
401     Warning: this isn't equale to the coq's Reflexivity because this one tries
402     only refl_eqT, coq's one also try "refl_equal"
403     @param status current proof engine status
404   *)
405 let reflexivity_tac (proof, goal) =
406   warn "in Ring.reflexivity_tac";
407   let refl_eqt = mkCtor ~uri:refl_eqt_uri ~exp_named_subst:[] in
408   try
409     apply_tac (proof, goal) ~term:refl_eqt
410   with (Fail _) as e ->
411     let e_str = Printexc.to_string e in
412     raise (Fail ("Reflexivity failed with exception: " ^ e_str))
413 *)
414
415   (** lift an 8-uple of debrujins indexes of n *)
416 let lift ~n (a,b,c,d,e,f,g,h) =
417   match (List.map (CicSubstitution.lift n) [a;b;c;d;e;f;g;h]) with
418   | [a;b;c;d;e;f;g;h] -> (a,b,c,d,e,f,g,h)
419   | _ -> assert false
420
421   (**
422     remove hypothesis from a given status starting from the last one
423     @param count number of hypotheses to remove
424     @param status current proof engine status
425   *)
426 let purge_hyps_tac ~count status =
427   let module S = ProofEngineStructuralRules in
428   let (proof, goal) = status in
429   let rec aux n context status =
430     assert(n>=0);
431     match (n, context) with
432     | (0, _) -> status
433     | (n, hd::tl) ->
434         aux (n-1) tl
435          (status_of_single_goal_tactic_result (S.clear ~hyp:hd status))
436     | (_, []) -> failwith "Ring.purge_hyps_tac: no hypotheses left"
437   in
438    let (_, metasenv, _, _) = proof in
439     let (_, context, _) = CicUtil.lookup_meta goal metasenv in
440      let proof',goal' = aux count context status in
441       assert (goal = goal') ;
442       proof',[goal']
443
444 (** THE TACTIC! *)
445
446   (**
447     Ring tactic, does associative and commutative rewritings in Reals ring
448     @param status current proof engine status
449   *)
450 let ring_tac status =
451   let (proof, goal) = status in
452   warn "in Ring tactic";
453   let eqt = mkMutInd (Logic.eq_URI, 0) [] in
454   let r = Reals.r in
455   let metasenv = metasenv_of_status status in
456   let (metano, context, ty) = CicUtil.lookup_meta goal metasenv in
457   let (t1, t2) = split_eq ty in (* goal like t1 = t2 *)
458   match (build_segments ~terms:[t1; t2]) with
459   | (t1', t1'', t1'_eq_t1'')::(t2', t2'', t2'_eq_t2'')::[] -> begin
460       List.iter  (* debugging, feel free to remove *)
461         (fun (descr, term) ->
462           warn (descr ^ " " ^ (CicPp.ppterm term)))
463         (List.combine
464           ["t1"; "t1'"; "t1''"; "t1'_eq_t1''";
465            "t2"; "t2'"; "t2''"; "t2'_eq_t2''"]
466           [t1; t1'; t1''; t1'_eq_t1'';
467            t2; t2'; t2''; t2'_eq_t2'']);
468       try
469         let new_hyps = ref 0 in  (* number of new hypotheses created *)
470         Tacticals.try_tactics
471           status
472           ~tactics:[
473             "reflexivity", EqualityTactics.reflexivity_tac ;
474             "exact t1'_eq_t1''", exact_tac ~term:t1'_eq_t1'' ;
475             "exact t2'_eq_t2''", exact_tac ~term:t2'_eq_t2'' ;
476             "exact sym_eqt su t1 ...", exact_tac
477             ~term:(
478               Cic.Appl
479                [mkConst Logic.sym_eq_URI
480                  [equality_is_a_congruence_A, Reals.r;
481                   equality_is_a_congruence_x, t1'' ;
482                   equality_is_a_congruence_y, t1
483                  ] ;
484                 t1'_eq_t1''
485                ]) ;
486             "elim_type eqt su t1 ...", (fun status ->
487               let status' = (* status after 1st elim_type use *)
488                 let context = context_of_status status in
489                 if not (are_convertible context t1'' t1) then begin
490                   warn "t1'' and t1 are NOT CONVERTIBLE";
491                   let newstatus =
492                     elim_type2_tac  (* 1st elim_type use *)
493                       status ~proof:t1'_eq_t1''
494                       ~term:(Cic.Appl [eqt; r; t1''; t1])
495                   in
496                    incr new_hyps; (* elim_type add an hyp *)
497                    match newstatus with
498                       (proof,[goal]) -> proof,goal
499                     | _ -> assert false
500                 end else begin
501                   warn "t1'' and t1 are CONVERTIBLE";
502                   status
503                 end
504               in
505               let (t1,t1',t1'',t1'_eq_t1'',t2,t2',t2'',t2'_eq_t2'') =
506                 lift 1 (t1,t1',t1'',t1'_eq_t1'', t2,t2',t2'',t2'_eq_t2'')
507               in
508               let status'' =
509                 Tacticals.try_tactics (* try to solve 1st subgoal *)
510                   status'
511                   ~tactics:[
512                     "exact t2'_eq_t2''", exact_tac ~term:t2'_eq_t2'';
513                     "exact sym_eqt su t2 ...",
514                       exact_tac
515                        ~term:(
516                          Cic.Appl
517                           [mkConst Logic.sym_eq_URI
518                             [equality_is_a_congruence_A, Reals.r;
519                              equality_is_a_congruence_x, t2'' ;
520                              equality_is_a_congruence_y, t2
521                             ] ;
522                            t2'_eq_t2''
523                           ]) ;
524                     "elim_type eqt su t2 ...", (fun status ->
525                       let status' =
526                         let context = context_of_status status in
527                         if not (are_convertible context t2'' t2) then begin
528                           warn "t2'' and t2 are NOT CONVERTIBLE";
529                           let newstatus =
530                             elim_type2_tac  (* 2nd elim_type use *)
531                               status ~proof:t2'_eq_t2''
532                               ~term:(Cic.Appl [eqt; r; t2''; t2])
533                           in
534                           incr new_hyps; (* elim_type add an hyp *)
535                           match newstatus with
536                              (proof,[goal]) -> proof,goal
537                            | _ -> assert false
538                         end else begin
539                           warn "t2'' and t2 are CONVERTIBLE";
540                           status
541                         end
542                       in
543                       try (* try to solve main goal *)
544                         warn "trying reflexivity ....";
545                         EqualityTactics.reflexivity_tac status'
546                       with (Fail _) ->  (* leave conclusion to the user *)
547                         warn "reflexivity failed, solution's left as an ex :-)";
548                         purge_hyps_tac ~count:!new_hyps status')]
549               in
550               status'')]
551       with (Fail s) ->
552         raise (Fail ("Ring failure: " ^ s))
553     end
554   | _ -> (* impossible: we are applying ring exacty to 2 terms *)
555     assert false
556
557   (* wrap ring_tac catching GoalUnringable and raising Fail *)
558 let ring_tac status =
559   try
560     ring_tac status
561   with GoalUnringable ->
562     raise (Fail "goal unringable")
563