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