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