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