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