]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/tactics/auto.ml
commented some printings
[helm.git] / helm / software / components / tactics / auto.ml
1 (* Copyright (C) 2002, HELM Team.
2
3  * 
4  * This file is part of HELM, an Hypertextual, Electronic
5  * Library of Mathematics, developed at the Computer Science
6  * Department, University of Bologna, Italy.
7  * 
8  * HELM is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU General Public License
10  * as published by the Free Software Foundation; either version 2
11  * of the License, or (at your option) any later version.
12  * 
13  * HELM is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16  * GNU General Public License for more details.
17  *
18  * You should have received a copy of the GNU General Public License
19  * along with HELM; if not, write to the Free Software
20  * Foundation, Inc., 59 Temple Place - Suite 330, Boston,
21  * MA  02111-1307, USA.
22  * 
23  * For details, see the HELM World-Wide-Web page,
24  * http://cs.unibo.it/helm/.
25  *)
26
27 open AutoTypes;;
28 open AutoCache;;
29
30 let debug = false;;
31 let debug_print s = 
32   if debug then prerr_endline (Lazy.force s);;
33
34
35 let is_propositional context sort = 
36   match CicReduction.whd context sort with
37   | Cic.Sort Cic.Prop 
38   | Cic.Sort (Cic.CProp _) -> true
39   | _-> false
40 ;;
41
42
43 type auto_params = Cic.term list * (string * string) list 
44
45 let elems = ref [] ;;
46
47 (* closing a term w.r.t. its metavariables
48    very naif version: it does not take dependencies properly into account *)
49
50 let naif_closure ?(prefix_name="xxx_") t metasenv context =
51   let metasenv = ProofEngineHelpers.sort_metasenv metasenv in
52   let n = List.length metasenv in
53   let what = List.map (fun (i,cc,ty) -> Cic.Meta(i,[])) metasenv in
54   let _,with_what =
55     List.fold_left
56       (fun (i,acc) (_,cc,ty) -> (i-1,Cic.Rel i::acc)) 
57       (n,[]) metasenv 
58   in
59   let t = CicSubstitution.lift n t in
60   let body =
61     ProofEngineReduction.replace_lifting 
62       ~equality:(fun c t1 t2 ->
63          match t1,t2 with
64          | Cic.Meta(i,_),Cic.Meta(j,_) -> i = j
65          | _ -> false) 
66       ~context ~what ~with_what ~where:t 
67   in
68   let _, t =
69     List.fold_left
70       (fun (n,t) (_,cc,ty) -> 
71         n-1, Cic.Lambda(Cic.Name (prefix_name^string_of_int n),
72                CicSubstitution.lift n ty,t))
73       (n-1,body) metasenv 
74   in
75   t
76 ;;
77
78 let lambda_close ?prefix_name t menv ctx =
79   let t = naif_closure ?prefix_name t menv ctx in
80     List.fold_left
81       (fun (t,i) -> function 
82         | None -> CicSubstitution.subst (Cic.Implicit None) t,i (* delift *)
83         | Some (name, Cic.Decl ty) -> Cic.Lambda (name, ty, t),i+1
84         | Some (name, Cic.Def (bo, ty)) -> Cic.LetIn (name, bo, ty, t),i+1)
85       (t,List.length menv) ctx
86 ;;
87   
88 (* functions for retrieving theorems *)
89
90 exception FillingFailure of AutoCache.cache * int
91
92 let rec unfold context = function
93   | Cic.Prod(name,s,t) -> 
94       let t' = unfold ((Some (name,Cic.Decl s))::context) t in
95         Cic.Prod(name,s,t')        
96   | t -> ProofEngineReduction.unfold context t
97
98 let find_library_theorems dbd proof goal = 
99   let univ = MetadataQuery.universe_of_goal ~dbd false proof goal in
100   let terms = List.map CicUtil.term_of_uri univ in
101   List.map 
102     (fun t -> 
103        (t,fst(CicTypeChecker.type_of_aux' [] [] t CicUniv.oblivion_ugraph))) 
104     terms
105
106 let find_context_theorems context metasenv =
107   let l,_ =
108     List.fold_left
109       (fun (res,i) ctxentry ->
110          match ctxentry with
111            | Some (_,Cic.Decl t) -> 
112                (Cic.Rel i, CicSubstitution.lift i t)::res,i+1
113            | Some (_,Cic.Def (_,t)) ->
114                (Cic.Rel i, CicSubstitution.lift i t)::res,i+1
115            | None -> res,i+1)
116       ([],1) context
117   in l
118
119 let rec is_an_equality = function
120   | Cic.Appl [Cic.MutInd (uri, _, _); _; _; _] 
121     when (LibraryObjects.is_eq_URI uri) -> true
122   | Cic.Prod (_, _, t) -> is_an_equality t
123   | _ -> false
124 ;;
125
126 let partition_equalities =
127   List.partition (fun (_,ty) -> is_an_equality ty)
128
129
130 let default_auto maxm _ _ cache _ _ _ _ = [],cache,maxm ;; 
131
132 (* giusto per provare che succede 
133 let is_unit_equation context metasenv oldnewmeta term =
134   let head, metasenv, args, newmeta =
135     TermUtil.saturate_term oldnewmeta metasenv context term 0
136   in
137   let newmetas = 
138     List.filter (fun (i,_,_) -> i >= oldnewmeta) metasenv 
139   in
140     Some (args,metasenv,newmetas,head,newmeta) *)
141
142 let is_unit_equation context metasenv oldnewmeta term = 
143   let head, metasenv, args, newmeta =
144     TermUtil.saturate_term oldnewmeta metasenv context term 0
145   in
146   let propositional_args = 
147     HExtlib.filter_map
148       (function 
149       | Cic.Meta(i,_) -> 
150           let _,_,mt = CicUtil.lookup_meta i metasenv in
151           let sort,u = 
152             CicTypeChecker.type_of_aux' metasenv context mt 
153               CicUniv.oblivion_ugraph
154           in
155           if is_propositional context sort then Some i else None 
156       | _ -> assert false)
157     args
158   in
159     if propositional_args = [] then 
160       let newmetas = 
161         List.filter (fun (i,_,_) -> i >= oldnewmeta) metasenv 
162       in
163         Some (args,metasenv,newmetas,head,newmeta)
164     else None
165 ;;
166
167 let get_candidates skip_trie_filtering universe cache t =
168   let t = if skip_trie_filtering then Cic.Meta(0,[]) else t in
169   let candidates= 
170     (Universe.get_candidates universe t)@(AutoCache.get_candidates cache t)
171   in 
172   let debug_msg =
173     (lazy ("candidates for " ^ (CicPp.ppterm t) ^ " = " ^ 
174              (String.concat "\n" (List.map CicPp.ppterm candidates)))) in
175   debug_print debug_msg;
176   candidates
177 ;;
178
179 let only signature context metasenv t =
180   try
181     let ty,_ = 
182       CicTypeChecker.type_of_aux' metasenv context t CicUniv.oblivion_ugraph 
183     in
184     let consts = MetadataConstraints.constants_of ty in
185     let b = MetadataConstraints.UriManagerSet.subset consts signature in
186 (*     if b then (prerr_endline ("keeping " ^ (CicPp.ppterm t)); b)  *)
187     if b then b 
188     else
189       let ty' = unfold context ty in
190       let consts' = MetadataConstraints.constants_of ty' in
191       let b = MetadataConstraints.UriManagerSet.subset consts' signature  in
192 (*
193         if not b then prerr_endline ("filtering " ^ (CicPp.ppterm t))
194         else prerr_endline ("keeping " ^ (CicPp.ppterm t)); 
195 *)
196       b
197   with 
198   | CicTypeChecker.TypeCheckerFailure _ -> assert false
199   | ProofEngineTypes.Fail _ -> false (* unfold may fail *)
200 ;;
201
202 let not_default_eq_term t =
203   try
204     let uri = CicUtil.uri_of_term t in
205       not (LibraryObjects.in_eq_URIs uri)
206   with Invalid_argument _ -> true
207
208 let retrieve_equations dont_filter signature universe cache context metasenv =
209   match LibraryObjects.eq_URI() with
210     | None -> [] 
211     | Some eq_uri -> 
212         let eq_uri = UriManager.strip_xpointer eq_uri in
213         let fake= Cic.Meta(-1,[]) in
214         let fake_eq = Cic.Appl [Cic.MutInd (eq_uri,0, []);fake;fake;fake] in
215         let candidates = get_candidates false universe cache fake_eq in
216         if dont_filter then candidates
217         else let eq_uri = UriManager.uri_of_uriref eq_uri 0 None in
218           (* let candidates = List.filter not_default_eq_term candidates in *)
219           List.filter 
220             (only (MetadataConstraints.UriManagerSet.add eq_uri signature) 
221                context metasenv) candidates 
222
223 let build_equality bag head args proof newmetas maxmeta = 
224   match head with
225   | Cic.Appl [Cic.MutInd (uri, _, _); ty; t1; t2] ->
226       let p =
227         if args = [] then proof else Cic.Appl (proof::args)
228       in 
229       let o = !Utils.compare_terms t1 t2 in
230       let stat = (ty,t1,t2,o) in
231       (* let w = compute_equality_weight stat in *)
232       let w = 0 in 
233       let proof = Equality.Exact p in
234       let e = Equality.mk_equality bag (w, proof, stat, newmetas) in
235       (* to clean the local context of metas *)
236       Equality.fix_metas bag maxmeta e
237   | _ -> assert false
238 ;;
239
240 let partition_unit_equalities context metasenv newmeta bag equations =
241   List.fold_left
242     (fun (units,other,maxmeta)(t,ty) ->
243        if not (CicUtil.is_meta_closed t && CicUtil.is_meta_closed ty) then
244          let _ = 
245            HLog.warn 
246            ("Skipping " ^ CicMetaSubst.ppterm_in_context ~metasenv [] t context
247              ^ " since it is not meta closed")
248          in
249          units,(t,ty)::other,maxmeta
250        else
251        match is_unit_equation context metasenv maxmeta ty with
252          | Some (args,metasenv,newmetas,head,newmeta') ->
253              let maxmeta,equality =
254                build_equality bag head args t newmetas newmeta' in
255              equality::units,other,maxmeta
256          | None -> 
257              units,(t,ty)::other,maxmeta)
258     ([],[],newmeta) equations
259
260 let empty_tables = 
261   (Saturation.make_active [], 
262    Saturation.make_passive [],
263    Equality.mk_equality_bag)
264
265
266 let init_cache_and_tables 
267   ?dbd use_library paramod use_context dont_filter universe (proof, goal) 
268 =
269   (* the local cache in initially empty  *)
270   let cache = AutoCache.cache_empty in
271   let _, metasenv, _subst,_, _, _ = proof in
272   let signature = MetadataQuery.signature_of metasenv goal in
273   let newmeta = CicMkImplicit.new_meta metasenv [] in
274   let _,context,_ = CicUtil.lookup_meta goal metasenv in
275   let ct = if use_context then find_context_theorems context metasenv else [] in
276   debug_print 
277     (lazy ("ho trovato nel contesto " ^ (string_of_int (List.length ct))));
278   let lt = 
279     match use_library, dbd with
280     | true, Some dbd -> find_library_theorems dbd metasenv goal 
281     | _ -> []
282   in
283   debug_print 
284     (lazy ("ho trovato nella libreria " ^ (string_of_int (List.length lt))));
285   let cache = cache_add_list cache context (ct@lt) in  
286   let equations = 
287     retrieve_equations dont_filter (* true *) signature universe cache context metasenv 
288   in
289   debug_print 
290     (lazy ("ho trovato equazioni n. "^(string_of_int (List.length equations))));
291   let eqs_and_types =
292     HExtlib.filter_map 
293       (fun t -> 
294          let ty,_ =
295            CicTypeChecker.type_of_aux' 
296              metasenv context t CicUniv.oblivion_ugraph
297          in
298          (* retrieve_equations could also return flexible terms *)
299          if is_an_equality ty then Some(t,ty) 
300          else
301            try
302              let ty' = unfold context ty in
303              if is_an_equality ty' then Some(t,ty') else None
304            with ProofEngineTypes.Fail _ -> None) 
305       equations
306   in
307   let bag = Equality.mk_equality_bag () in
308   let units, other_equalities, newmeta = 
309     partition_unit_equalities context metasenv newmeta bag eqs_and_types 
310   in
311   (* SIMPLIFICATION STEP 
312   let equalities = 
313     let env = (metasenv, context, CicUniv.oblivion_ugraph) in 
314     let eq_uri = HExtlib.unopt (LibraryObjects.eq_URI()) in
315     Saturation.simplify_equalities bag eq_uri env units 
316   in 
317   *)
318   let passive = Saturation.make_passive units in
319   let no = List.length units in
320   let active = Saturation.make_active [] in
321   let active,passive,newmeta = 
322     if paramod then active,passive,newmeta
323     else
324       Saturation.pump_actives 
325         context bag newmeta active passive (no+1) infinity
326   in 
327     (active,passive,bag),cache,newmeta
328
329 let fill_hypothesis context metasenv oldnewmeta term tables (universe:Universe.universe) cache auto fast = 
330   let head, metasenv, args, newmeta =
331     TermUtil.saturate_term oldnewmeta metasenv context term 0
332   in
333   let propositional_args = 
334     HExtlib.filter_map
335       (function 
336       | Cic.Meta(i,_) -> 
337           let _,_,mt = CicUtil.lookup_meta i metasenv in
338           let sort,u = 
339             CicTypeChecker.type_of_aux' metasenv context mt 
340               CicUniv.oblivion_ugraph
341           in
342           if is_propositional context sort then Some i else None 
343       | _ -> assert false)
344     args
345   in
346   let results,cache,newmeta = 
347     if propositional_args = [] then 
348       let newmetas = List.filter (fun (i,_,_) -> i >= oldnewmeta) metasenv in
349       [args,metasenv,newmetas,head,newmeta],cache,newmeta
350     else
351       (*
352       let proof = 
353         None,metasenv,term,term (* term non e' significativo *)
354       in *)
355       let flags = 
356         if fast then
357           {AutoTypes.default_flags() with 
358            AutoTypes.timeout = Unix.gettimeofday() +. 1.0;
359            maxwidth = 2;maxdepth = 2;
360            use_paramod=true;use_only_paramod=false}
361         else
362           {AutoTypes.default_flags() with
363            AutoTypes.timeout = Unix.gettimeofday() +. 1.0;
364            maxwidth = 2;maxdepth = 4;
365            use_paramod=true;use_only_paramod=false} 
366       in
367       match auto newmeta tables universe cache context metasenv propositional_args flags with
368       | [],cache,newmeta -> raise (FillingFailure (cache,newmeta))
369       | substs,cache,newmeta ->
370           List.map 
371             (fun subst ->
372               let metasenv = 
373                 CicMetaSubst.apply_subst_metasenv subst metasenv
374               in
375               let head = CicMetaSubst.apply_subst subst head in
376               let newmetas = 
377                 List.filter (fun (i,_,_) ->i >= oldnewmeta) metasenv 
378               in
379               let args = List.map (CicMetaSubst.apply_subst subst) args in
380               let newm = CicMkImplicit.new_meta metasenv subst in
381                 args,metasenv,newmetas,head,max newm newmeta)
382             substs, cache, newmeta
383   in
384   results,cache,newmeta
385
386 let build_equalities auto context metasenv tables universe cache newmeta equations =
387   List.fold_left 
388     (fun (facts,cache,newmeta) (t,ty) ->
389        (* in any case we add the equation to the cache *)
390        let cache = AutoCache.cache_add_list cache context [(t,ty)] in
391        try
392          let saturated,cache,newmeta = 
393            fill_hypothesis context metasenv newmeta ty tables universe cache auto true
394          in
395          let (active,passive,bag) = tables in
396          let eqs,bag,newmeta = 
397            List.fold_left 
398              (fun (acc,bag,newmeta) (args,metasenv,newmetas,head,newmeta') ->
399                 let maxmeta,equality =
400                   build_equality bag head args t newmetas newmeta'
401                 in
402                   equality::acc,bag,maxmeta)
403              ([],bag,newmeta) saturated
404          in
405            (eqs@facts, cache, newmeta)
406        with FillingFailure (cache,newmeta) ->
407          (* if filling hypothesis fails we add the equation to
408             the cache *)
409          (facts,cache,newmeta)
410       )
411     ([],cache,newmeta) equations
412
413 let close_more tables maxmeta context status auto universe cache =
414   let (active,passive,bag) = tables in
415   let proof, goalno = status in
416   let _, metasenv,_subst,_,_, _ = proof in  
417   let signature = MetadataQuery.signature_of metasenv goalno in
418   let equations = 
419     retrieve_equations false signature universe cache context metasenv 
420   in
421   let eqs_and_types =
422     HExtlib.filter_map 
423       (fun t -> 
424          let ty,_ =
425            CicTypeChecker.type_of_aux' metasenv context t
426            CicUniv.oblivion_ugraph in
427            (* retrieve_equations could also return flexible terms *)
428            if is_an_equality ty then Some(t,ty) else None)
429       equations in
430   let units, cache, maxm = 
431       build_equalities auto context metasenv tables universe cache maxmeta eqs_and_types in
432   debug_print (lazy (">>>>>>> gained from a new context saturation >>>>>>>>>" ^
433     string_of_int maxm));
434   List.iter
435     (fun e -> debug_print (lazy (Equality.string_of_equality e))) 
436     units;
437   debug_print (lazy ">>>>>>>>>>>>>>>>>>>>>>");
438   let passive = Saturation.add_to_passive units passive in
439   let no = List.length units in
440   debug_print (lazy ("No = " ^ (string_of_int no)));
441   let active,passive,newmeta = 
442     Saturation.pump_actives context bag maxm active passive (no+1) infinity
443   in 
444     (active,passive,bag),cache,newmeta
445
446 let find_context_equalities 
447   maxmeta bag context proof (universe:Universe.universe) cache 
448 =
449   let module C = Cic in
450   let module S = CicSubstitution in
451   let module T = CicTypeChecker in
452   let _,metasenv,_subst,_,_, _ = proof in
453   let newmeta = max (ProofEngineHelpers.new_meta_of_proof ~proof) maxmeta in
454   (* if use_auto is true, we try to close the hypothesis of equational
455     statements using auto; a naif, and probably wrong approach *)
456   let rec aux cache index newmeta = function
457     | [] -> [], newmeta,cache
458     | (Some (_, C.Decl (term)))::tl ->
459         debug_print
460           (lazy
461              (Printf.sprintf "Examining: %d (%s)" index (CicPp.ppterm term)));
462         let do_find context term =
463           match term with
464           | C.Prod (name, s, t) when is_an_equality t ->
465               (try 
466                 
467                 let term = S.lift index term in
468                 let saturated,cache,newmeta = 
469                   fill_hypothesis context metasenv newmeta term 
470                     empty_tables universe cache default_auto false
471                 in
472                 let eqs,newmeta = 
473                   List.fold_left 
474                    (fun (acc,newmeta) (args,metasenv,newmetas,head,newmeta') ->
475                      let newmeta, equality = 
476                        build_equality
477                          bag head args (Cic.Rel index) newmetas (max newmeta newmeta')
478                      in
479                      equality::acc, newmeta + 1)
480                    ([],newmeta) saturated
481                 in
482                  eqs, newmeta, cache
483               with FillingFailure (cache,newmeta) ->
484                 [],newmeta,cache)
485           | C.Appl [C.MutInd (uri, _, _); ty; t1; t2]
486               when LibraryObjects.is_eq_URI uri ->
487               let term = S.lift index term in
488               let newmeta, e = 
489                 build_equality bag term [] (Cic.Rel index) [] newmeta
490               in
491               [e], (newmeta+1),cache
492           | _ -> [], newmeta, cache
493         in 
494         let eqs, newmeta, cache = do_find context term in
495         let rest, newmeta,cache = aux cache (index+1) newmeta tl in
496         List.map (fun x -> index,x) eqs @ rest, newmeta, cache
497     | _::tl ->
498         aux cache (index+1) newmeta tl
499   in
500   let il, maxm, cache = 
501     aux cache 1 newmeta context 
502   in
503   let indexes, equalities = List.split il in
504   indexes, equalities, maxm, cache
505 ;;
506
507 (********** PARAMETERS PASSING ***************)
508
509 let bool params name default =
510     try 
511       let s = List.assoc name params in 
512       if s = "" || s = "1" || s = "true" || s = "yes" || s = "on" then true
513       else if s = "0" || s = "false" || s = "no" || s= "off" then false
514       else 
515         let msg = "Unrecognized value for parameter "^name^"\n" in
516         let msg = msg^"Accepted values are 1,true,yes,on and 0,false,no,off" in
517         raise (ProofEngineTypes.Fail (lazy msg))
518     with Not_found -> default
519 ;; 
520
521 let string params name default =
522     try List.assoc name params with
523     | Not_found -> default
524 ;; 
525
526 let int params name default =
527     try int_of_string (List.assoc name params) with
528     | Not_found -> default
529     | Failure _ -> 
530         raise (ProofEngineTypes.Fail (lazy (name ^ " must be an integer")))
531 ;;  
532
533 let flags_of_params params ?(for_applyS=false) () =
534  let int = int params in
535  let bool = bool params in
536  let close_more = bool "close_more" false in
537  let use_paramod = bool "use_paramod" true in
538  let skip_trie_filtering = bool "skip_trie_filtering" false in
539  let skip_context = bool "skip_context" false in
540  let use_only_paramod =
541   if for_applyS then true else bool "paramodulation" false in
542  let use_library = bool "library"  
543    ((AutoTypes.default_flags()).AutoTypes.use_library) in
544  let depth = int "depth" ((AutoTypes.default_flags()).AutoTypes.maxdepth) in
545  let width = int "width" ((AutoTypes.default_flags()).AutoTypes.maxwidth) in
546  let size = int "size" ((AutoTypes.default_flags()).AutoTypes.maxsize) in
547  let gsize = int "gsize" ((AutoTypes.default_flags()).AutoTypes.maxgoalsizefactor) in
548  let do_type = bool "type" false in
549  let timeout = int "timeout" 0 in
550   { AutoTypes.maxdepth = 
551       if use_only_paramod then 2 else depth;
552     AutoTypes.maxwidth = width;
553     AutoTypes.maxsize = size;
554     AutoTypes.timeout = 
555       if timeout = 0 then
556        if for_applyS then Unix.gettimeofday () +. 30.0
557        else
558          infinity
559       else
560        Unix.gettimeofday() +. (float_of_int timeout);
561     AutoTypes.use_library = use_library; 
562     AutoTypes.use_paramod = use_paramod;
563     AutoTypes.use_only_paramod = use_only_paramod;
564     AutoTypes.close_more = close_more;
565     AutoTypes.dont_cache_failures = false;
566     AutoTypes.maxgoalsizefactor = gsize;
567     AutoTypes.do_types = do_type;
568     AutoTypes.skip_trie_filtering = skip_trie_filtering;
569     AutoTypes.skip_context = skip_context;
570   }
571
572 let universe_of_params metasenv context universe tl =
573   if tl = [] then universe else 
574    let tys =
575      List.map 
576        (fun term ->
577          fst (CicTypeChecker.type_of_aux' metasenv context term
578                 CicUniv.oblivion_ugraph))
579        tl          
580    in
581      Universe.index_list Universe.empty context (List.combine tl tys)
582 ;;
583
584
585 (***************** applyS *******************)
586
587 let new_metasenv_and_unify_and_t 
588  dbd flags universe proof goal ?tables newmeta' metasenv' 
589  context term' ty termty goal_arity 
590 =
591  let (consthead,newmetasenv,arguments,_) =
592    TermUtil.saturate_term newmeta' metasenv' context termty goal_arity in
593  let term'' = 
594    match arguments with [] -> term' | _ -> Cic.Appl (term'::arguments) 
595  in
596  let proof',oldmetasenv =
597   let (puri,metasenv,_subst,pbo,pty, attrs) = proof in
598    (puri,newmetasenv,_subst,pbo,pty, attrs),metasenv
599  in
600  let goal_for_paramod =
601   match LibraryObjects.eq_URI () with
602   | Some uri -> 
603       Cic.Appl [Cic.MutInd (uri,0,[]); Cic.Sort Cic.Prop; consthead; ty]
604   | None -> raise (ProofEngineTypes.Fail (lazy "No equality defined"))
605  in
606  let newmeta = CicMkImplicit.new_meta newmetasenv (*subst*) [] in
607  let metasenv_for_paramod = (newmeta,context,goal_for_paramod)::newmetasenv in
608  let proof'' = 
609    let uri,_,_subst,p,ty, attrs = proof' in 
610    uri,metasenv_for_paramod,_subst,p,ty, attrs 
611  in
612  let irl = CicMkImplicit.identity_relocation_list_for_metavariable context in
613  let proof''',goals =
614   ProofEngineTypes.apply_tactic
615     (EqualityTactics.rewrite_tac ~direction:`RightToLeft
616       ~pattern:(ProofEngineTypes.conclusion_pattern None) 
617         (Cic.Meta(newmeta,irl)) [])
618    (proof'',goal)
619  in
620  let goal = match goals with [g] -> g | _ -> assert false in
621  let  proof'''', _  =
622    ProofEngineTypes.apply_tactic 
623      (PrimitiveTactics.apply_tac term'')
624      (proof''',goal) 
625  in
626  match 
627    let (active, passive,bag), cache, maxmeta =
628      init_cache_and_tables ~dbd flags.use_library true true false universe
629      (proof'''',newmeta)
630    in
631      Saturation.given_clause bag maxmeta (proof'''',newmeta) active passive 
632        max_int max_int flags.timeout
633  with
634  | None, _,_,_ -> 
635      raise (ProofEngineTypes.Fail (lazy ("FIXME: propaga le tabelle"))) 
636  | Some (_,proof''''',_), active,passive,_  -> 
637      proof''''',
638      ProofEngineHelpers.compare_metasenvs ~oldmetasenv
639        ~newmetasenv:(let _,m,_subst,_,_, _ = proof''''' in m),  active, passive
640 ;;
641
642 let rec count_prods context ty =
643  match CicReduction.whd context ty with
644     Cic.Prod (n,s,t) -> 1 + count_prods (Some (n,Cic.Decl s)::context) t
645   | _ -> 0
646
647 let apply_smart 
648   ~dbd ~term ~subst ~universe ?tables ~params:(univ,params) (proof, goal) 
649 =
650  let module T = CicTypeChecker in
651  let module R = CicReduction in
652  let module C = Cic in
653   let (_,metasenv,_subst,_,_, _) = proof in
654   let metano,context,ty = CicUtil.lookup_meta goal metasenv in
655   let flags = flags_of_params params ~for_applyS:true () in
656   let universe = universe_of_params metasenv context universe univ in
657   let newmeta = CicMkImplicit.new_meta metasenv subst in
658    let exp_named_subst_diff,newmeta',newmetasenvfragment,term' =
659     match term with
660        C.Var (uri,exp_named_subst) ->
661         let newmeta',newmetasenvfragment,exp_named_subst',exp_named_subst_diff =
662          PrimitiveTactics.generalize_exp_named_subst_with_fresh_metas context newmeta uri
663           exp_named_subst
664         in
665          exp_named_subst_diff,newmeta',newmetasenvfragment,
666           C.Var (uri,exp_named_subst')
667      | C.Const (uri,exp_named_subst) ->
668         let newmeta',newmetasenvfragment,exp_named_subst',exp_named_subst_diff =
669          PrimitiveTactics.generalize_exp_named_subst_with_fresh_metas context newmeta uri
670           exp_named_subst
671         in
672          exp_named_subst_diff,newmeta',newmetasenvfragment,
673           C.Const (uri,exp_named_subst')
674      | C.MutInd (uri,tyno,exp_named_subst) ->
675         let newmeta',newmetasenvfragment,exp_named_subst',exp_named_subst_diff =
676          PrimitiveTactics.generalize_exp_named_subst_with_fresh_metas context newmeta uri
677           exp_named_subst
678         in
679          exp_named_subst_diff,newmeta',newmetasenvfragment,
680           C.MutInd (uri,tyno,exp_named_subst')
681      | C.MutConstruct (uri,tyno,consno,exp_named_subst) ->
682         let newmeta',newmetasenvfragment,exp_named_subst',exp_named_subst_diff =
683          PrimitiveTactics.generalize_exp_named_subst_with_fresh_metas context newmeta uri
684           exp_named_subst
685         in
686          exp_named_subst_diff,newmeta',newmetasenvfragment,
687           C.MutConstruct (uri,tyno,consno,exp_named_subst')
688      | _ -> [],newmeta,[],term
689    in
690    let metasenv' = metasenv@newmetasenvfragment in
691    let termty,_ = 
692      CicTypeChecker.type_of_aux' metasenv' context term' CicUniv.oblivion_ugraph
693    in
694    let termty = CicSubstitution.subst_vars exp_named_subst_diff termty in
695    let goal_arity = count_prods context ty in
696    let proof, gl, active, passive =
697     new_metasenv_and_unify_and_t dbd flags universe proof goal ?tables
698      newmeta' metasenv' context term' ty termty goal_arity
699    in
700     proof, gl, active, passive
701 ;;
702
703 (****************** AUTO ********************)
704
705 let mk_irl ctx = CicMkImplicit.identity_relocation_list_for_metavariable ctx;;
706 let ugraph = CicUniv.oblivion_ugraph;;
707 let typeof = CicTypeChecker.type_of_aux';;
708 let ppterm ctx t = 
709   let names = List.map (function None -> None | Some (x,_) -> Some x) ctx in
710   CicPp.pp t names
711 ;;
712 let is_in_prop context subst metasenv ty =
713   let sort,u = typeof ~subst metasenv context ty CicUniv.oblivion_ugraph in
714   is_propositional context sort
715 ;;
716
717 exception NotConvertible;;
718
719 let check_proof_is_valid proof metasenv context goalty =
720   if debug then
721     begin
722       try
723         let ty,u = typeof metasenv context proof CicUniv.oblivion_ugraph in
724         let b,_ = CicReduction.are_convertible context ty goalty u in
725         if not b then raise NotConvertible else b
726       with _ ->
727         let names = 
728           List.map (function None -> None | Some (x,_) -> Some x) context 
729         in
730           debug_print (lazy ("PROOF:" ^ CicPp.pp proof names));
731           (* debug_print (lazy ("PROOFTY:" ^ CicPp.pp ty names)); *)
732           debug_print (lazy ("GOAL:" ^ CicPp.pp goalty names));
733           debug_print (lazy ("MENV:" ^ CicMetaSubst.ppmetasenv [] metasenv));
734         false
735     end
736   else true
737 ;;
738
739 let assert_proof_is_valid proof metasenv context goalty =
740   assert (check_proof_is_valid proof metasenv context goalty)
741 ;;
742
743 let assert_subst_are_disjoint subst subst' =
744   if debug then
745     assert(List.for_all
746              (fun (i,_) -> List.for_all (fun (j,_) -> i<>j) subst') 
747              subst)
748   else ()
749 ;;
750
751 let split_goals_in_prop metasenv subst gl =
752   List.partition 
753     (fun g ->
754       let _,context,ty = CicUtil.lookup_meta g metasenv in
755       try
756         let sort,u = typeof ~subst metasenv context ty ugraph in
757         is_propositional context sort
758       with 
759       | CicTypeChecker.AssertFailure s 
760       | CicTypeChecker.TypeCheckerFailure s -> 
761           debug_print 
762             (lazy ("NON TIPA" ^ ppterm context (CicMetaSubst.apply_subst subst ty)));
763           debug_print s;
764           false)
765     (* FIXME... they should type! *)
766     gl
767 ;;
768
769 let split_goals_with_metas metasenv subst gl =
770   List.partition 
771     (fun g ->
772       let _,context,ty = CicUtil.lookup_meta g metasenv in
773       let ty = CicMetaSubst.apply_subst subst ty in
774       CicUtil.is_meta_closed ty)
775     gl
776 ;;
777
778 let order_new_goals metasenv subst open_goals ppterm =
779   let prop,rest = split_goals_in_prop metasenv subst open_goals in
780   let closed_prop, open_prop = split_goals_with_metas metasenv subst prop in
781   let closed_type, open_type = split_goals_with_metas metasenv subst rest in
782   let open_goals =
783     (List.map (fun x -> x,P) (open_prop @ closed_prop)) 
784     @ 
785     (List.map (fun x -> x,T) (open_type @ closed_type))
786   in
787   let tys = 
788     List.map 
789       (fun (i,sort) -> 
790         let _,_,ty = CicUtil.lookup_meta i metasenv in i,ty,sort) open_goals 
791   in
792   debug_print (lazy ("   OPEN: "^
793     String.concat "\n" 
794       (List.map 
795          (function
796             | (i,t,P) -> string_of_int i   ^ ":"^ppterm t^ "Prop" 
797             | (i,t,T) -> string_of_int i  ^ ":"^ppterm t^ "Type")
798          tys)));
799   open_goals
800 ;;
801
802 let is_an_equational_goal = function
803   | Cic.Appl [Cic.MutInd(u,_,_);_;_;_] when LibraryObjects.is_eq_URI u -> true
804   | _ -> false
805 ;;
806
807 (*
808 let prop = function (_,depth,P) -> depth < 9 | _ -> false;;
809 *)
810
811 let calculate_timeout flags = 
812     if flags.timeout = 0. then 
813       (debug_print (lazy "AUTO WITH NO TIMEOUT");
814        {flags with timeout = infinity})
815     else 
816       flags 
817 ;;
818 let is_equational_case goalty flags =
819   let ensure_equational t = 
820     if is_an_equational_goal t then true 
821     else false
822     (*
823       let msg="Not an equational goal.\nYou cant use the paramodulation flag"in
824       raise (ProofEngineTypes.Fail (lazy msg))
825     *)
826   in
827   (flags.use_paramod && is_an_equational_goal goalty) || 
828   (flags.use_only_paramod && ensure_equational goalty)
829 ;;
830 (*
831 let cache_add_success sort cache k v =
832   if sort = P then cache_add_success cache k v else cache_remove_underinspection
833   cache k
834 ;;
835 *)
836
837 type menv = Cic.metasenv
838 type subst = Cic.substitution
839 type goal = ProofEngineTypes.goal * int * AutoTypes.sort
840 let candidate_no = ref 0;;
841 type candidate = int * Cic.term Lazy.t
842 type cache = AutoCache.cache
843 type tables = 
844   Saturation.active_table * Saturation.passive_table * Equality.equality_bag
845
846 type fail = 
847   (* the goal (mainly for depth) and key of the goal *)
848   goal * AutoCache.cache_key
849 type op = 
850   (* goal has to be proved *)
851   | D of goal 
852   (* goal has to be cached as a success obtained using candidate as the first
853    * step *)
854   | S of goal * AutoCache.cache_key * candidate * int 
855 type elem = 
856   (* menv, subst, size, operations done (only S), operations to do, failures to cache if any op fails *)
857   menv * subst * int * op list * op list * fail list 
858 type status = 
859   (* list of computations that may lead to the solution: all op list will
860    * end with the same (S(g,_)) *)
861   elem list
862 type auto_result = 
863   (* menv, subst, alternatives, tables, cache, maxmeta *)
864   | Proved of menv * subst * elem list * tables * cache * int
865   | Gaveup of tables * cache * int 
866
867
868 (* the status exported to the external observer *)  
869 type auto_status = 
870   (* context, (goal,candidate) list, and_list, history *)
871   Cic.context * (int * Cic.term * bool * int * (int * Cic.term Lazy.t) list) list * 
872   (int * Cic.term * int) list * Cic.term Lazy.t list
873
874 let d_prefix l =
875   let rec aux acc = function
876     | (D g)::tl -> aux (acc@[g]) tl
877     | _ -> acc
878   in
879     aux [] l
880 ;;
881 let prop_only l =
882   List.filter (function (_,_,P) -> true | _ -> false) l
883 ;;
884
885 let d_goals l =
886   let rec aux acc = function
887     | (D g)::tl -> aux (acc@[g]) tl
888     | (S _)::tl -> aux acc tl
889     | [] -> acc
890   in
891     aux [] l
892 ;;
893
894 let calculate_goal_ty (goalno,_,_) s m = 
895   try
896     let _,cc,goalty = CicUtil.lookup_meta goalno m in
897     (* XXX applicare la subst al contesto? *)
898     Some (cc, CicMetaSubst.apply_subst s goalty)
899   with CicUtil.Meta_not_found i when i = goalno -> None
900 ;;
901
902 let calculate_closed_goal_ty (goalno,_,_) s = 
903   try
904     let cc,_,goalty = List.assoc goalno s in
905     (* XXX applicare la subst al contesto? *)
906     Some (cc, CicMetaSubst.apply_subst s goalty)
907   with Not_found -> None
908 ;;
909
910 let pp_status ctx status = 
911   if debug then 
912   let names = Utils.names_of_context ctx in
913   let pp x = 
914     let x = 
915       ProofEngineReduction.replace 
916         ~equality:(fun a b -> match b with Cic.Meta _ -> true | _ -> false) 
917           ~what:[Cic.Rel 1] ~with_what:[Cic.Implicit None] ~where:x
918     in
919     CicPp.pp x names
920   in
921   let string_of_do m s (gi,_,_ as g) d =
922     match calculate_goal_ty g s m with
923     | Some (_,gty) -> Printf.sprintf "D(%d, %s, %d)" gi (pp gty) d
924     | None -> Printf.sprintf "D(%d, _, %d)" gi d
925   in
926   let string_of_s m su k (ci,ct) gi =
927     Printf.sprintf "S(%d, %s, %s, %d)" gi (pp k) (pp (Lazy.force ct)) ci
928   in
929   let string_of_ol m su l =
930     String.concat " | " 
931       (List.map 
932         (function 
933           | D (g,d,s) -> string_of_do m su (g,d,s) d 
934           | S ((gi,_,_),k,c,_) -> string_of_s m su k c gi) 
935         l)
936   in
937   let string_of_fl m s fl = 
938     String.concat " | " 
939       (List.map (fun ((i,_,_),ty) -> 
940          Printf.sprintf "(%d, %s)" i (pp ty)) fl)
941   in
942   let rec aux = function
943     | [] -> ()
944     | (m,s,_,_,ol,fl)::tl ->
945         Printf.eprintf "< [%s] ;;; [%s]>\n" 
946           (string_of_ol m s ol) (string_of_fl m s fl);
947         aux tl
948   in
949     Printf.eprintf "-------------------------- status -------------------\n";
950     aux status;
951     Printf.eprintf "-----------------------------------------------------\n";
952 ;;
953   
954 let auto_status = ref [] ;;
955 let auto_context = ref [];;
956 let in_pause = ref false;;
957 let pause b = in_pause := b;;
958 let cond = Condition.create ();;
959 let mutex = Mutex.create ();;
960 let hint = ref None;;
961 let prune_hint = ref [];;
962
963 let step _ = Condition.signal cond;;
964 let give_hint n = hint := Some n;;
965 let give_prune_hint hint =
966   prune_hint := hint :: !prune_hint
967 ;;
968
969 let check_pause _ =
970   if !in_pause then
971     begin
972       Mutex.lock mutex;
973       Condition.wait cond mutex;
974       Mutex.unlock mutex
975     end
976 ;;
977
978 let get_auto_status _ = 
979   let status = !auto_status in
980   let and_list,elems,last = 
981     match status with
982     | [] -> [],[],[]
983     | (m,s,_,don,gl,fail)::tl ->
984         let and_list = 
985           HExtlib.filter_map 
986             (fun (id,d,_ as g) -> 
987               match calculate_goal_ty g s m with
988               | Some (_,x) -> Some (id,x,d) | None -> None)
989             (d_goals gl)
990         in
991         let rows = 
992           (* these are the S goalsin the or list *)
993           let orlist = 
994             List.map
995               (fun (m,s,_,don,gl,fail) -> 
996                 HExtlib.filter_map
997                   (function S (g,k,c,_) -> Some (g,k,c) | _ -> None) 
998                   (List.rev don @ gl))
999               status
1000           in
1001           (* this function eats id from a list l::[id,x] returning x, l *)
1002           let eat_tail_if_eq id l = 
1003             let rec aux (s, l) = function
1004               | [] -> s, l
1005               | ((id1,_,_),k1,c)::tl when id = id1 ->
1006                   (match s with
1007                   | None -> aux (Some c,l) tl
1008                   | Some _ -> assert false)
1009               | ((id1,_,_),k1,c as e)::tl -> aux (s, e::l) tl
1010             in
1011             let c, l = aux (None, []) l in
1012             c, List.rev l
1013           in
1014           let eat_in_parallel id l =
1015             let rec aux (b,eaten, new_l as acc) l =
1016               match l with
1017               | [] -> acc
1018               | l::tl ->
1019                   match eat_tail_if_eq id l with
1020                   | None, l -> aux (b@[false], eaten, new_l@[l]) tl
1021                   | Some t,l -> aux (b@[true],eaten@[t], new_l@[l]) tl
1022             in
1023             aux ([],[],[]) l
1024           in
1025           let rec eat_all rows l =
1026             match l with
1027             | [] -> rows
1028             | elem::or_list ->
1029                 match List.rev elem with
1030                 | ((to_eat,depth,_),k,_)::next_lunch ->
1031                     let b, eaten, l = eat_in_parallel to_eat l in
1032                     let eaten = HExtlib.list_uniq eaten in
1033                     let eaten = List.rev eaten in
1034                     let b = true (* List.hd (List.rev b) *) in
1035                     let rows = rows @ [to_eat,k,b,depth,eaten] in
1036                     eat_all rows l
1037                 | [] -> eat_all rows or_list
1038           in
1039           eat_all [] (List.rev orlist)
1040         in
1041         let history = 
1042           HExtlib.filter_map
1043             (function (S (_,_,(_,c),_)) -> Some c | _ -> None) 
1044             gl 
1045         in
1046 (*         let rows = List.filter (fun (_,l) -> l <> []) rows in *)
1047         and_list, rows, history
1048   in
1049   !auto_context, elems, and_list, last
1050 ;;
1051
1052 (* Works if there is no dependency over proofs *)
1053 let is_a_green_cut goalty =
1054   CicUtil.is_meta_closed goalty
1055 ;;
1056 let rec first_s = function
1057   | (D _)::tl -> first_s tl
1058   | (S (g,k,c,s))::tl -> Some ((g,k,c,s),tl)
1059   | [] -> None
1060 ;;
1061 let list_union l1 l2 =
1062   (* TODO ottimizzare compare *)
1063   HExtlib.list_uniq (List.sort compare (l1 @ l1))
1064 ;;
1065 let rec eq_todo l1 l2 =
1066   match l1,l2 with
1067   | (D g1) :: tl1,(D g2) :: tl2 when g1=g2 -> eq_todo tl1 tl2
1068   | (S (g1,k1,(c1,lt1),i1)) :: tl1, (S (g2,k2,(c2,lt2),i2)) :: tl2
1069     when i1 = i2 && g1 = g2 && k1 = k2 && c1 = c2 ->
1070       if Lazy.force lt1 = Lazy.force lt2 then eq_todo tl1 tl2 else false
1071   | [],[] -> true
1072   | _ -> false
1073 ;;
1074 let eat_head todo id fl orlist = 
1075   let rec aux acc = function
1076   | [] -> [], acc
1077   | (m, s, _, _, todo1, fl1)::tl as orlist -> 
1078       let rec aux1 todo1 =
1079         match first_s todo1 with
1080         | None -> orlist, acc
1081         | Some (((gno,_,_),_,_,_), todo11) ->
1082             (* TODO confronto tra todo da ottimizzare *)
1083             if gno = id && eq_todo todo11 todo then 
1084               aux (list_union fl1 acc) tl
1085             else 
1086               aux1 todo11
1087       in
1088        aux1 todo1
1089   in 
1090     aux fl orlist
1091 ;;
1092 let close_proof p ty menv context = 
1093   let metas =
1094     List.map fst (CicUtil.metas_of_term p @ CicUtil.metas_of_term ty)
1095   in
1096   let menv = List.filter (fun (i,_,_) -> List.exists ((=)i) metas) menv in
1097   naif_closure p menv context
1098 ;;
1099 (* XXX capire bene quando aggiungere alla cache *)
1100 let add_to_cache_and_del_from_orlist_if_green_cut
1101   g s m cache key todo orlist fl ctx size minsize
1102
1103   let cache = cache_remove_underinspection cache key in
1104   (* prima per fare la irl usavamo il contesto vero e proprio e non quello 
1105    * canonico! XXX *)
1106   match calculate_closed_goal_ty g s with
1107   | None -> assert false
1108   | Some (canonical_ctx , gty) ->
1109       let goalno,depth,sort = g in
1110       let irl = mk_irl canonical_ctx in
1111       let goal = Cic.Meta(goalno, irl) in
1112       let proof = CicMetaSubst.apply_subst s goal in
1113       let green_proof, closed_proof = 
1114         let b = is_a_green_cut proof in
1115         if not b then
1116           b, (* close_proof proof gty m ctx *) proof 
1117         else
1118           b, proof
1119       in
1120       debug_print (lazy ("TENTATIVE CACHE: " ^ CicPp.ppterm key));
1121       if is_a_green_cut key then
1122         (* if the initia goal was closed, we cut alternatives *)
1123         let _ = debug_print (lazy ("MANGIO: " ^ string_of_int goalno)) in
1124         let orlist, fl = eat_head todo goalno fl orlist in
1125         let cache = 
1126           if size < minsize then 
1127             (debug_print (lazy ("NO CACHE: 2 (size <= minsize)"));cache)
1128           else 
1129           (* if the proof is closed we cache it *)
1130           if green_proof then cache_add_success cache key proof
1131           else (* cache_add_success cache key closed_proof *) 
1132             (debug_print (lazy ("NO CACHE: (no gree proof)"));cache)
1133         in
1134         cache, orlist, fl, true
1135       else
1136         let cache = 
1137           debug_print (lazy ("TENTATIVE CACHE: " ^ CicPp.ppterm gty));
1138           if size < minsize then 
1139             (debug_print (lazy ("NO CACHE: (size <= minsize)")); cache) else
1140           (* if the substituted goal and the proof are closed we cache it *)
1141           if is_a_green_cut gty then
1142             if green_proof then cache_add_success cache gty proof
1143             else (* cache_add_success cache gty closed_proof *) 
1144               (debug_print (lazy ("NO CACHE: (no green proof (gty))"));cache)
1145           else (*
1146             try
1147               let ty, _ =
1148                 CicTypeChecker.type_of_aux' ~subst:s 
1149                   m ctx closed_proof CicUniv.oblivion_ugraph
1150               in
1151               if is_a_green_cut ty then 
1152                 cache_add_success cache ty closed_proof
1153               else cache
1154             with
1155             | CicTypeChecker.TypeCheckerFailure _ ->*) 
1156           (debug_print (lazy ("NO CACHE: (no green gty )"));cache)
1157         in
1158         cache, orlist, fl, false
1159 ;;
1160 let close_failures (fl : fail list) (cache : cache) = 
1161   List.fold_left 
1162     (fun cache ((gno,depth,_),gty) -> 
1163       debug_print (lazy ("FAIL: INDUCED: " ^ string_of_int gno));
1164       cache_add_failure cache gty depth) 
1165     cache fl
1166 ;;
1167 let put_in_subst subst metasenv  (goalno,_,_) canonical_ctx t ty =
1168   let entry = goalno, (canonical_ctx, t,ty) in
1169   assert_subst_are_disjoint subst [entry];
1170   let subst = entry :: subst in
1171   let metasenv = CicMetaSubst.apply_subst_metasenv subst metasenv in
1172   subst, metasenv
1173 ;;
1174
1175 let mk_fake_proof metasenv subst (goalno,_,_) goalty context = 
1176   None,metasenv,subst ,(lazy (Cic.Meta(goalno,mk_irl context))),goalty, [] 
1177 ;;
1178 let equational_case 
1179   tables maxm cache depth fake_proof goalno goalty subst context 
1180     flags
1181 =
1182   let active,passive,bag = tables in
1183   let ppterm = ppterm context in
1184   let status = (fake_proof,goalno) in
1185     if flags.use_only_paramod then
1186       begin
1187         debug_print (lazy ("PARAMODULATION SU: " ^ 
1188                          string_of_int goalno ^ " " ^ ppterm goalty ));
1189         let goal_steps, saturation_steps, timeout =
1190           max_int,max_int,flags.timeout 
1191         in
1192
1193         match
1194           Saturation.given_clause bag maxm status active passive 
1195             goal_steps saturation_steps timeout
1196         with 
1197           | None, active, passive, maxmeta -> 
1198               [], (active,passive,bag), cache, maxmeta, flags
1199           | Some(subst',(_,metasenv,_subst,proof,_, _),open_goals),active,
1200             passive,maxmeta ->
1201               assert_subst_are_disjoint subst subst';
1202               let subst = subst@subst' in
1203               let open_goals = 
1204                 order_new_goals metasenv subst open_goals ppterm 
1205               in
1206               let open_goals = 
1207                 List.map (fun (x,sort) -> x,depth-1,sort) open_goals 
1208               in
1209               incr candidate_no;
1210                       [(!candidate_no,proof),metasenv,subst,open_goals], 
1211                 (active,passive,bag), 
1212                 cache, maxmeta, flags
1213       end
1214     else
1215       begin
1216         debug_print 
1217           (lazy 
1218            ("SUBSUMPTION SU: " ^ string_of_int goalno ^ " " ^ ppterm goalty));
1219         let res, maxmeta = 
1220           Saturation.all_subsumed bag maxm status active passive 
1221         in
1222         assert (maxmeta >= maxm);
1223         let res' =
1224           List.map 
1225             (fun (subst',(_,metasenv,_subst,proof,_, _),open_goals) ->
1226                assert_subst_are_disjoint subst subst';
1227                let subst = subst@subst' in
1228                let open_goals = 
1229                  order_new_goals metasenv subst open_goals ppterm 
1230                in
1231                let open_goals = 
1232                  List.map (fun (x,sort) -> x,depth-1,sort) open_goals 
1233                in
1234                incr candidate_no;
1235                  (!candidate_no,proof),metasenv,subst,open_goals)
1236             res 
1237           in
1238           res', (active,passive,bag), cache, maxmeta, flags 
1239       end
1240 ;;
1241
1242 let try_candidate 
1243   goalty tables maxm subst fake_proof goalno depth context cand 
1244 =
1245   let ppterm = ppterm context in
1246   try 
1247     let subst,((_,metasenv,_,_,_,_), open_goals),maxmeta =
1248         (PrimitiveTactics.apply_with_subst ~subst ~maxmeta:maxm ~term:cand)
1249         (fake_proof,goalno) 
1250     in
1251     debug_print (lazy ("   OK: " ^ ppterm cand));
1252     let metasenv = CicRefine.pack_coercion_metasenv metasenv in
1253     let open_goals = order_new_goals metasenv subst open_goals ppterm in
1254     let open_goals = List.map (fun (x,sort) -> x,depth-1,sort) open_goals in
1255     incr candidate_no;
1256     Some ((!candidate_no,lazy cand),metasenv,subst,open_goals), tables , maxmeta
1257   with 
1258     | ProofEngineTypes.Fail s -> None,tables, maxm
1259     | CicUnification.Uncertain s ->  None,tables, maxm
1260 ;;
1261
1262 let sort_new_elems = 
1263  List.sort (fun (_,_,_,l1) (_,_,_,l2) -> 
1264   List.length (prop_only l1) - List.length (prop_only l2))
1265 ;;
1266
1267 let applicative_case 
1268   tables maxm depth subst fake_proof goalno goalty metasenv context universe
1269   cache flags
1270
1271   let candidates = get_candidates flags.skip_trie_filtering universe cache goalty in
1272   let tables, elems, maxm = 
1273     List.fold_left 
1274       (fun (tables,elems,maxm) cand ->
1275         match 
1276           try_candidate goalty
1277             tables maxm subst fake_proof goalno depth context cand
1278         with
1279         | None, tables,maxm  -> tables,elems, maxm 
1280         | Some x, tables, maxm -> tables,x::elems, maxm)
1281       (tables,[],maxm) candidates
1282   in
1283   let elems = sort_new_elems elems in
1284   elems, tables, cache, maxm 
1285 ;;
1286
1287 let equational_and_applicative_case 
1288   universe flags m s g gty tables cache maxm context 
1289 =
1290   let goalno, depth, sort = g in
1291   let fake_proof = mk_fake_proof m s g gty context in
1292   if is_equational_case gty flags then
1293     let elems,tables,cache,maxm1, flags =
1294       equational_case tables maxm cache
1295         depth fake_proof goalno gty s context flags 
1296     in
1297     let maxm = maxm1 in
1298     let more_elems, tables, cache, maxm1 =
1299       if flags.use_only_paramod then
1300         [],tables, cache, maxm
1301       else
1302         applicative_case 
1303           tables maxm depth s fake_proof goalno 
1304             gty m context universe cache flags
1305     in
1306     let maxm = maxm1 in
1307       elems@more_elems, tables, cache, maxm, flags            
1308   else
1309     let elems, tables, cache, maxm =
1310       applicative_case tables maxm depth s fake_proof goalno 
1311         gty m context universe cache flags
1312     in
1313       elems, tables, cache, maxm, flags  
1314 ;;
1315 let rec condition_for_hint i = function
1316   | [] -> false
1317   | S (_,_,(j,_),_):: tl -> j <> i (* && condition_for_hint i tl *)
1318   | _::tl -> condition_for_hint i tl
1319 ;;
1320 let remove_s_from_fl (id,_,_) (fl : fail list) =
1321   let rec aux = function
1322     | [] -> []
1323     | ((id1,_,_),_)::tl when id = id1 -> tl
1324     | hd::tl ->  hd :: aux tl
1325   in 
1326     aux fl
1327 ;;
1328
1329 let prunable_for_size flags s m todo =
1330   let rec aux b = function
1331     | (S _)::tl -> aux b tl
1332     | (D (_,_,T))::tl -> aux b tl
1333     | (D g)::tl -> 
1334         (match calculate_goal_ty g s m with
1335           | None -> aux b tl
1336           | Some (canonical_ctx, gty) -> 
1337             let gsize, _ = 
1338               Utils.weight_of_term 
1339                 ~consider_metas:false ~count_metas_occurrences:true gty in
1340             let newb = b || gsize > flags.maxgoalsizefactor in
1341             aux newb tl)
1342     | [] -> b
1343   in
1344     aux false todo
1345
1346 (*
1347 let prunable ty todo =
1348   let rec aux b = function
1349     | (S(_,k,_,_))::tl -> aux (b || Equality.meta_convertibility k ty) tl
1350     | (D (_,_,T))::tl -> aux b tl
1351     | D _::_ -> false
1352     | [] -> b
1353   in
1354     aux false todo
1355 ;;
1356 *)
1357
1358 let prunable menv subst ty todo =
1359   let rec aux = function
1360     | (S(_,k,_,_))::tl ->
1361          (match Equality.meta_convertibility_subst k ty menv with
1362           | None -> aux tl
1363           | Some variant -> 
1364                no_progress variant tl (* || aux tl*))
1365     | (D (_,_,T))::tl -> aux tl
1366     | _ -> false
1367   and no_progress variant = function
1368     | [] -> (*prerr_endline "++++++++++++++++++++++++ no_progress";*) true
1369     | D ((n,_,P) as g)::tl -> 
1370         (match calculate_goal_ty g subst menv with
1371            | None -> no_progress variant tl
1372            | Some (_, gty) -> 
1373                (match calculate_goal_ty g variant menv with
1374                   | None -> assert false
1375                   | Some (_, gty') ->
1376                       if gty = gty' then
1377                          no_progress variant tl
1378                       else false))
1379     | _::tl -> no_progress variant tl
1380   in
1381     aux todo
1382
1383 ;;
1384 let condition_for_prune_hint prune (m, s, size, don, todo, fl) =
1385   let s = 
1386     HExtlib.filter_map (function S (_,_,(c,_),_) -> Some c | _ -> None) todo 
1387   in
1388   List.for_all (fun i -> List.for_all (fun j -> i<>j) prune) s
1389 ;;
1390 let filter_prune_hint l =
1391   let prune = !prune_hint in
1392   prune_hint := []; (* possible race... *)
1393   if prune = [] then l
1394   else List.filter (condition_for_prune_hint prune) l
1395 ;;
1396 let auto_main tables maxm context flags universe cache elems =
1397   auto_context := context;
1398   let rec aux tables maxm flags cache (elems : status) =
1399 (*     pp_status context elems; *)
1400 (* DEBUGGING CODE: uncomment these two lines to stop execution at each iteration
1401     auto_status := elems;
1402     check_pause ();
1403 *)
1404     let elems = filter_prune_hint elems in
1405     match elems with
1406     | (m, s, size, don, todo, fl)::orlist when !hint <> None ->
1407         debug_print (lazy "skip");
1408         (match !hint with
1409         | Some i when condition_for_hint i todo ->
1410             aux tables maxm flags cache orlist
1411         | _ ->
1412           hint := None;
1413           aux tables maxm flags cache elems)
1414     | [] ->
1415         (* complete failure *)
1416         debug_print (lazy "give up");
1417         Gaveup (tables, cache, maxm)
1418     | (m, s, _, _, [],_)::orlist ->
1419         (* complete success *)
1420         debug_print (lazy "success");
1421         Proved (m, s, orlist, tables, cache, maxm)
1422     | (m, s, size, don, (D (_,_,T))::todo, fl)::orlist 
1423       when not flags.AutoTypes.do_types ->
1424         (* skip since not Prop, don't even check if closed by side-effect *)
1425         debug_print (lazy "skip existential goal");
1426         aux tables maxm flags cache ((m, s, size, don, todo, fl)::orlist)
1427     | (m, s, size, don, (S(g, key, c,minsize) as op)::todo, fl)::orlist ->
1428         (* partial success, cache g and go on *)
1429         let cache, orlist, fl, sibling_pruned = 
1430           add_to_cache_and_del_from_orlist_if_green_cut 
1431             g s m cache key todo orlist fl context size minsize
1432         in
1433         debug_print (lazy (AutoCache.cache_print context cache));
1434         let fl = remove_s_from_fl g fl in
1435         let don = if sibling_pruned then don else op::don in
1436         aux tables maxm flags cache ((m, s, size, don, todo, fl)::orlist)
1437     | (m, s, size, don, todo, fl)::orlist 
1438       when List.length(prop_only (d_goals todo)) > flags.maxwidth ->
1439         debug_print (lazy ("FAIL: WIDTH"));
1440         (* too many goals in and generated by last th *)
1441         let cache = close_failures fl cache in
1442         aux tables maxm flags cache orlist
1443     | (m, s, size, don, todo, fl)::orlist when size > flags.maxsize ->
1444         debug_print 
1445           (lazy ("FAIL: SIZE: "^string_of_int size ^ 
1446             " > " ^ string_of_int flags.maxsize ));
1447         (* we already have a too large proof term *)
1448         let cache = close_failures fl cache in
1449         aux tables maxm flags cache orlist
1450     | _ when Unix.gettimeofday () > flags.timeout ->
1451         (* timeout *)
1452         debug_print (lazy ("FAIL: TIMEOUT"));
1453         Gaveup (tables, cache, maxm)
1454     | (m, s, size, don, (D (gno,depth,_ as g))::todo, fl)::orlist as status ->
1455         (* attack g *) 
1456         debug_print (lazy "attack goal");
1457         match calculate_goal_ty g s m with
1458         | None -> 
1459             (* closed by side effect *)
1460             debug_print (lazy ("SUCCESS: SIDE EFFECT: " ^ string_of_int gno));
1461             aux tables maxm flags cache ((m,s,size,don,todo, fl)::orlist)
1462         | Some (canonical_ctx, gty) ->
1463             let gsize, _ = 
1464               Utils.weight_of_term ~consider_metas:false ~count_metas_occurrences:true gty 
1465             in
1466             if gsize > flags.maxgoalsizefactor then
1467               (debug_print (lazy ("FAIL: SIZE: goal: "^string_of_int gsize));
1468                aux tables maxm flags cache orlist)
1469             else if prunable_for_size flags s m todo then
1470                 (debug_print (lazy ("POTO at depth: "^(string_of_int depth)));
1471                  aux tables maxm flags cache orlist)
1472             else
1473             (* still to be proved *)
1474             (debug_print (lazy ("EXAMINE: "^CicPp.ppterm gty));
1475             match cache_examine cache gty with
1476             | Failed_in d when d >= depth -> 
1477                 (* fail depth *)
1478                 debug_print (lazy ("FAIL: DEPTH (cache): "^string_of_int gno));
1479                 let cache = close_failures fl cache in
1480                 aux tables maxm flags cache orlist
1481             | UnderInspection -> 
1482                 (* fail loop *)
1483                 debug_print (lazy ("FAIL: LOOP: " ^ string_of_int gno));
1484                 let cache = close_failures fl cache in
1485                 aux tables maxm flags cache orlist
1486             | Succeded t -> 
1487                 debug_print (lazy ("SUCCESS: CACHE HIT: " ^ string_of_int gno));
1488                 let s, m = put_in_subst s m g canonical_ctx t gty in
1489                 aux tables maxm flags cache ((m, s, size, don,todo, fl)::orlist)
1490             | Notfound 
1491             | Failed_in _ when depth > 0 -> 
1492                 ( (* more depth or is the first time we see the goal *)
1493                     if prunable m s gty todo then
1494                       (debug_print (lazy(
1495                          "FAIL: LOOP: one father is equal"));
1496                        aux tables maxm flags cache orlist)
1497                     else
1498                     let cache = cache_add_underinspection cache gty depth in
1499                     auto_status := status;
1500                     check_pause ();
1501                     debug_print 
1502                       (lazy ("INSPECTING: " ^ 
1503                         string_of_int gno ^ "("^ string_of_int size ^ "): "^
1504                         CicPp.ppterm gty));
1505                     (* elems are possible computations for proving gty *)
1506                     let elems, tables, cache, maxm, flags =
1507                       equational_and_applicative_case 
1508                         universe flags m s g gty tables cache maxm context
1509                     in
1510                     if elems = [] then
1511                       (* this goal has failed *)
1512                       let cache = close_failures ((g,gty)::fl) cache in
1513                       aux tables maxm flags cache orlist
1514                     else
1515                       (* elems = (cand,m,s,gl) *)
1516                       let size_gl l = List.length 
1517                         (List.filter (function (_,_,P) -> true | _ -> false) l) 
1518                       in
1519                       let elems = 
1520                         let inj_gl gl = List.map (fun g -> D g) gl in
1521                         let rec map = function
1522                           | [] -> assert false
1523                           | (cand,m,s,gl)::[] ->
1524                               (* in the last one we add the failure *)
1525                               let todo = 
1526                                 inj_gl gl @ (S(g,gty,cand,size+1))::todo 
1527                               in
1528                               (* we are the last in OR, we fail on g and 
1529                                * also on all failures implied by g *)
1530                               (m,s, size + size_gl gl, don, todo, (g,gty)::fl)
1531                               :: orlist
1532                           | (cand,m,s,gl)::tl -> 
1533                               (* we add the S step after gl and before todo *)
1534                               let todo = 
1535                                 inj_gl gl @ (S(g,gty,cand,size+1))::todo 
1536                               in
1537                               (* since we are not the last in OR, we do not
1538                                * imply failures *)
1539                               (m,s, size + size_gl gl, don, todo, []) :: map tl
1540                         in
1541                           map elems
1542                       in
1543                         aux tables maxm flags cache elems)
1544             | _ -> 
1545                 (* no more depth *)
1546                 debug_print (lazy ("FAIL: DEPTH: " ^ string_of_int gno));
1547                 let cache = close_failures fl cache in
1548                 aux tables maxm flags cache orlist)
1549   in
1550     (aux tables maxm flags cache elems : auto_result)
1551 ;;
1552     
1553
1554 let
1555   auto_all_solutions maxm tables universe cache context metasenv gl flags 
1556 =
1557   let goals = order_new_goals metasenv [] gl CicPp.ppterm in
1558   let goals = 
1559     List.map 
1560       (fun (x,s) -> D (x,flags.maxdepth,s)) goals 
1561   in
1562   let elems = [metasenv,[],1,[],goals,[]] in
1563   let rec aux tables maxm solutions cache elems flags =
1564     match auto_main tables maxm context flags universe cache elems with
1565     | Gaveup (tables,cache,maxm) ->
1566         solutions,cache,maxm
1567     | Proved (metasenv,subst,others,tables,cache,maxm) -> 
1568         if Unix.gettimeofday () > flags.timeout then
1569           ((subst,metasenv)::solutions), cache, maxm
1570         else
1571           aux tables maxm ((subst,metasenv)::solutions) cache others flags
1572   in
1573   let rc = aux tables maxm [] cache elems flags in
1574     match rc with
1575     | [],cache,maxm -> [],cache,maxm
1576     | solutions,cache,maxm -> 
1577         let solutions = 
1578           HExtlib.filter_map
1579             (fun (subst,newmetasenv) ->
1580               let opened = 
1581                 ProofEngineHelpers.compare_metasenvs ~oldmetasenv:metasenv ~newmetasenv
1582               in
1583               if opened = [] then Some subst else None)
1584             solutions
1585         in
1586          solutions,cache,maxm
1587 ;;
1588
1589 (* }}} ****************** AUTO ***************)
1590
1591 let auto flags metasenv tables universe cache context metasenv gl =
1592   let initial_time = Unix.gettimeofday() in
1593   let goals = order_new_goals metasenv [] gl CicPp.ppterm in
1594   let goals = List.map (fun (x,s) -> D(x,flags.maxdepth,s)) goals in
1595   let elems = [metasenv,[],1,[],goals,[]] in
1596   match auto_main tables 0 context flags universe cache elems with
1597   | Proved (metasenv,subst,_, tables,cache,_) -> 
1598       debug_print(lazy
1599         ("TIME:"^string_of_float(Unix.gettimeofday()-.initial_time)));
1600       Some (subst,metasenv), cache
1601   | Gaveup (tables,cache,maxm) -> 
1602       debug_print(lazy
1603         ("TIME:"^string_of_float(Unix.gettimeofday()-.initial_time)));
1604       None,cache
1605 ;;
1606
1607 let applyS_tac ~dbd ~term ~params ~universe =
1608  ProofEngineTypes.mk_tactic
1609   (fun status ->
1610     try 
1611       let proof, gl,_,_ =
1612        apply_smart ~dbd ~term ~subst:[] ~params ~universe status
1613       in 
1614        proof, gl
1615     with 
1616     | CicUnification.UnificationFailure msg
1617     | CicTypeChecker.TypeCheckerFailure msg ->
1618         raise (ProofEngineTypes.Fail msg))
1619
1620 let auto_tac ~(dbd:HSql.dbd) ~params:(univ,params) ~universe (proof, goal) =
1621   let _,metasenv,_subst,_,_, _ = proof in
1622   let _,context,goalty = CicUtil.lookup_meta goal metasenv in
1623   let flags = flags_of_params params () in
1624   let universe = universe_of_params metasenv context universe univ in
1625   let use_library = flags.use_library in
1626   let tables,cache,newmeta =
1627     init_cache_and_tables ~dbd use_library flags.use_only_paramod (not flags.skip_context)
1628       false universe (proof, goal) in
1629   let tables,cache,newmeta =
1630     if flags.close_more then
1631       close_more 
1632         tables newmeta context (proof, goal) 
1633           auto_all_solutions universe cache 
1634     else tables,cache,newmeta in
1635   let initial_time = Unix.gettimeofday() in
1636   let (_,oldmetasenv,_subst,_,_, _) = proof in
1637   hint := None;
1638   let elem = 
1639     metasenv,[],1,[],[D (goal,flags.maxdepth,P)],[]
1640   in
1641   match auto_main tables newmeta context flags universe cache [elem] with
1642     | Proved (metasenv,subst,_, tables,cache,_) -> 
1643         debug_print (lazy 
1644           ("TIME:"^string_of_float(Unix.gettimeofday()-.initial_time)));
1645         let proof,metasenv =
1646         ProofEngineHelpers.subst_meta_and_metasenv_in_proof
1647           proof goal subst metasenv
1648         in
1649         let opened = 
1650           ProofEngineHelpers.compare_metasenvs ~oldmetasenv
1651             ~newmetasenv:metasenv
1652         in
1653           proof,opened
1654     | Gaveup (tables,cache,maxm) -> 
1655         debug_print
1656           (lazy ("TIME:"^
1657             string_of_float(Unix.gettimeofday()-.initial_time)));
1658         raise (ProofEngineTypes.Fail (lazy "Auto gave up"))
1659 ;;
1660
1661 let auto_tac ~dbd ~params ~universe = 
1662   ProofEngineTypes.mk_tactic (auto_tac ~params ~dbd ~universe);;
1663
1664 let eq_of_goal = function
1665   | Cic.Appl [Cic.MutInd(uri,0,_);_;_;_] when LibraryObjects.is_eq_URI uri ->
1666       uri
1667   | _ -> raise (ProofEngineTypes.Fail (lazy ("The goal is not an equality ")))
1668 ;;
1669
1670 (* performs steps of rewrite with the universe, obtaining if possible 
1671  * a trivial goal *)
1672 let solve_rewrite_tac ~universe ~params:(univ,params) (proof,goal as status)= 
1673   let _,metasenv,_subst,_,_,_ = proof in
1674   let _,context,ty = CicUtil.lookup_meta goal metasenv in
1675   let steps = int_of_string (string params "steps" "1") in 
1676   let universe = universe_of_params metasenv context universe univ in
1677   let eq_uri = eq_of_goal ty in
1678   let (active,passive,bag), cache, maxm =
1679      (* we take the whole universe (no signature filtering) *)
1680      init_cache_and_tables false true false true universe (proof,goal) 
1681   in
1682   let initgoal = [], metasenv, ty in
1683   let table = 
1684     let equalities = (Saturation.list_of_passive passive) in
1685     (* we demodulate using both actives passives *)
1686     List.fold_left (fun tbl eq -> Indexing.index tbl eq) (snd active) equalities
1687   in
1688   let env = metasenv,context,CicUniv.oblivion_ugraph in
1689   match Indexing.solve_demodulating bag env table initgoal steps with 
1690   | Some (proof, metasenv, newty) ->
1691       let refl = 
1692         match newty with
1693         | Cic.Appl[Cic.MutInd _;eq_ty;left;_] ->
1694             Equality.Exact (Equality.refl_proof eq_uri eq_ty left)
1695         | _ -> assert false
1696       in
1697       let proofterm,_ = 
1698         Equality.build_goal_proof 
1699           bag eq_uri proof refl newty [] context metasenv
1700       in
1701       ProofEngineTypes.apply_tactic
1702         (PrimitiveTactics.apply_tac ~term:proofterm) status
1703   | None -> 
1704       raise 
1705         (ProofEngineTypes.Fail (lazy 
1706           ("Unable to solve with " ^ string_of_int steps ^ " demodulations")))
1707 ;;
1708 let solve_rewrite_tac ~params ~universe () =
1709   ProofEngineTypes.mk_tactic (solve_rewrite_tac ~universe ~params)
1710 ;;
1711
1712 (* Demodulate thorem *)
1713 let open_type ty bo =
1714   let rec open_type_aux context ty k args =
1715     match ty with 
1716       | Cic.Prod (n,s,t) ->
1717           let n' = 
1718             FreshNamesGenerator.mk_fresh_name [] context n ~typ:s ~subst:[] in
1719           let entry = match n' with
1720             | Cic.Name _    -> Some (n',(Cic.Decl s))
1721             | Cic.Anonymous -> None
1722           in
1723             open_type_aux (entry::context) t (k+1) ((Cic.Rel k)::args)
1724       | Cic.LetIn (n,s,sty,t) ->
1725           let entry = Some (n,(Cic.Def (s,sty)))
1726           in
1727             open_type_aux (entry::context) t (k+1) args
1728       | _  -> context, ty, args
1729   in
1730   let context, ty, args = open_type_aux [] ty 1 [] in
1731   match args with
1732     | [] -> context, ty, bo
1733     | _ -> context, ty, Cic.Appl (bo::args)
1734 ;; 
1735
1736 let rec close_type bo ty context =
1737   match context with 
1738     | [] -> assert_proof_is_valid bo [] [] ty; (bo,ty)
1739     | Some (n,(Cic.Decl s))::tl ->
1740         close_type (Cic.Lambda (n,s,bo)) (Cic.Prod (n,s,ty)) tl
1741     | Some (n,(Cic.Def (s,sty)))::tl ->
1742         close_type (Cic.LetIn (n,s,sty,bo)) (Cic.LetIn (n,s,sty,ty)) tl
1743     | _ -> assert false
1744 ;; 
1745
1746 let is_subsumed univ context ty =
1747   let candidates = Universe.get_candidates univ ty in
1748     List.fold_left 
1749       (fun res cand ->
1750          match res with
1751            | Some found -> Some found
1752            | None -> 
1753                try 
1754                  let mk_irl = CicMkImplicit.identity_relocation_list_for_metavariable in
1755                  let metasenv = [(0,context,ty)] in
1756                  let fake_proof = None,metasenv,[] , (lazy (Cic.Meta(0,mk_irl context))),ty,[] in
1757                  let subst,((_,metasenv,_,_,_,_), open_goals),maxmeta =
1758                    (PrimitiveTactics.apply_with_subst ~subst:[] ~maxmeta:0 ~term:cand) (fake_proof,0)
1759                  in
1760                  let prop_goals, other = split_goals_in_prop metasenv subst open_goals in
1761                    if prop_goals = [] then Some cand else None
1762                with 
1763                  | ProofEngineTypes.Fail s -> None
1764                  | CicUnification.Uncertain s ->  None
1765       ) None candidates
1766 ;;
1767
1768 let demodulate_theorem ~universe uri =
1769   let eq_uri = 
1770     match LibraryObjects.eq_URI () with
1771       | Some (uri) -> uri
1772       | None -> raise (ProofEngineTypes.Fail (lazy "equality not declared")) in
1773   let obj,_ = CicEnvironment.get_cooked_obj CicUniv.empty_ugraph uri
1774   in
1775   let context,ty,bo =
1776     match obj with 
1777       | Cic.Constant(n, _, ty ,_, _) -> open_type ty (Cic.Const(uri,[]))
1778       | _ -> raise (ProofEngineTypes.Fail (lazy "not a theorem"))
1779   in
1780   if CicUtil.is_closed ty then 
1781     raise (ProofEngineTypes.Fail (lazy ("closed term: dangerous reduction")));
1782   let initgoal = [], [], ty in
1783   (* compute the signature *)
1784   let signature = 
1785     let ty_set = MetadataConstraints.constants_of ty in
1786     let hyp_set = MetadataQuery.signature_of_hypothesis context [] in
1787     let set = MetadataConstraints.UriManagerSet.union ty_set hyp_set in
1788       MetadataQuery.close_with_types set [] context 
1789   in
1790   (* retrieve equations from the universe universe *)
1791   let equations = 
1792     retrieve_equations true signature universe AutoCache.cache_empty context []
1793   in
1794   debug_print 
1795     (lazy ("ho trovato equazioni n. "^(string_of_int (List.length equations))));
1796   let eqs_and_types =
1797     HExtlib.filter_map 
1798       (fun t -> 
1799          let ty,_ =
1800            CicTypeChecker.type_of_aux' [] context t CicUniv.oblivion_ugraph
1801          in
1802          (* retrieve_equations could also return flexible terms *)
1803          if is_an_equality ty then Some(t,ty) 
1804          else
1805            try
1806              let ty' = unfold context ty in
1807              if is_an_equality ty' then Some(t,ty') else None
1808            with ProofEngineTypes.Fail _ -> None) 
1809       equations
1810   in
1811   let bag = Equality.mk_equality_bag () in
1812
1813   let units, _, newmeta = 
1814     partition_unit_equalities context [] (CicMkImplicit.new_meta [] []) bag eqs_and_types 
1815   in
1816   let table =
1817     List.fold_left 
1818       (fun tbl eq -> Indexing.index tbl eq) 
1819       Indexing.empty units
1820   in 
1821   let changed,(newproof,newmetasenv, newty) =
1822     Indexing.demod bag
1823       ([],context,CicUniv.oblivion_ugraph) table initgoal in
1824   if changed then
1825     begin
1826       let oldproof = Equality.Exact bo in
1827       let proofterm,_ = 
1828         Equality.build_goal_proof (~contextualize:false) (~forward:true) bag
1829           eq_uri newproof oldproof ty [] context newmetasenv
1830       in
1831       if newmetasenv <> [] then 
1832         raise (ProofEngineTypes.Fail (lazy ("metasenv not empty")))
1833       else
1834         begin
1835           assert_proof_is_valid proofterm newmetasenv context newty;
1836           match is_subsumed universe context newty with
1837             | Some t -> raise 
1838                 (ProofEngineTypes.Fail (lazy ("subsumed by " ^ CicPp.ppterm t)))
1839             | None -> close_type proofterm newty context 
1840         end
1841     end
1842   else (* if newty = ty then *)
1843     raise (ProofEngineTypes.Fail (lazy "no progress"))
1844   (*else ProofEngineTypes.apply_tactic 
1845     (ReductionTactics.simpl_tac
1846       ~pattern:(ProofEngineTypes.conclusion_pattern None)) initialstatus*)
1847 ;;      
1848
1849
1850 (* NEW DEMODULATE *)
1851 let demodulate_tac ~dbd ~universe ~params:(univ, params) (proof,goal)= 
1852   let curi,metasenv,_subst,pbo,pty, attrs = proof in
1853   let metano,context,ty = CicUtil.lookup_meta goal metasenv in
1854   let universe = universe_of_params metasenv context universe univ in
1855   let irl = CicMkImplicit.identity_relocation_list_for_metavariable context in
1856   let initgoal = [], metasenv, ty in
1857   let eq_uri = 
1858     match LibraryObjects.eq_URI () with
1859       | Some (uri) -> uri
1860       | None -> raise (ProofEngineTypes.Fail (lazy "equality not declared")) in
1861   (* let eq_uri = eq_of_goal ty in *)
1862   let (active,passive,bag), cache, maxm =
1863      init_cache_and_tables 
1864        ~dbd false false true true universe (proof,goal) 
1865   in
1866   let equalities = (Saturation.list_of_passive passive) in
1867   (* we demodulate using both actives passives *)
1868   let table = 
1869     List.fold_left 
1870       (fun tbl eq -> Indexing.index tbl eq) 
1871       (snd active) equalities
1872   in
1873   let changed,(newproof,newmetasenv, newty) =
1874     (* Indexing.demodulation_goal bag *)
1875       Indexing.demod bag
1876       (metasenv,context,CicUniv.oblivion_ugraph) table initgoal 
1877   in
1878   if changed then
1879     begin
1880       let opengoal = Equality.Exact (Cic.Meta(maxm,irl)) in
1881       let proofterm,_ = 
1882         Equality.build_goal_proof (~contextualize:false) bag
1883           eq_uri newproof opengoal ty [] context metasenv
1884       in
1885         let extended_metasenv = (maxm,context,newty)::metasenv in
1886         let extended_status = 
1887           (curi,extended_metasenv,_subst,pbo,pty, attrs),goal in
1888         let (status,newgoals) = 
1889           ProofEngineTypes.apply_tactic 
1890             (PrimitiveTactics.apply_tac ~term:proofterm)
1891             extended_status in
1892         (status,maxm::newgoals)
1893     end
1894   else (* if newty = ty then *)
1895     raise (ProofEngineTypes.Fail (lazy "no progress"))
1896   (*else ProofEngineTypes.apply_tactic 
1897     (ReductionTactics.simpl_tac
1898       ~pattern:(ProofEngineTypes.conclusion_pattern None)) initialstatus*)
1899 ;;
1900
1901 let demodulate_tac ~dbd ~params ~universe = 
1902   ProofEngineTypes.mk_tactic (demodulate_tac ~dbd ~params ~universe);;
1903
1904 let pp_proofterm = Equality.pp_proofterm;;
1905
1906 let revision = "$Revision$";;
1907 let size_and_depth context metasenv t = 100, 100