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