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