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