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