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