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