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