]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/ng_tactics/nnAuto.ml
some experiment filtering with height
[helm.git] / helm / software / components / ng_tactics / nnAuto.ml
1 (*
2     ||M||  This file is part of HELM, an Hypertextual, Electronic        
3     ||A||  Library of Mathematics, developed at the Computer Science     
4     ||T||  Department, University of Bologna, Italy.                     
5     ||I||                                                                 
6     ||T||  HELM is free software; you can redistribute it and/or         
7     ||A||  modify it under the terms of the GNU General Public License   
8     \   /  version 2 or (at your option) any later version.      
9      \ /   This software is distributed as is, NO WARRANTY.     
10       V_______________________________________________________________ *)
11
12 open Printf
13
14 let debug = ref false
15 let debug_print ?(depth=0) s = 
16   if !debug then prerr_endline (String.make depth '\t'^Lazy.force s) else ()
17 (* let print = debug_print *)
18 let print ?(depth=0) s = 
19   prerr_endline (String.make depth '\t'^Lazy.force s) 
20
21 let debug_do f = if !debug then f () else ()
22
23 open Continuationals.Stack
24 open NTacStatus
25 module Ast = CicNotationPt
26 let app_counter = ref 0
27
28 (* ======================= utility functions ========================= *)
29 module IntSet = Set.Make(struct type t = int let compare = compare end)
30
31 let get_sgoalty status g =
32  let _,_,metasenv,subst,_ = status#obj in
33  try
34    let _, ctx, ty = NCicUtils.lookup_meta g metasenv in
35    let ty = NCicUntrusted.apply_subst subst ctx ty in
36    let ctx = NCicUntrusted.apply_subst_context 
37      ~fix_projections:true subst ctx
38    in
39      NTacStatus.mk_cic_term ctx ty
40  with NCicUtils.Meta_not_found _ as exn -> fail ~exn (lazy "get_sgoalty")
41 ;;
42
43 let deps status g =
44   let gty = get_sgoalty status g in
45   metas_of_term status gty
46 ;;
47
48 let menv_closure status gl = 
49   let rec closure acc = function
50     | [] -> acc
51     | x::l when IntSet.mem x acc -> closure acc l
52     | x::l -> closure (IntSet.add x acc) (deps status x @ l)
53   in closure IntSet.empty gl
54 ;;
55
56 (* we call a "fact" an object whose hypothesis occur in the goal 
57    or in types of goal-variables *)
58 let is_a_fact status ty =  
59   let status, ty, metas = saturate ~delta:0 status ty in
60   debug_print (lazy ("saturated ty :" ^ (ppterm status ty)));
61   let g_metas = metas_of_term status ty in
62   let clos = menv_closure status g_metas in
63   (* let _,_,metasenv,_,_ = status#obj in *)
64   let menv = 
65     List.fold_left
66       (fun acc m ->
67          let _, m = term_of_cic_term status m (ctx_of m) in
68          match m with 
69          | NCic.Meta(i,_) -> IntSet.add i acc
70          | _ -> assert false)
71       IntSet.empty metas
72   in IntSet.subset menv clos;;
73
74 let is_a_fact_obj s uri = 
75   let obj = NCicEnvironment.get_checked_obj uri in
76   match obj with
77     | (_,_,[],[],NCic.Constant(_,_,Some(t),ty,_)) ->
78         is_a_fact s (mk_cic_term [] ty)
79 (* aggiungere i costruttori *)
80     | _ -> false
81
82 let is_a_fact_ast status subst metasenv ctx cand = 
83  debug_print ~depth:0 
84    (lazy ("------- checking " ^ CicNotationPp.pp_term cand)); 
85  let status, t = disambiguate status ctx ("",0,cand) None in
86  let status,t = term_of_cic_term status t ctx in
87  let ty = NCicTypeChecker.typeof subst metasenv ctx t in
88    is_a_fact status (mk_cic_term ctx ty)
89
90 let current_goal status = 
91   let open_goals = head_goals status#stack in
92   assert (List.length open_goals  = 1);
93   let open_goal = List.hd open_goals in
94   let gty = get_goalty status open_goal in
95   let ctx = ctx_of gty in
96     open_goal, ctx, gty
97
98
99 (* =============================== paramod =========================== *)
100 let solve fast status eq_cache goal =
101   let f = 
102     if fast then NCicParamod.fast_eq_check
103     else NCicParamod.paramod in
104   let n,h,metasenv,subst,o = status#obj in
105   let gname, ctx, gty = List.assoc goal metasenv in
106   let gty = NCicUntrusted.apply_subst subst ctx gty in
107   let build_status (pt, _, metasenv, subst) =
108     try
109       debug_print (lazy ("refining: "^(NCicPp.ppterm ctx subst metasenv pt)));
110       let stamp = Unix.gettimeofday () in 
111       let metasenv, subst, pt, pty =
112         NCicRefiner.typeof status
113          (* (status#set_coerc_db NCicCoercion.empty_db) *)
114           metasenv subst ctx pt None in
115         debug_print (lazy ("refined: "^(NCicPp.ppterm ctx subst metasenv pt)));
116         debug_print (lazy ("synt: "^(NCicPp.ppterm ctx subst metasenv pty)));
117         let metasenv, subst =
118           NCicUnification.unify status metasenv subst ctx gty pty 
119         (* the previous code is much less expensive than directly refining
120            pt with expected type pty 
121            in 
122            prerr_endline ("exp: "^(NCicPp.ppterm ctx subst metasenv gty));
123            NCicRefiner.typeof 
124              (status#set_coerc_db NCicCoercion.empty_db) 
125              metasenv subst ctx pt (Some gty) *)
126         in 
127           debug_print (lazy (Printf.sprintf "Refined in %fs"
128                      (Unix.gettimeofday() -. stamp))); 
129           let status = status#set_obj (n,h,metasenv,subst,o) in
130           let metasenv = List.filter (fun j,_ -> j <> goal) metasenv in
131           let subst = (goal,(gname,ctx,pt,pty)) :: subst in
132             Some (status#set_obj (n,h,metasenv,subst,o))
133     with 
134         NCicRefiner.RefineFailure msg 
135       | NCicRefiner.Uncertain msg ->
136           debug_print (lazy ("WARNING: refining in fast_eq_check failed" ^
137                         snd (Lazy.force msg))); None
138       | NCicRefiner.AssertFailure msg -> 
139           debug_print (lazy ("WARNING: refining in fast_eq_check failed" ^
140                         Lazy.force msg)); None
141       | _ -> None
142     in
143     HExtlib.filter_map build_status
144       (f status metasenv subst ctx eq_cache (NCic.Rel ~-1,gty))
145 ;;
146
147 let fast_eq_check eq_cache status goal =
148   match solve true status eq_cache goal with
149   | [] -> raise (Error (lazy "no proof found",None))
150   | s::_ -> s
151 ;;
152
153 let dist_fast_eq_check eq_cache s = 
154   NTactics.distribute_tac (fast_eq_check eq_cache) s
155 ;;
156
157 let auto_eq_check eq_cache status =
158   try 
159     let s = dist_fast_eq_check eq_cache status in
160       [s]
161   with
162     | Error _ -> []
163 ;;
164
165 (* warning: ctx is supposed to be already instantiated w.r.t subst *)
166 let index_local_equations eq_cache status =
167   let open_goals = head_goals status#stack in
168   let open_goal = List.hd open_goals in
169   let ngty = get_goalty status open_goal in
170   let ctx = ctx_of ngty in
171   let c = ref 0 in
172   List.fold_left 
173     (fun eq_cache _ ->
174        c:= !c+1;
175        let t = NCic.Rel !c in
176          try
177            let ty = NCicTypeChecker.typeof [] [] ctx t in
178            if is_a_fact status (mk_cic_term ctx ty) then
179              (debug_print(lazy("eq indexing " ^ (NCicPp.ppterm ctx [] [] ty)));
180               NCicParamod.forward_infer_step eq_cache t ty)
181            else 
182              (debug_print (lazy ("not a fact: " ^ (NCicPp.ppterm ctx [] [] ty)));
183               eq_cache)
184          with 
185            | NCicTypeChecker.TypeCheckerFailure _
186            | NCicTypeChecker.AssertFailure _ -> eq_cache) 
187     eq_cache ctx
188 ;;
189
190 let fast_eq_check_tac ~params s = 
191   let unit_eq = index_local_equations s#eq_cache s in   
192   dist_fast_eq_check unit_eq s
193 ;;
194
195 let paramod eq_cache status goal =
196   match solve false status eq_cache goal with
197   | [] -> raise (Error (lazy "no proof found",None))
198   | s::_ -> s
199 ;;
200
201 let paramod_tac ~params s = 
202   let unit_eq = index_local_equations s#eq_cache s in   
203   NTactics.distribute_tac (paramod unit_eq) s
204 ;;
205
206 (*
207 let fast_eq_check_tac_all  ~params eq_cache status = 
208   let g,_,_ = current_goal status in
209   let allstates = fast_eq_check_all status eq_cache g in
210   let pseudo_low_tac s _ _ = s in
211   let pseudo_low_tactics = 
212     List.map pseudo_low_tac allstates 
213   in
214     List.map (fun f -> NTactics.distribute_tac f status) pseudo_low_tactics
215 ;;
216 *)
217
218 (*
219 let demod status eq_cache goal =
220   let n,h,metasenv,subst,o = status#obj in
221   let gname, ctx, gty = List.assoc goal metasenv in
222   let gty = NCicUntrusted.apply_subst subst ctx gty in
223
224 let demod_tac ~params s = 
225   let unit_eq = index_local_equations s#eq_cache s in   
226   dist_fast_eq_check unit_eq s
227 *)
228
229 (*************** subsumption ****************)
230
231 let close_wrt_context =
232   List.fold_left 
233     (fun ty ctx_entry -> 
234         match ctx_entry with 
235        | name, NCic.Decl t -> NCic.Prod(name,t,ty)
236        | name, NCic.Def(bo, _) -> NCicSubstitution.subst bo ty)
237 ;;
238
239 let args_for_context ?(k=1) ctx =
240   let _,args =
241     List.fold_left 
242       (fun (n,l) ctx_entry -> 
243          match ctx_entry with 
244            | name, NCic.Decl t -> n+1,NCic.Rel(n)::l
245            | name, NCic.Def(bo, _) -> n+1,l)
246       (k,[]) ctx in
247     args
248
249 let constant_for_meta ctx ty i =
250   let name = "cic:/foo"^(string_of_int i)^".con" in
251   let uri = NUri.uri_of_string name in
252   let ty = close_wrt_context ty ctx in
253   (* prerr_endline (NCicPp.ppterm [] [] [] ty); *)
254   let attr = (`Generated,`Definition,`Local) in
255   let obj = NCic.Constant([],name,None,ty,attr) in
256     (* Constant  of relevance * string * term option * term * c_attr *)
257     (uri,0,[],[],obj)
258
259 (* not used *)
260 let refresh metasenv =
261   List.fold_left 
262     (fun (metasenv,subst) (i,(iattr,ctx,ty)) ->
263        let ikind = NCicUntrusted.kind_of_meta iattr in
264        let metasenv,j,instance,ty = 
265          NCicMetaSubst.mk_meta ~attrs:iattr 
266            metasenv ctx ~with_type:ty ikind in
267        let s_entry = i,(iattr, ctx, instance, ty) in
268        let metasenv = List.filter (fun x,_ -> i <> x) metasenv in
269          metasenv,s_entry::subst) 
270       (metasenv,[]) metasenv
271
272 (* close metasenv returns a ground instance of all the metas in the
273 metasenv, insantiatied with axioms, and the list of these axioms *)
274 let close_metasenv metasenv subst = 
275   (*
276   let metasenv = NCicUntrusted.apply_subst_metasenv subst metasenv in
277   *)
278   let metasenv = NCicUntrusted.sort_metasenv subst metasenv in 
279     List.fold_left 
280       (fun (subst,objs) (i,(iattr,ctx,ty)) ->
281          let ty = NCicUntrusted.apply_subst subst ctx ty in
282          let ctx = 
283            NCicUntrusted.apply_subst_context ~fix_projections:true 
284              subst ctx in
285          let (uri,_,_,_,obj) as okind = 
286            constant_for_meta ctx ty i in
287          try
288            NCicEnvironment.check_and_add_obj okind;
289            let iref = NReference.reference_of_spec uri NReference.Decl in
290            let iterm =
291              let args = args_for_context ctx in
292                if args = [] then NCic.Const iref 
293                else NCic.Appl(NCic.Const iref::args)
294            in
295            (* prerr_endline (NCicPp.ppterm ctx [] [] iterm); *)
296            let s_entry = i, ([], ctx, iterm, ty)
297            in s_entry::subst,okind::objs
298          with _ -> assert false)
299       (subst,[]) metasenv
300 ;;
301
302 let ground_instances status gl =
303   let _,_,metasenv,subst,_ = status#obj in
304   let subset = menv_closure status gl in
305   let submenv = List.filter (fun (x,_) -> IntSet.mem x subset) metasenv in
306 (*
307   let submenv = metasenv in
308 *)
309   let subst, objs = close_metasenv submenv subst in
310   try
311     List.iter
312       (fun i -> 
313          let (_, ctx, t, _) = List.assoc i subst in
314            debug_print (lazy (NCicPp.ppterm ctx [] [] t));
315            List.iter 
316              (fun (uri,_,_,_,_) as obj -> 
317                 NCicEnvironment.invalidate_item (`Obj (uri, obj))) 
318              objs;
319            ())
320       gl
321   with
322       Not_found -> assert false 
323   (* (ctx,t) *)
324 ;;
325
326 let replace_meta i args target = 
327   let rec aux k = function
328     (* TODO: local context *)
329     | NCic.Meta (j,lc) when i = j ->
330         (match args with
331            | [] -> NCic.Rel 1
332            | _ -> let args = 
333                List.map (NCicSubstitution.subst_meta lc) args in
334                NCic.Appl(NCic.Rel k::args))
335     | NCic.Meta (j,lc) as m ->
336         (match lc with
337            _,NCic.Irl _ -> m
338          | n,NCic.Ctx l ->
339             NCic.Meta
340              (i,(0,NCic.Ctx
341                  (List.map (fun t ->
342                    aux k (NCicSubstitution.lift n t)) l))))
343     | t -> NCicUtils.map (fun _ k -> k+1) k aux t
344  in
345    aux 1 target
346 ;;
347
348 let close_wrt_metasenv subst =
349   List.fold_left 
350     (fun ty (i,(iattr,ctx,mty)) ->
351        let mty = NCicUntrusted.apply_subst subst ctx mty in
352        let ctx = 
353          NCicUntrusted.apply_subst_context ~fix_projections:true 
354            subst ctx in
355        let cty = close_wrt_context mty ctx in
356        let name = "foo"^(string_of_int i) in
357        let ty = NCicSubstitution.lift 1 ty in
358        let args = args_for_context ~k:1 ctx in
359          (* prerr_endline (NCicPp.ppterm ctx [] [] iterm); *)
360        let ty = replace_meta i args ty
361        in
362        NCic.Prod(name,cty,ty))
363 ;;
364
365 let close status g =
366   let _,_,metasenv,subst,_ = status#obj in
367   let subset = menv_closure status [g] in
368   let subset = IntSet.remove g subset in
369   let elems = IntSet.elements subset in 
370   let _, ctx, ty = NCicUtils.lookup_meta g metasenv in
371   let ty = NCicUntrusted.apply_subst subst ctx ty in
372   debug_print (lazy ("metas in " ^ (NCicPp.ppterm ctx [] metasenv ty)));
373   debug_print (lazy (String.concat ", " (List.map string_of_int elems)));
374   let submenv = List.filter (fun (x,_) -> IntSet.mem x subset) metasenv in
375   let submenv = List.rev (NCicUntrusted.sort_metasenv subst submenv) in 
376 (*  
377     let submenv = metasenv in
378 *)
379   let ty = close_wrt_metasenv subst ty submenv in
380     debug_print (lazy (NCicPp.ppterm ctx [] [] ty));
381     ctx,ty
382 ;;
383
384
385
386 (* =================================== auto =========================== *)
387 (****************** AUTO ********************
388
389 let calculate_timeout flags = 
390     if flags.timeout = 0. then 
391       (debug_print (lazy "AUTO WITH NO TIMEOUT");
392        {flags with timeout = infinity})
393     else 
394       flags 
395 ;;
396 let is_equational_case goalty flags =
397   let ensure_equational t = 
398     if is_an_equational_goal t then true 
399     else false
400   in
401   (flags.use_paramod && is_an_equational_goal goalty) || 
402   (flags.use_only_paramod && ensure_equational goalty)
403 ;;
404
405 type menv = Cic.metasenv
406 type subst = Cic.substitution
407 type goal = ProofEngineTypes.goal * int * AutoTypes.sort
408 let candidate_no = ref 0;;
409 type candidate = int * Cic.term Lazy.t
410 type cache = AutoCache.cache
411
412 type fail = 
413   (* the goal (mainly for depth) and key of the goal *)
414   goal * AutoCache.cache_key
415 type op = 
416   (* goal has to be proved *)
417   | D of goal 
418   (* goal has to be cached as a success obtained using candidate as the first
419    * step *)
420   | S of goal * AutoCache.cache_key * candidate * int 
421 type elem = 
422   (* menv, subst, size, operations done (only S), operations to do, failures to cache if any op fails *)
423   menv * subst * int * op list * op list * fail list 
424 type status = 
425   (* list of computations that may lead to the solution: all op list will
426    * end with the same (S(g,_)) *)
427   elem list
428 type auto_result = 
429   (* menv, subst, alternatives, tables, cache *)
430   | Proved of menv * subst * elem list * AutomationCache.tables * cache 
431   | Gaveup of AutomationCache.tables * cache 
432
433
434 (* the status exported to the external observer *)  
435 type auto_status = 
436   (* context, (goal,candidate) list, and_list, history *)
437   Cic.context * (int * Cic.term * bool * int * (int * Cic.term Lazy.t) list) list * 
438   (int * Cic.term * int) list * Cic.term Lazy.t list
439
440 let d_prefix l =
441   let rec aux acc = function
442     | (D g)::tl -> aux (acc@[g]) tl
443     | _ -> acc
444   in
445     aux [] l
446 ;;
447
448 let calculate_goal_ty (goalno,_,_) s m = 
449   try
450     let _,cc,goalty = CicUtil.lookup_meta goalno m in
451     (* XXX applicare la subst al contesto? *)
452     Some (cc, CicMetaSubst.apply_subst s goalty)
453   with CicUtil.Meta_not_found i when i = goalno -> None
454 ;;
455
456 let calculate_closed_goal_ty (goalno,_,_) s = 
457   try
458     let cc,_,goalty = List.assoc goalno s in
459     (* XXX applicare la subst al contesto? *)
460     Some (cc, CicMetaSubst.apply_subst s goalty)
461   with Not_found -> 
462     None
463 ;;
464
465 let pp_status ctx status = 
466   if debug then 
467   let names = Utils.names_of_context ctx in
468   let pp x = 
469     let x = 
470       ProofEngineReduction.replace 
471         ~equality:(fun a b -> match b with Cic.Meta _ -> true | _ -> false) 
472           ~what:[Cic.Rel 1] ~with_what:[Cic.Implicit None] ~where:x
473     in
474     CicPp.pp x names
475   in
476   let string_of_do m s (gi,_,_ as g) d =
477     match calculate_goal_ty g s m with
478     | Some (_,gty) -> Printf.sprintf "D(%d, %s, %d)" gi (pp gty) d
479     | None -> Printf.sprintf "D(%d, _, %d)" gi d
480   in
481   let string_of_s m su k (ci,ct) gi =
482     Printf.sprintf "S(%d, %s, %s, %d)" gi (pp k) (pp (Lazy.force ct)) ci
483   in
484   let string_of_ol m su l =
485     String.concat " | " 
486       (List.map 
487         (function 
488           | D (g,d,s) -> string_of_do m su (g,d,s) d 
489           | S ((gi,_,_),k,c,_) -> string_of_s m su k c gi) 
490         l)
491   in
492   let string_of_fl m s fl = 
493     String.concat " | " 
494       (List.map (fun ((i,_,_),ty) -> 
495          Printf.sprintf "(%d, %s)" i (pp ty)) fl)
496   in
497   let rec aux = function
498     | [] -> ()
499     | (m,s,_,_,ol,fl)::tl ->
500         Printf.eprintf "< [%s] ;;; [%s]>\n" 
501           (string_of_ol m s ol) (string_of_fl m s fl);
502         aux tl
503   in
504     Printf.eprintf "-------------------------- status -------------------\n";
505     aux status;
506     Printf.eprintf "-----------------------------------------------------\n";
507 ;;
508   
509 let auto_status = ref [] ;;
510 let auto_context = ref [];;
511 let in_pause = ref false;;
512 let pause b = in_pause := b;;
513 let cond = Condition.create ();;
514 let mutex = Mutex.create ();;
515 let hint = ref None;;
516 let prune_hint = ref [];;
517
518 let step _ = Condition.signal cond;;
519 let give_hint n = hint := Some n;;
520 let give_prune_hint hint =
521   prune_hint := hint :: !prune_hint
522 ;;
523
524 let check_pause _ =
525   if !in_pause then
526     begin
527       Mutex.lock mutex;
528       Condition.wait cond mutex;
529       Mutex.unlock mutex
530     end
531 ;;
532
533 let get_auto_status _ = 
534   let status = !auto_status in
535   let and_list,elems,last = 
536     match status with
537     | [] -> [],[],[]
538     | (m,s,_,don,gl,fail)::tl ->
539         let and_list = 
540           HExtlib.filter_map 
541             (fun (id,d,_ as g) -> 
542               match calculate_goal_ty g s m with
543               | Some (_,x) -> Some (id,x,d) | None -> None)
544             (d_goals gl)
545         in
546         let rows = 
547           (* these are the S goalsin the or list *)
548           let orlist = 
549             List.map
550               (fun (m,s,_,don,gl,fail) -> 
551                 HExtlib.filter_map
552                   (function S (g,k,c,_) -> Some (g,k,c) | _ -> None) 
553                   (List.rev don @ gl))
554               status
555           in
556           (* this function eats id from a list l::[id,x] returning x, l *)
557           let eat_tail_if_eq id l = 
558             let rec aux (s, l) = function
559               | [] -> s, l
560               | ((id1,_,_),k1,c)::tl when id = id1 ->
561                   (match s with
562                   | None -> aux (Some c,l) tl
563                   | Some _ -> assert false)
564               | ((id1,_,_),k1,c as e)::tl -> aux (s, e::l) tl
565             in
566             let c, l = aux (None, []) l in
567             c, List.rev l
568           in
569           let eat_in_parallel id l =
570             let rec aux (b,eaten, new_l as acc) l =
571               match l with
572               | [] -> acc
573               | l::tl ->
574                   match eat_tail_if_eq id l with
575                   | None, l -> aux (b@[false], eaten, new_l@[l]) tl
576                   | Some t,l -> aux (b@[true],eaten@[t], new_l@[l]) tl
577             in
578             aux ([],[],[]) l
579           in
580           let rec eat_all rows l =
581             match l with
582             | [] -> rows
583             | elem::or_list ->
584                 match List.rev elem with
585                 | ((to_eat,depth,_),k,_)::next_lunch ->
586                     let b, eaten, l = eat_in_parallel to_eat l in
587                     let eaten = HExtlib.list_uniq eaten in
588                     let eaten = List.rev eaten in
589                     let b = true (* List.hd (List.rev b) *) in
590                     let rows = rows @ [to_eat,k,b,depth,eaten] in
591                     eat_all rows l
592                 | [] -> eat_all rows or_list
593           in
594           eat_all [] (List.rev orlist)
595         in
596         let history = 
597           HExtlib.filter_map
598             (function (S (_,_,(_,c),_)) -> Some c | _ -> None) 
599             gl 
600         in
601 (*         let rows = List.filter (fun (_,l) -> l <> []) rows in *)
602         and_list, rows, history
603   in
604   !auto_context, elems, and_list, last
605 ;;
606
607 (* Works if there is no dependency over proofs *)
608 let is_a_green_cut goalty =
609   CicUtil.is_meta_closed goalty
610 ;;
611 let rec first_s = function
612   | (D _)::tl -> first_s tl
613   | (S (g,k,c,s))::tl -> Some ((g,k,c,s),tl)
614   | [] -> None
615 ;;
616 let list_union l1 l2 =
617   (* TODO ottimizzare compare *)
618   HExtlib.list_uniq (List.sort compare (l1 @ l1))
619 ;;
620 let rec eq_todo l1 l2 =
621   match l1,l2 with
622   | (D g1) :: tl1,(D g2) :: tl2 when g1=g2 -> eq_todo tl1 tl2
623   | (S (g1,k1,(c1,lt1),i1)) :: tl1, (S (g2,k2,(c2,lt2),i2)) :: tl2
624     when i1 = i2 && g1 = g2 && k1 = k2 && c1 = c2 ->
625       if Lazy.force lt1 = Lazy.force lt2 then eq_todo tl1 tl2 else false
626   | [],[] -> true
627   | _ -> false
628 ;;
629 let eat_head todo id fl orlist = 
630   let rec aux acc = function
631   | [] -> [], acc
632   | (m, s, _, _, todo1, fl1)::tl as orlist -> 
633       let rec aux1 todo1 =
634         match first_s todo1 with
635         | None -> orlist, acc
636         | Some (((gno,_,_),_,_,_), todo11) ->
637             (* TODO confronto tra todo da ottimizzare *)
638             if gno = id && eq_todo todo11 todo then 
639               aux (list_union fl1 acc) tl
640             else 
641               aux1 todo11
642       in
643        aux1 todo1
644   in 
645     aux fl orlist
646 ;;
647 let close_proof p ty menv context = 
648   let metas =
649     List.map fst (CicUtil.metas_of_term p @ CicUtil.metas_of_term ty)
650   in
651   let menv = List.filter (fun (i,_,_) -> List.exists ((=)i) metas) menv in
652   naif_closure p menv context
653 ;;
654 (* XXX capire bene quando aggiungere alla cache *)
655 let add_to_cache_and_del_from_orlist_if_green_cut
656   g s m cache key todo orlist fl ctx size minsize
657
658   let cache = cache_remove_underinspection cache key in
659   (* prima per fare la irl usavamo il contesto vero e proprio e non quello 
660    * canonico! XXX *)
661   match calculate_closed_goal_ty g s with
662   | None -> assert false
663   | Some (canonical_ctx , gty) ->
664       let goalno,depth,sort = g in
665       let irl = mk_irl canonical_ctx in
666       let goal = Cic.Meta(goalno, irl) in
667       let proof = CicMetaSubst.apply_subst s goal in
668       let green_proof, closed_proof = 
669         let b = is_a_green_cut proof in
670         if not b then
671           b, (* close_proof proof gty m ctx *) proof 
672         else
673           b, proof
674       in
675       debug_print (lazy ("TENTATIVE CACHE: " ^ CicPp.ppterm key));
676       if is_a_green_cut key then
677         (* if the initia goal was closed, we cut alternatives *)
678         let _ = debug_print (lazy ("MANGIO: " ^ string_of_int goalno)) in
679         let orlist, fl = eat_head todo goalno fl orlist in
680         let cache = 
681           if size < minsize then 
682             (debug_print (lazy ("NO CACHE: 2 (size <= minsize)"));cache)
683           else 
684           (* if the proof is closed we cache it *)
685           if green_proof then cache_add_success cache key proof
686           else (* cache_add_success cache key closed_proof *) 
687             (debug_print (lazy ("NO CACHE: (no gree proof)"));cache)
688         in
689         cache, orlist, fl, true
690       else
691         let cache = 
692           debug_print (lazy ("TENTATIVE CACHE: " ^ CicPp.ppterm gty));
693           if size < minsize then 
694             (debug_print (lazy ("NO CACHE: (size <= minsize)")); cache) else
695           (* if the substituted goal and the proof are closed we cache it *)
696           if is_a_green_cut gty then
697             if green_proof then cache_add_success cache gty proof
698             else (* cache_add_success cache gty closed_proof *) 
699               (debug_print (lazy ("NO CACHE: (no green proof (gty))"));cache)
700           else (*
701             try
702               let ty, _ =
703                 CicTypeChecker.type_of_aux' ~subst:s 
704                   m ctx closed_proof CicUniv.oblivion_ugraph
705               in
706               if is_a_green_cut ty then 
707                 cache_add_success cache ty closed_proof
708               else cache
709             with
710             | CicTypeChecker.TypeCheckerFailure _ ->*) 
711           (debug_print (lazy ("NO CACHE: (no green gty )"));cache)
712         in
713         cache, orlist, fl, false
714 ;;
715 let close_failures (fl : fail list) (cache : cache) = 
716   List.fold_left 
717     (fun cache ((gno,depth,_),gty) -> 
718       if CicUtil.is_meta_closed gty then
719        ( debug_print (lazy ("FAIL: INDUCED: " ^ string_of_int gno));
720          cache_add_failure cache gty depth) 
721       else
722          cache)
723     cache fl
724 ;;
725 let put_in_subst subst metasenv  (goalno,_,_) canonical_ctx t ty =
726   let entry = goalno, (canonical_ctx, t,ty) in
727   assert_subst_are_disjoint subst [entry];
728   let subst = entry :: subst in
729   
730   let metasenv = CicMetaSubst.apply_subst_metasenv subst metasenv in
731
732   subst, metasenv
733 ;;
734
735 let mk_fake_proof metasenv subst (goalno,_,_) goalty context = 
736   None,metasenv,subst ,(lazy (Cic.Meta(goalno,mk_irl context))),goalty, [] 
737 ;;
738
739 let equational_case 
740   tables cache depth fake_proof goalno goalty subst context 
741     flags
742 =
743   let active,passive,bag = tables in
744   let ppterm = ppterm context in
745   let status = (fake_proof,goalno) in
746     if flags.use_only_paramod then
747       begin
748         debug_print (lazy ("PARAMODULATION SU: " ^ 
749                          string_of_int goalno ^ " " ^ ppterm goalty ));
750         let goal_steps, saturation_steps, timeout =
751           max_int,max_int,flags.timeout 
752         in
753         match
754           Saturation.given_clause bag status active passive 
755             goal_steps saturation_steps timeout
756         with 
757           | None, active, passive, bag -> 
758               [], (active,passive,bag), cache, flags
759           | Some(subst',(_,metasenv,_subst,proof,_, _),open_goals),active,
760             passive,bag ->
761               assert_subst_are_disjoint subst subst';
762               let subst = subst@subst' in
763               let open_goals = 
764                 order_new_goals metasenv subst open_goals ppterm 
765               in
766               let open_goals = 
767                 List.map (fun (x,sort) -> x,depth-1,sort) open_goals 
768               in
769               incr candidate_no;
770               [(!candidate_no,proof),metasenv,subst,open_goals], 
771                 (active,passive,bag), cache, flags
772       end
773     else
774       begin
775         debug_print (lazy ("NARROWING DEL GOAL: " ^ 
776                          string_of_int goalno ^ " " ^ ppterm goalty ));
777         let goal_steps, saturation_steps, timeout =
778           1,0,flags.timeout 
779         in
780         match
781           Saturation.solve_narrowing bag status active passive goal_steps 
782         with 
783           | None, active, passive, bag -> 
784               [], (active,passive,bag), cache, flags
785           | Some(subst',(_,metasenv,_subst,proof,_, _),open_goals),active,
786             passive,bag ->
787               assert_subst_are_disjoint subst subst';
788               let subst = subst@subst' in
789               let open_goals = 
790                 order_new_goals metasenv subst open_goals ppterm 
791               in
792               let open_goals = 
793                 List.map (fun (x,sort) -> x,depth-1,sort) open_goals 
794               in
795               incr candidate_no;
796               [(!candidate_no,proof),metasenv,subst,open_goals], 
797                 (active,passive,bag), cache, flags
798       end
799 (*
800       begin
801         let params = ([],["use_context","false"]) in
802         let automation_cache = { 
803               AutomationCache.tables = tables ;
804               AutomationCache.univ = Universe.empty; }
805         in
806         try 
807           let ((_,metasenv,subst,_,_,_),open_goals) =
808
809             solve_rewrite ~params ~automation_cache
810               (fake_proof, goalno)
811           in
812           let proof = lazy (Cic.Meta (-1,[])) in
813           [(!candidate_no,proof),metasenv,subst,[]],tables, cache, flags
814         with ProofEngineTypes.Fail _ -> [], tables, cache, flags
815 (*
816         let res = Saturation.all_subsumed bag status active passive in
817         let res' =
818           List.map 
819             (fun (subst',(_,metasenv,_subst,proof,_, _),open_goals) ->
820                assert_subst_are_disjoint subst subst';
821                let subst = subst@subst' in
822                let open_goals = 
823                  order_new_goals metasenv subst open_goals ppterm 
824                in
825                let open_goals = 
826                  List.map (fun (x,sort) -> x,depth-1,sort) open_goals 
827                in
828                incr candidate_no;
829                  (!candidate_no,proof),metasenv,subst,open_goals)
830             res 
831           in
832           res', (active,passive,bag), cache, flags 
833 *)
834       end
835 *)
836 ;;
837
838 let sort_new_elems = 
839  List.sort (fun (_,_,_,l1) (_,_,_,l2) -> 
840          let p1 = List.length (prop_only l1) in 
841          let p2 = List.length (prop_only l2) in
842          if p1 = p2 then List.length l1 - List.length l2 else p1-p2)
843 ;;
844
845
846 let try_candidate dbd
847   goalty tables subst fake_proof goalno depth context cand 
848 =
849   let ppterm = ppterm context in
850   try 
851     let actives, passives, bag = tables in 
852     let (_,metasenv,subst,_,_,_), open_goals =
853        ProofEngineTypes.apply_tactic
854         (PrimitiveTactics.apply_tac ~term:cand)
855         (fake_proof,goalno) 
856     in
857     let tables = actives, passives, 
858       Equality.push_maxmeta bag 
859         (max (Equality.maxmeta bag) (CicMkImplicit.new_meta metasenv subst)) 
860     in
861     debug_print (lazy ("   OK: " ^ ppterm cand));
862     let metasenv = CicRefine.pack_coercion_metasenv metasenv in
863     let open_goals = order_new_goals metasenv subst open_goals ppterm in
864     let open_goals = List.map (fun (x,sort) -> x,depth-1,sort) open_goals in
865     incr candidate_no;
866     Some ((!candidate_no,lazy cand),metasenv,subst,open_goals), tables 
867   with 
868     | ProofEngineTypes.Fail s -> None,tables
869     | CicUnification.Uncertain s ->  None,tables
870 ;;
871
872 let applicative_case dbd
873   tables depth subst fake_proof goalno goalty metasenv context 
874   signature universe cache flags
875
876   (* let goalty_aux = 
877     match goalty with
878     | Cic.Appl (hd::tl) -> 
879         Cic.Appl (hd :: HExtlib.mk_list (Cic.Meta (0,[])) (List.length tl))
880     | _ -> goalty
881   in *)
882   let goalty_aux = goalty in
883   let candidates = 
884     get_candidates flags.skip_trie_filtering universe cache goalty_aux
885   in
886   (* if the goal is an equality we skip the congruence theorems 
887   let candidates =
888     if is_equational_case goalty flags 
889     then List.filter not_default_eq_term candidates 
890     else candidates 
891   in *)
892   let candidates = List.filter (only signature context metasenv) candidates 
893   in
894   let tables, elems = 
895     List.fold_left 
896       (fun (tables,elems) cand ->
897         match 
898           try_candidate dbd goalty
899             tables subst fake_proof goalno depth context cand
900         with
901         | None, tables -> tables, elems
902         | Some x, tables -> tables, x::elems)
903       (tables,[]) candidates
904   in
905   let elems = sort_new_elems elems in
906   elems, tables, cache
907 ;;
908
909 let try_smart_candidate dbd
910   goalty tables subst fake_proof goalno depth context cand 
911 =
912   let ppterm = ppterm context in
913   try
914     let params = ([],[]) in
915     let automation_cache = { 
916           AutomationCache.tables = tables ;
917           AutomationCache.univ = Universe.empty; }
918     in
919     debug_print (lazy ("candidato per " ^ string_of_int goalno 
920       ^ ": " ^ CicPp.ppterm cand));
921 (*
922     let (_,metasenv,subst,_,_,_) = fake_proof in
923     prerr_endline ("metasenv:\n" ^ CicMetaSubst.ppmetasenv [] metasenv);
924     prerr_endline ("subst:\n" ^ CicMetaSubst.ppsubst ~metasenv subst);
925 *)
926     let ((_,metasenv,subst,_,_,_),open_goals) =
927       apply_smart ~dbd ~term:cand ~params ~automation_cache
928         (fake_proof, goalno)
929     in
930     let metasenv = CicRefine.pack_coercion_metasenv metasenv in
931     let open_goals = order_new_goals metasenv subst open_goals ppterm in
932     let open_goals = List.map (fun (x,sort) -> x,depth-1,sort) open_goals in
933     incr candidate_no;
934     Some ((!candidate_no,lazy cand),metasenv,subst,open_goals), tables 
935   with 
936   | ProofEngineTypes.Fail s -> None,tables
937   | CicUnification.Uncertain s ->  None,tables
938 ;;
939
940 let smart_applicative_case dbd
941   tables depth subst fake_proof goalno goalty metasenv context signature
942   universe cache flags
943
944   let goalty_aux = 
945     match goalty with
946     | Cic.Appl (hd::tl) -> 
947         Cic.Appl (hd :: HExtlib.mk_list (Cic.Meta (0,[])) (List.length tl))
948     | _ -> goalty
949   in
950   let smart_candidates = 
951     get_candidates flags.skip_trie_filtering universe cache goalty_aux
952   in
953   let candidates = 
954     get_candidates flags.skip_trie_filtering universe cache goalty
955   in
956   let smart_candidates = 
957     List.filter
958       (fun x -> not(List.mem x candidates)) smart_candidates
959   in 
960   let debug_msg =
961     (lazy ("smart_candidates" ^ " = " ^ 
962              (String.concat "\n" (List.map CicPp.ppterm smart_candidates)))) in
963   debug_print debug_msg;
964   let candidates = List.filter (only signature context metasenv) candidates in
965   let smart_candidates = 
966     List.filter (only signature context metasenv) smart_candidates 
967   in
968 (*
969   let penalty cand depth = 
970     if only signature context metasenv cand then depth else ((prerr_endline (
971     "penalizzo " ^ CicPp.ppterm cand));depth -1)
972   in
973 *)
974   let tables, elems = 
975     List.fold_left 
976       (fun (tables,elems) cand ->
977         match 
978           try_candidate dbd goalty
979             tables subst fake_proof goalno depth context cand
980         with
981         | None, tables ->
982             (* if normal application fails we try to be smart *)
983             (match try_smart_candidate dbd goalty
984                tables subst fake_proof goalno depth context cand
985              with
986                | None, tables -> tables, elems
987                | Some x, tables -> tables, x::elems)
988         | Some x, tables -> tables, x::elems)
989       (tables,[]) candidates
990   in
991   let tables, smart_elems = 
992       List.fold_left 
993         (fun (tables,elems) cand ->
994           match 
995             try_smart_candidate dbd goalty
996               tables subst fake_proof goalno depth context cand
997           with
998           | None, tables -> tables, elems
999           | Some x, tables -> tables, x::elems)
1000         (tables,[]) smart_candidates
1001   in
1002   let elems = sort_new_elems (elems @ smart_elems) in
1003   elems, tables, cache
1004 ;;
1005
1006 let equational_and_applicative_case dbd
1007   signature universe flags m s g gty tables cache context 
1008 =
1009   let goalno, depth, sort = g in
1010   let fake_proof = mk_fake_proof m s g gty context in
1011   if is_equational_case gty flags then
1012     let elems,tables,cache, flags =
1013       equational_case tables cache
1014         depth fake_proof goalno gty s context flags 
1015     in
1016     let more_elems, tables, cache =
1017       if flags.use_only_paramod then
1018         [],tables, cache
1019       else
1020         applicative_case dbd
1021           tables depth s fake_proof goalno 
1022             gty m context signature universe cache flags
1023     in
1024       elems@more_elems, tables, cache, flags            
1025   else
1026     let elems, tables, cache =
1027       match LibraryObjects.eq_URI () with
1028       | Some _ ->
1029          smart_applicative_case dbd tables depth s fake_proof goalno 
1030            gty m context signature universe cache flags
1031       | None -> 
1032          applicative_case dbd tables depth s fake_proof goalno 
1033            gty m context signature universe cache flags
1034     in
1035       elems, tables, cache, flags  
1036 ;;
1037 let rec condition_for_hint i = function
1038   | [] -> false
1039   | S (_,_,(j,_),_):: tl -> j <> i (* && condition_for_hint i tl *)
1040   | _::tl -> condition_for_hint i tl
1041 ;;
1042 let prunable_for_size flags s m todo =
1043   let rec aux b = function
1044     | (S _)::tl -> aux b tl
1045     | (D (_,_,T))::tl -> aux b tl
1046     | (D g)::tl -> 
1047         (match calculate_goal_ty g s m with
1048           | None -> aux b tl
1049           | Some (canonical_ctx, gty) -> 
1050             let gsize, _ = 
1051               Utils.weight_of_term 
1052                 ~consider_metas:false ~count_metas_occurrences:true gty in
1053             let newb = b || gsize > flags.maxgoalsizefactor in
1054             aux newb tl)
1055     | [] -> b
1056   in
1057     aux false todo
1058
1059 (*
1060 let prunable ty todo =
1061   let rec aux b = function
1062     | (S(_,k,_,_))::tl -> aux (b || Equality.meta_convertibility k ty) tl
1063     | (D (_,_,T))::tl -> aux b tl
1064     | D _::_ -> false
1065     | [] -> b
1066   in
1067     aux false todo
1068 ;;
1069 *)
1070
1071 let prunable menv subst ty todo =
1072   let rec aux = function
1073     | (S(_,k,_,_))::tl ->
1074          (match Equality.meta_convertibility_subst k ty menv with
1075           | None -> aux tl
1076           | Some variant -> 
1077                no_progress variant tl (* || aux tl*))
1078     | (D (_,_,T))::tl -> aux tl
1079     | _ -> false
1080   and no_progress variant = function
1081     | [] -> (*prerr_endline "++++++++++++++++++++++++ no_progress";*) true
1082     | D ((n,_,P) as g)::tl -> 
1083         (match calculate_goal_ty g subst menv with
1084            | None -> no_progress variant tl
1085            | Some (_, gty) -> 
1086                (match calculate_goal_ty g variant menv with
1087                   | None -> assert false
1088                   | Some (_, gty') ->
1089                       if gty = gty' then no_progress variant tl
1090 (* 
1091 (prerr_endline (string_of_int n);
1092  prerr_endline (CicPp.ppterm gty);
1093  prerr_endline (CicPp.ppterm gty');
1094  prerr_endline "---------- subst";
1095  prerr_endline (CicMetaSubst.ppsubst ~metasenv:menv subst);
1096  prerr_endline "---------- variant";
1097  prerr_endline (CicMetaSubst.ppsubst ~metasenv:menv variant);
1098  prerr_endline "---------- menv";
1099  prerr_endline (CicMetaSubst.ppmetasenv [] menv); 
1100                          no_progress variant tl) *)
1101                       else false))
1102     | _::tl -> no_progress variant tl
1103   in
1104     aux todo
1105
1106 ;;
1107 let condition_for_prune_hint prune (m, s, size, don, todo, fl) =
1108   let s = 
1109     HExtlib.filter_map (function S (_,_,(c,_),_) -> Some c | _ -> None) todo 
1110   in
1111   List.for_all (fun i -> List.for_all (fun j -> i<>j) prune) s
1112 ;;
1113 let filter_prune_hint c l =
1114   let prune = !prune_hint in
1115   prune_hint := []; (* possible race... *)
1116   if prune = [] then c,l
1117   else 
1118     cache_reset_underinspection c,      
1119     List.filter (condition_for_prune_hint prune) l
1120 ;;
1121
1122     
1123
1124 let
1125   auto_all_solutions dbd tables universe cache context metasenv gl flags 
1126 =
1127   let signature =
1128     List.fold_left 
1129       (fun set g ->
1130          MetadataConstraints.UriManagerSet.union set 
1131              (MetadataQuery.signature_of metasenv g)
1132        )
1133       MetadataConstraints.UriManagerSet.empty gl 
1134   in
1135   let goals = order_new_goals metasenv [] gl CicPp.ppterm in
1136   let goals = 
1137     List.map 
1138       (fun (x,s) -> D (x,flags.maxdepth,s)) goals 
1139   in
1140   let elems = [metasenv,[],1,[],goals,[]] in
1141   let rec aux tables solutions cache elems flags =
1142     match auto_main dbd tables context flags signature universe cache elems with
1143     | Gaveup (tables,cache) ->
1144         solutions,cache, tables
1145     | Proved (metasenv,subst,others,tables,cache) -> 
1146         if Unix.gettimeofday () > flags.timeout then
1147           ((subst,metasenv)::solutions), cache, tables
1148         else
1149           aux tables ((subst,metasenv)::solutions) cache others flags
1150   in
1151   let rc = aux tables [] cache elems flags in
1152     match rc with
1153     | [],cache,tables -> [],cache,tables
1154     | solutions, cache,tables -> 
1155         let solutions = 
1156           HExtlib.filter_map
1157             (fun (subst,newmetasenv) ->
1158               let opened = 
1159                 ProofEngineHelpers.compare_metasenvs ~oldmetasenv:metasenv ~newmetasenv
1160               in
1161               if opened = [] then Some subst else None)
1162             solutions
1163         in
1164          solutions,cache,tables
1165 ;;
1166
1167 (******************* AUTO ***************)
1168
1169
1170 let auto dbd flags metasenv tables universe cache context metasenv gl =
1171   let initial_time = Unix.gettimeofday() in  
1172   let signature =
1173     List.fold_left 
1174       (fun set g ->
1175          MetadataConstraints.UriManagerSet.union set 
1176              (MetadataQuery.signature_of metasenv g)
1177        )
1178       MetadataConstraints.UriManagerSet.empty gl 
1179   in
1180   let goals = order_new_goals metasenv [] gl CicPp.ppterm in
1181   let goals = List.map (fun (x,s) -> D(x,flags.maxdepth,s)) goals in
1182   let elems = [metasenv,[],1,[],goals,[]] in
1183   match auto_main dbd tables context flags signature universe cache elems with
1184   | Proved (metasenv,subst,_, tables,cache) -> 
1185       debug_print(lazy
1186         ("TIME:"^string_of_float(Unix.gettimeofday()-.initial_time)));
1187       Some (subst,metasenv), cache
1188   | Gaveup (tables,cache) -> 
1189       debug_print(lazy
1190         ("TIME:"^string_of_float(Unix.gettimeofday()-.initial_time)));
1191       None,cache
1192 ;;
1193
1194 let auto_tac ~(dbd:HSql.dbd) ~params:(univ,params) ~automation_cache (proof, goal) =
1195   let flags = flags_of_params params () in
1196   let use_library = flags.use_library in
1197   let universe, tables, cache =
1198     init_cache_and_tables 
1199      ~dbd ~use_library ~use_context:(not flags.skip_context)
1200      automation_cache univ (proof, goal) 
1201   in
1202   let _,metasenv,subst,_,_, _ = proof in
1203   let _,context,goalty = CicUtil.lookup_meta goal metasenv in
1204   let signature = MetadataQuery.signature_of metasenv goal in
1205   let signature = 
1206     List.fold_left 
1207       (fun set t ->
1208          let ty, _ = 
1209            CicTypeChecker.type_of_aux' metasenv context t 
1210              CicUniv.oblivion_ugraph
1211          in
1212          MetadataConstraints.UriManagerSet.union set 
1213            (MetadataConstraints.constants_of ty)
1214        )
1215       signature univ
1216   in
1217   let tables,cache =
1218     if flags.close_more then
1219       close_more 
1220         tables context (proof, goal) 
1221           (auto_all_solutions dbd) signature universe cache 
1222     else tables,cache in
1223   let initial_time = Unix.gettimeofday() in
1224   let (_,oldmetasenv,_,_,_, _) = proof in
1225     hint := None;
1226   let elem = 
1227     metasenv,subst,1,[],[D (goal,flags.maxdepth,P)],[]
1228   in
1229   match auto_main dbd tables context flags signature universe cache [elem] with
1230     | Proved (metasenv,subst,_, tables,cache) -> 
1231         debug_print (lazy 
1232           ("TIME:"^string_of_float(Unix.gettimeofday()-.initial_time)));
1233         let proof,metasenv =
1234         ProofEngineHelpers.subst_meta_and_metasenv_in_proof
1235           proof goal subst metasenv
1236         in
1237         let opened = 
1238           ProofEngineHelpers.compare_metasenvs ~oldmetasenv
1239             ~newmetasenv:metasenv
1240         in
1241           proof,opened
1242     | Gaveup (tables,cache) -> 
1243         debug_print
1244           (lazy ("TIME:"^
1245             string_of_float(Unix.gettimeofday()-.initial_time)));
1246         raise (ProofEngineTypes.Fail (lazy "Auto gave up"))
1247 ;;
1248 *)
1249
1250 (****************** smart application ********************)
1251
1252
1253 let smart_apply t unit_eq status g = 
1254   let n,h,metasenv,subst,o = status#obj in
1255   let gname, ctx, gty = List.assoc g metasenv in
1256   (* let ggty = mk_cic_term context gty in *)
1257   let status, t = disambiguate status ctx t None in
1258   let status,t = term_of_cic_term status t ctx in
1259   let ty = NCicTypeChecker.typeof subst metasenv ctx t in
1260   let ty,metasenv,args = NCicMetaSubst.saturate metasenv subst ctx ty 0 in
1261   let metasenv,j,inst,_ = NCicMetaSubst.mk_meta metasenv ctx `IsTerm in
1262   let status = status#set_obj (n,h,metasenv,subst,o) in
1263   let pterm = if args=[] then t else NCic.Appl(t::args) in
1264   let eq_coerc =       
1265     let uri = 
1266       NUri.uri_of_string "cic:/matita/ng/Plogic/equality/eq_coerc.con" in
1267     let ref = NReference.reference_of_spec uri (NReference.Def(2)) in
1268       NCic.Const ref
1269   in
1270   let smart = 
1271     NCic.Appl[eq_coerc;ty;NCic.Implicit `Type;pterm;inst] in
1272   let smart = mk_cic_term ctx smart in 
1273     try
1274       let status = instantiate status g smart in
1275       let _,_,metasenv,subst,_ = status#obj in
1276       let _,ctx,jty = List.assoc j metasenv in
1277       let jty = NCicUntrusted.apply_subst subst ctx jty in
1278         debug_print(lazy("goal " ^ (NCicPp.ppterm ctx [] [] jty)));
1279         fast_eq_check unit_eq status j
1280     with
1281       | Error _ as e -> debug_print (lazy "error"); raise e
1282
1283 let smart_apply_tac t s =
1284   let unit_eq = index_local_equations s#eq_cache s in   
1285   NTactics.distribute_tac (smart_apply t unit_eq) s
1286
1287 let smart_apply_auto t eq_cache =
1288   NTactics.distribute_tac (smart_apply t eq_cache)
1289
1290
1291 (****************** types **************)
1292
1293
1294 type th_cache = (NCic.context * InvRelDiscriminationTree.t) list
1295
1296 let keys_of_term status t =
1297   let status, orig_ty = typeof status (ctx_of t) t in
1298   let _, ty, _ = saturate ~delta:max_int status orig_ty in
1299   let keys = [ty] in
1300   let keys = 
1301     let _, ty = term_of_cic_term status ty (ctx_of ty) in
1302     match ty with
1303     | NCic.Const (NReference.Ref (_,NReference.Def h)) 
1304     | NCic.Appl (NCic.Const(NReference.Ref(_,NReference.Def h))::_) 
1305        when h > 0 ->
1306          let _,ty,_= saturate status ~delta:(h-1) orig_ty in
1307          ty::keys
1308     | _ -> keys
1309   in
1310   status, keys
1311 ;;
1312
1313 let mk_th_cache status gl = 
1314   List.fold_left 
1315     (fun (status, acc) g ->
1316        let gty = get_goalty status g in
1317        let ctx = ctx_of gty in
1318        debug_print(lazy("th cache for: "^ppterm status gty));
1319        debug_print(lazy("th cache in: "^ppcontext status ctx));
1320        if List.mem_assq ctx acc then status, acc else
1321          let idx = InvRelDiscriminationTree.empty in
1322          let status,_,idx = 
1323            List.fold_left 
1324              (fun (status, i, idx) _ -> 
1325                 let t = mk_cic_term ctx (NCic.Rel i) in
1326                 debug_print(lazy("indexing: "^ppterm status t));
1327                 let status, keys = keys_of_term status t in
1328                 let idx =
1329                   List.fold_left (fun idx k -> 
1330                     InvRelDiscriminationTree.index idx k t) idx keys
1331                 in
1332                 status, i+1, idx)
1333              (status, 1, idx) ctx
1334           in
1335          status, (ctx, idx) :: acc)
1336     (status,[]) gl
1337 ;;
1338
1339 let add_to_th t c ty = 
1340   let key_c = ctx_of t in
1341   if not (List.mem_assq key_c c) then
1342       (key_c ,InvRelDiscriminationTree.index 
1343                InvRelDiscriminationTree.empty ty t ) :: c 
1344   else
1345     let rec replace = function
1346       | [] -> []
1347       | (x, idx) :: tl when x == key_c -> 
1348           (x, InvRelDiscriminationTree.index idx ty t) :: tl
1349       | x :: tl -> x :: replace tl
1350     in 
1351       replace c
1352 ;;
1353
1354 let pp_idx status idx =
1355    InvRelDiscriminationTree.iter idx
1356       (fun k set ->
1357          debug_print(lazy("K: " ^ NCicInverseRelIndexable.string_of_path k));
1358          Ncic_termSet.iter 
1359            (fun t -> debug_print(lazy("\t"^ppterm status t))) 
1360            set)
1361 ;;
1362
1363 let pp_th status = 
1364   List.iter 
1365     (fun ctx, idx ->
1366        debug_print(lazy( "-----------------------------------------------"));
1367        debug_print(lazy( (NCicPp.ppcontext ~metasenv:[] ~subst:[] ctx)));
1368        debug_print(lazy( "||====>  "));
1369        pp_idx status idx)
1370 ;;
1371
1372 let search_in_th gty th = 
1373   let c = ctx_of gty in
1374   let rec aux acc = function
1375    | [] -> (* Ncic_termSet.elements *) acc
1376    | (_::tl) as k ->
1377        try 
1378          let idx = List.assq k th in
1379          let acc = Ncic_termSet.union acc 
1380            (InvRelDiscriminationTree.retrieve_unifiables idx gty)
1381          in
1382          aux acc tl
1383        with Not_found -> aux acc tl
1384   in
1385     aux Ncic_termSet.empty c
1386 ;;
1387
1388 type flags = {
1389         do_types : bool; (* solve goals in Type *)
1390         last : bool; (* last goal: take first solution only  *)
1391         maxwidth : int;
1392         maxsize  : int;
1393         maxdepth : int;
1394         timeout  : float;
1395 }
1396
1397 type cache =
1398     {facts : th_cache; (* positive results *)
1399      under_inspection : th_cache; (* to prune looping *)
1400      unit_eq : NCicParamod.state
1401     }
1402
1403 type sort = T | P
1404 type goal = int * sort (* goal, depth, sort *)
1405 type fail = goal * cic_term
1406 type candidate = int * Ast.term (* unique candidate number, candidate *)
1407
1408 exception Gaveup of IntSet.t (* a sublist of unprovable conjunctive
1409                                 atoms of the input goals *)
1410 exception Proved of NTacStatus.tac_status
1411
1412 let height_of_ref (NReference.Ref (uri, x)) = 
1413   match x with
1414   | NReference.Decl 
1415   | NReference.Ind _ 
1416   | NReference.Con _
1417   | NReference.CoFix _ -> 
1418       let _,height,_,_,_ = NCicEnvironment.get_checked_obj uri in
1419       height 
1420   | NReference.Def h -> h 
1421   | NReference.Fix (_,_,h) -> h 
1422 ;;
1423
1424 let fast_height_of_term t =
1425  let h = ref 0 in
1426  let rec aux =
1427   function
1428      NCic.Meta (_,(_,NCic.Ctx l)) -> List.iter aux l
1429    | NCic.Meta _ -> ()
1430    | NCic.Rel _
1431    | NCic.Sort _ -> ()
1432    | NCic.Implicit _ -> assert false
1433    | NCic.Const nref as t -> 
1434 (*
1435                    prerr_endline (NCicPp.ppterm ~metasenv:[] ~subst:[]
1436                    ~context:[] t ^ ":" ^ string_of_int (height_of_ref nref));            
1437 *)
1438        h := max !h (height_of_ref nref)
1439    | NCic.Prod (_,t1,t2)
1440    | NCic.Lambda (_,t1,t2) -> aux t1; aux t2
1441    | NCic.LetIn (_,s,ty,t) -> aux s; aux ty; aux t
1442    | NCic.Appl l -> List.iter aux l
1443    | NCic.Match (_,outty,t,pl) -> aux outty; aux t; List.iter aux pl
1444  in
1445   aux t; !h
1446 ;;
1447
1448 let height_of_goals status = 
1449   let open_goals = head_goals status#stack in
1450   assert (List.length open_goals > 0);
1451   let h = ref 0 in
1452   List.iter 
1453     (fun open_goal ->
1454       let ty = get_goalty status open_goal in
1455       let context = ctx_of ty in
1456       let _, ty = term_of_cic_term status ty (ctx_of ty) in
1457       h := max !h (fast_height_of_term ty);
1458       List.iter 
1459         (function 
1460         | _, NCic.Decl ty -> h := max !h (fast_height_of_term ty)
1461         | _, NCic.Def (bo,ty) -> 
1462             h := max !h (fast_height_of_term ty);
1463             h := max !h (fast_height_of_term bo);
1464             ) 
1465         context)
1466      open_goals;
1467   prerr_endline ("altezza sequente: " ^ string_of_int !h);
1468   !h
1469 ;;
1470
1471 (* let close_failures _ c = c;; *)
1472 (* let prunable _ _ _ = false;; *)
1473 (* let cache_examine cache gty = `Notfound;; *)
1474 (* let put_in_subst s _ _ _  = s;; *)
1475 (* let add_to_cache_and_del_from_orlist_if_green_cut _ _ c _ _ o f _ = c, o, f, false ;; *)
1476 (* let cache_add_underinspection c _ _ = c;; *)
1477
1478 let init_cache ?(facts=[]) ?(under_inspection=[]) 
1479     ?(unit_eq=NCicParamod.empty_state) _ = 
1480     {facts = facts;
1481      under_inspection = under_inspection;
1482      unit_eq = unit_eq
1483     }
1484
1485 let only signature _context candidate = 
1486         (* TASSI: nel trie ci mettiamo solo il body, non il ty *)
1487   let candidate_ty = 
1488    NCicTypeChecker.typeof ~subst:[] ~metasenv:[] [] candidate
1489   in
1490   let height = fast_height_of_term candidate_ty in
1491   let rc = signature >= height in
1492   if rc = false then
1493           prerr_endline ("Filtro: " ^ NCicPp.ppterm ~context:[] ~subst:[]
1494           ~metasenv:[] candidate ^ ": " ^ string_of_int height)
1495   else 
1496           prerr_endline ("Tengo: " ^ NCicPp.ppterm ~context:[] ~subst:[]
1497           ~metasenv:[] candidate ^ ": " ^ string_of_int height);
1498
1499   rc
1500 ;; 
1501
1502 let candidate_no = ref 0;;
1503
1504 let openg_no status = List.length (head_goals status#stack)
1505
1506 let sort_new_elems l =
1507   List.sort (fun (_,s1) (_,s2) -> openg_no s1 - openg_no s2) l
1508
1509 let try_candidate ?(smart=0) flags depth status eq_cache t =
1510  try
1511    debug_print ~depth (lazy ("------------ try " ^ CicNotationPp.pp_term t));
1512   let status = 
1513     if smart= 0 then NTactics.apply_tac ("",0,t) status 
1514     else if smart = 1 then smart_apply_auto ("",0,t) eq_cache status 
1515     else (* smart = 2: both *)
1516       try NTactics.apply_tac ("",0,t) status 
1517       with Error _ -> 
1518         smart_apply_auto ("",0,t) eq_cache status in 
1519   let og_no = openg_no status in 
1520     if (* og_no > flags.maxwidth || *)
1521       ((depth + 1) = flags.maxdepth && og_no <> 0) then
1522         (debug_print ~depth (lazy "pruned immediately"); None)
1523    else
1524      (incr candidate_no;
1525       Some ((!candidate_no,t),status))
1526  with Error (msg,exn) -> debug_print ~depth (lazy "failed"); None
1527 ;;
1528
1529 let get_candidates ?(smart=true) status cache signature gty =
1530   let universe = status#auto_cache in
1531   let context = ctx_of gty in
1532   let t_ast t = 
1533      let _status, t = term_of_cic_term status t context 
1534      in Ast.NCic t in
1535   let c_ast = function 
1536     | NCic.Const r -> Ast.NRef r | _ -> assert false in
1537   let _, raw_gty = term_of_cic_term status gty context in
1538   let cands = NDiscriminationTree.DiscriminationTree.retrieve_unifiables 
1539         universe raw_gty in
1540   let local_cands = search_in_th gty cache in
1541   let together global local =
1542     List.map c_ast 
1543       (List.filter (only signature context) 
1544         (NDiscriminationTree.TermSet.elements global)) @
1545       List.map t_ast (Ncic_termSet.elements local) in
1546   let candidates = together cands local_cands in
1547   let smart_candidates = 
1548     if smart then
1549       match raw_gty with
1550         | NCic.Appl (hd::tl) -> 
1551             let weak_gty = 
1552               NCic.Appl (hd:: HExtlib.mk_list(NCic.Meta (0,(0,NCic.Irl 0))) 
1553                            (List.length tl)) in
1554             let more_cands = 
1555               NDiscriminationTree.DiscriminationTree.retrieve_unifiables 
1556                 universe weak_gty in
1557             let smart_cands = 
1558               NDiscriminationTree.TermSet.diff more_cands cands in
1559             let cic_weak_gty = mk_cic_term context weak_gty in
1560             let more_local_cands = search_in_th cic_weak_gty cache in
1561             let smart_local_cands = 
1562               Ncic_termSet.diff more_local_cands local_cands in
1563               together smart_cands smart_local_cands  
1564         | _ -> []
1565     else [] 
1566   in
1567     candidates, smart_candidates
1568 ;;
1569
1570 let applicative_case depth signature status flags gty (cache:cache) =
1571   app_counter:= !app_counter+1; 
1572   let _,_,metasenv,subst,_ = status#obj in
1573   let context = ctx_of gty in
1574   let tcache = cache.facts in
1575   let is_eq =   
1576     let status, t = term_of_cic_term status gty context  in 
1577     NCicParamod.is_equation metasenv subst context t 
1578   in
1579   debug_print(lazy (string_of_bool is_eq)); 
1580   let candidates, smart_candidates = 
1581     get_candidates ~smart:(not is_eq) status tcache signature gty in
1582   debug_print ~depth
1583     (lazy ("candidates: " ^ string_of_int (List.length candidates)));
1584   debug_print ~depth
1585     (lazy ("smart candidates: " ^ 
1586              string_of_int (List.length smart_candidates)));
1587 (*
1588   let sm = 0 in 
1589   let smart_candidates = [] in *)
1590   let sm = if is_eq then 0 else 2 in
1591   let maxd = ((depth + 1) = flags.maxdepth) in 
1592   let only_one = flags.last && maxd in
1593   debug_print (lazy ("only_one: " ^ (string_of_bool only_one))); 
1594   debug_print (lazy ("maxd: " ^ (string_of_bool maxd)));
1595   let elems =  
1596     List.fold_left 
1597       (fun elems cand ->
1598          if (only_one && (elems <> [])) then elems 
1599          else 
1600            if (maxd && not(is_a_fact_ast status subst metasenv context cand)) 
1601            then (debug_print (lazy "pruned: not a fact"); elems)
1602          else
1603            match try_candidate (~smart:sm) 
1604              flags depth status cache.unit_eq cand with
1605                | None -> elems
1606                | Some x -> x::elems)
1607       [] candidates
1608   in
1609   let more_elems = 
1610     if only_one && elems <> [] then elems 
1611     else
1612       List.fold_left 
1613         (fun elems cand ->
1614          if (only_one && (elems <> [])) then elems 
1615          else 
1616            if (maxd && not(is_a_fact_ast status subst metasenv context cand)) 
1617            then (debug_print (lazy "pruned: not a fact"); elems)
1618          else
1619            match try_candidate (~smart:1) 
1620              flags depth status cache.unit_eq cand with
1621                | None -> elems
1622                | Some x -> x::elems)
1623         [] smart_candidates
1624   in
1625   elems@more_elems
1626 ;;
1627
1628 exception Found
1629 ;;
1630
1631 (* gty is supposed to be meta-closed *)
1632 let is_subsumed depth status gty cache =
1633   if cache=[] then false else (
1634   debug_print ~depth (lazy("Subsuming " ^ (ppterm status gty))); 
1635   let n,h,metasenv,subst,obj = status#obj in
1636   let ctx = ctx_of gty in
1637   let _ , target = term_of_cic_term status gty ctx in
1638   let target = NCicSubstitution.lift 1 target in 
1639   (* candidates must only be searched w.r.t the given context *)
1640   let candidates = 
1641     try
1642     let idx = List.assq ctx cache in
1643       Ncic_termSet.elements 
1644         (InvRelDiscriminationTree.retrieve_generalizations idx gty)
1645     with Not_found -> []
1646   in
1647   debug_print ~depth
1648     (lazy ("failure candidates: " ^ string_of_int (List.length candidates)));
1649     try
1650       List.iter
1651         (fun t ->
1652            let _ , source = term_of_cic_term status t ctx in
1653            let implication = 
1654              NCic.Prod("foo",source,target) in
1655            let metasenv,j,_,_ = 
1656              NCicMetaSubst.mk_meta  
1657                metasenv ctx ~with_type:implication `IsType in
1658            let status = status#set_obj (n,h,metasenv,subst,obj) in
1659            let status = status#set_stack [([1,Open j],[],[],`NoTag)] in 
1660            try
1661              let status = NTactics.intro_tac "foo" status in
1662              let status =
1663                NTactics.apply_tac ("",0,Ast.NCic (NCic.Rel 1)) status
1664              in 
1665                if (head_goals status#stack = []) then raise Found
1666                else ()
1667            with
1668              | Error _ -> ())
1669         candidates;false
1670     with Found -> debug_print ~depth (lazy "success");true)
1671 ;;
1672
1673 let rec guess_name name ctx = 
1674   if name = "_" then guess_name "auto" ctx else
1675   if not (List.mem_assoc name ctx) then name else
1676   guess_name (name^"'") ctx
1677 ;;
1678
1679 let is_prod status = 
1680   let _, ctx, gty = current_goal status in
1681   let _, raw_gty = term_of_cic_term status gty ctx in
1682   match raw_gty with
1683     | NCic.Prod (name,_,_) -> Some (guess_name name ctx)
1684     | _ -> None
1685
1686 let intro ~depth status facts name =
1687   let status = NTactics.intro_tac name status in
1688   let _, ctx, ngty = current_goal status in
1689   let t = mk_cic_term ctx (NCic.Rel 1) in
1690   let status, keys = keys_of_term status t in
1691   let facts = List.fold_left (add_to_th t) facts keys in
1692     debug_print ~depth (lazy ("intro: "^ name));
1693   (* unprovability is not stable w.r.t introduction *)
1694   status, facts
1695 ;;
1696
1697 let rec intros_facts ~depth status facts =
1698   match is_prod status with
1699     | Some(name) ->
1700         let status,facts =
1701           intro ~depth status facts name
1702         in intros_facts ~depth status facts 
1703     | _ -> status, facts
1704 ;; 
1705
1706 let rec intros ~depth status (cache:cache) =
1707     match is_prod status with
1708       | Some _ ->
1709           let status,facts =
1710             intros_facts ~depth status cache.facts 
1711           in 
1712             (* we reindex the equation from scratch *)
1713           let unit_eq = 
1714             index_local_equations status#eq_cache status in
1715             (* under_inspection must be set to empty *)
1716           status, init_cache ~facts ~unit_eq () 
1717       | _ -> status, cache
1718 ;;
1719
1720 let reduce ~depth status g = 
1721   let n,h,metasenv,subst,o = status#obj in 
1722   let attr, ctx, ty = NCicUtils.lookup_meta g metasenv in
1723   let ty = NCicUntrusted.apply_subst subst ctx ty in
1724   let ty' = NCicReduction.whd ~subst ctx ty in
1725   if ty = ty' then []
1726   else
1727     (debug_print ~depth 
1728       (lazy ("reduced to: "^ NCicPp.ppterm ctx subst metasenv ty'));
1729     let metasenv = 
1730       (g,(attr,ctx,ty'))::(List.filter (fun (i,_) -> i<>g) metasenv) 
1731     in
1732     let status = status#set_obj (n,h,metasenv,subst,o) in
1733     incr candidate_no;
1734     [(!candidate_no,Ast.Ident("__whd",None)),status])
1735 ;;
1736
1737 let do_something signature flags status g depth gty cache =
1738   (* whd *)
1739   let l = reduce ~depth status g in
1740   (* backward aplications *)
1741   let l1 = 
1742     List.map 
1743       (fun s ->
1744          incr candidate_no;
1745          ((!candidate_no,Ast.Ident("__paramod",None)),s))
1746       (auto_eq_check cache.unit_eq status) in
1747   let l2 = 
1748     if (l1 <> []) then []
1749     else applicative_case depth signature status flags gty cache 
1750   (* fast paramodulation *) 
1751   in
1752   (* states in l1 have have an empty set of subgoals: no point to sort them *)
1753     l1 @ (sort_new_elems (l@l2)), cache
1754 ;;
1755
1756 let pp_goal = function
1757   | (_,Continuationals.Stack.Open i) 
1758   | (_,Continuationals.Stack.Closed i) -> string_of_int i 
1759 ;;
1760
1761 let pp_goals status l =
1762   String.concat ", " 
1763     (List.map 
1764        (fun i -> 
1765           let gty = get_goalty status i in
1766             NTacStatus.ppterm status gty)
1767        l)
1768 ;;
1769
1770 module M = 
1771   struct 
1772     type t = int
1773     let compare = Pervasives.compare
1774   end
1775 ;;
1776
1777 module MS = HTopoSort.Make(M)
1778 ;;
1779
1780 let sort_tac status =
1781   let gstatus = 
1782     match status#stack with
1783     | [] -> assert false
1784     | (goals, t, k, tag) :: s ->
1785         let g = head_goals status#stack in
1786         let sortedg = 
1787           (List.rev (MS.topological_sort g (deps status))) in
1788           debug_print (lazy ("old g = " ^ 
1789             String.concat "," (List.map string_of_int g)));
1790           debug_print (lazy ("sorted goals = " ^ 
1791             String.concat "," (List.map string_of_int sortedg)));
1792           let is_it i = function
1793             | (_,Continuationals.Stack.Open j ) 
1794             | (_,Continuationals.Stack.Closed j ) -> i = j
1795           in 
1796           let sorted_goals = 
1797             List.map (fun i -> List.find (is_it i) goals) sortedg
1798           in
1799             (sorted_goals, t, k, tag) :: s
1800   in
1801    status#set_stack gstatus
1802 ;;
1803   
1804 let clean_up_tac status =
1805   let gstatus = 
1806     match status#stack with
1807     | [] -> assert false
1808     | (g, t, k, tag) :: s ->
1809         let is_open = function
1810           | (_,Continuationals.Stack.Open _) -> true
1811           | (_,Continuationals.Stack.Closed _) -> false
1812         in
1813         let g' = List.filter is_open g in
1814           (g', t, k, tag) :: s
1815   in
1816    status#set_stack gstatus
1817 ;;
1818
1819 let focus_tac focus status =
1820   let gstatus = 
1821     match status#stack with
1822     | [] -> assert false
1823     | (g, t, k, tag) :: s ->
1824         let in_focus = function
1825           | (_,Continuationals.Stack.Open i) 
1826           | (_,Continuationals.Stack.Closed i) -> List.mem i focus
1827         in
1828         let focus,others = List.partition in_focus g
1829         in
1830           (* we need to mark it as a BranchTag, otherwise cannot merge later *)
1831           (focus,[],[],`BranchTag) :: (others, t, k, tag) :: s
1832   in
1833    status#set_stack gstatus
1834 ;;
1835
1836 let rec auto_clusters ?(top=false)  
1837     flags signature cache depth status : unit =
1838   debug_print ~depth (lazy "entering auto clusters");
1839   (* ignore(Unix.select [] [] [] 0.01); *)
1840   let status = clean_up_tac status in
1841   let goals = head_goals status#stack in
1842   if goals = [] then raise (Proved status)
1843   else if depth = flags.maxdepth then raise (Gaveup IntSet.empty)
1844   else if List.length goals < 2 then 
1845     auto_main flags signature cache depth status 
1846   else
1847     debug_print ~depth (lazy ("goals = " ^ 
1848       String.concat "," (List.map string_of_int goals)));
1849     let classes = HExtlib.clusters (deps status) goals in
1850     let classes = if top then List.rev classes else classes in
1851       debug_print ~depth
1852         (lazy 
1853            (String.concat "\n" 
1854            (List.map
1855               (fun l -> 
1856                  ("cluster:" ^ String.concat "," (List.map string_of_int l)))
1857            classes)));
1858       let status,b = 
1859         List.fold_left
1860           (fun (status,b) gl -> 
1861              let status = focus_tac gl status in
1862              try 
1863                debug_print ~depth (lazy ("focusing on" ^ 
1864                               String.concat "," (List.map string_of_int gl)));
1865                auto_main flags signature cache depth status; assert false
1866              with 
1867                | Proved(status) -> (NTactics.merge_tac status,true)
1868                | Gaveup _ when top -> (NTactics.merge_tac status,b)
1869           )
1870           (status,false) classes
1871       in if b then raise (Proved status) else raise (Gaveup IntSet.empty)
1872
1873 and
1874
1875 (* the goals returned upon failure are an unsatisfiable subset 
1876    of the initial head goals in the stack *)
1877
1878 auto_main flags signature (cache:cache) depth status: unit =
1879   debug_print ~depth (lazy "entering auto main");
1880   (* ignore(Unix.select [] [] [] 0.01); *)
1881   let status = sort_tac (clean_up_tac status) in
1882   let goals = head_goals status#stack in
1883   match goals with
1884     | [] -> raise (Proved status)
1885     | orig::_ ->
1886         let ng = List.length goals in 
1887         if ng > flags.maxwidth then 
1888           (debug_print (lazy "FAIL WIDTH"); raise (Gaveup IntSet.empty))
1889         else let branch = ng>1 in
1890         if depth = flags.maxdepth then raise (Gaveup IntSet.empty)
1891         else
1892         let status = 
1893           if branch then NTactics.branch_tac status 
1894           else status in
1895         let status, cache = intros ~depth status cache in
1896         let g,gctx, gty = current_goal status in
1897         let ctx,ty = close status g in
1898         let closegty = mk_cic_term ctx ty in
1899         let status, gty = apply_subst status gctx gty in
1900         debug_print ~depth (lazy("Attacking goal " ^ (string_of_int g) ^" : "^ppterm status gty)); 
1901         if is_subsumed depth status closegty cache.under_inspection then 
1902           (debug_print (lazy "SUBSUMED");
1903            raise (Gaveup IntSet.add g IntSet.empty))
1904         else 
1905         let do_flags = 
1906           {flags with last = flags.last && (not branch)} in 
1907         let alternatives, cache = 
1908           do_something signature do_flags status g depth gty cache in
1909         let loop_cache =
1910           let under_inspection = 
1911             add_to_th closegty cache.under_inspection closegty in
1912           {cache with under_inspection = under_inspection} in
1913         let unsat =
1914           List.fold_left
1915             (* the underscore information does not need to be returned
1916                by do_something *)
1917             (fun unsat ((_,t),status) ->
1918                let depth',looping_cache = 
1919                  if t=Ast.Ident("__whd",None) then depth,cache 
1920                  else depth+1, loop_cache in
1921                debug_print (~depth:depth') 
1922                  (lazy ("Case: " ^ CicNotationPp.pp_term t));
1923                let flags' = 
1924                  {flags with maxwidth = flags.maxwidth - ng +1} in
1925                  (* sistemare *)
1926                let flags' = 
1927                  {flags' with last = flags'.last && (not branch)} in 
1928                debug_print 
1929                  (lazy ("auto last: " ^ (string_of_bool flags'.last)));
1930                try auto_clusters flags' signature loop_cache
1931                  depth' status; unsat
1932                with 
1933                  | Proved status ->
1934                      debug_print (~depth:depth') (lazy "proved");
1935                      if branch then 
1936                        let status = NTactics.merge_tac status
1937                        in
1938                          (* old cache, here *)
1939                        let flags = 
1940                          {flags with maxwidth = flags.maxwidth - 1} in 
1941                          try auto_clusters flags signature cache 
1942                            depth status; assert false
1943                          with Gaveup f ->
1944                            debug_print ~depth 
1945                              (lazy ("Unsat1 at depth " ^ (string_of_int depth)
1946                                    ^ ": " ^ 
1947                                    (pp_goals status (IntSet.elements f))));
1948                         (* TODO: cache failures *)
1949                            IntSet.union f unsat
1950                      else raise (Proved status) 
1951                  | Gaveup f -> 
1952                      debug_print (~depth:depth')
1953                        (lazy ("Unsat2 at depth " ^ (string_of_int depth')
1954                               ^ ": " ^ 
1955                               (pp_goals status (IntSet.elements f))));
1956                      (* TODO: cache local failures *)
1957                      unsat)
1958             IntSet.empty alternatives
1959         in
1960           raise (Gaveup IntSet.add orig unsat)
1961 ;;
1962                  
1963 let int name l def = 
1964   try int_of_string (List.assoc name l)
1965   with Failure _ | Not_found -> def
1966 ;;
1967
1968 let auto_tac ~params:(_univ,flags) status =
1969   let oldstatus = status in
1970   let status = (status:> NTacStatus.tac_status) in
1971   let goals = head_goals status#stack in
1972   let status, facts = mk_th_cache status goals in
1973   let unit_eq = index_local_equations status#eq_cache status in 
1974   let cache = init_cache ~facts ~unit_eq  () in 
1975 (*   pp_th status facts; *)
1976 (*
1977   NDiscriminationTree.DiscriminationTree.iter status#auto_cache (fun p t -> 
1978     debug_print (lazy(
1979       NDiscriminationTree.NCicIndexable.string_of_path p ^ " |--> " ^
1980       String.concat "\n    " (List.map (
1981       NCicPp.ppterm ~metasenv:[] ~context:[] ~subst:[])
1982         (NDiscriminationTree.TermSet.elements t))
1983       )));
1984 *)
1985   let depth = int "depth" flags 3 in 
1986   let size  = int "size" flags 10 in 
1987   let width = int "width" flags 4 (* (3+List.length goals)*) in 
1988   (* XXX fix sort *)
1989 (*   let goals = List.map (fun i -> (i,P)) goals in *)
1990   let signature = height_of_goals status in 
1991   let flags = { 
1992           last = true;
1993           maxwidth = width;
1994           maxsize = size;
1995           maxdepth = depth;
1996           timeout = Unix.gettimeofday() +. 3000.;
1997           do_types = false; 
1998   } in
1999   let initial_time = Unix.gettimeofday() in
2000   app_counter:= 0;
2001   let rec up_to x y =
2002     if x > y then
2003       (print(lazy
2004         ("TIME ELAPSED:"^string_of_float(Unix.gettimeofday()-.initial_time)));
2005        debug_print(lazy
2006         ("Applicative nodes:"^string_of_int !app_counter)); 
2007        raise (Error (lazy "auto gave up", None)))
2008     else
2009       let _ = debug_print (lazy("\n\nRound "^string_of_int x^"\n")) in
2010       let flags = { flags with maxdepth = x } 
2011       in 
2012         try auto_clusters (~top:true) flags signature cache 0 status;assert false
2013         with
2014           | Gaveup _ -> up_to (x+1) y
2015           | Proved s -> 
2016               debug_print (lazy ("proved at depth " ^ string_of_int x));
2017               let stack = 
2018                 match s#stack with
2019                   | (g,t,k,f) :: rest -> (filter_open g,t,k,f):: rest
2020                   | _ -> assert false
2021               in
2022               let s = s#set_stack stack in
2023                 oldstatus#set_status s 
2024   in
2025   let s = up_to depth depth in
2026     debug_print(lazy
2027         ("TIME ELAPSED:"^string_of_float(Unix.gettimeofday()-.initial_time)));
2028     debug_print(lazy
2029         ("Applicative nodes:"^string_of_int !app_counter));
2030     s
2031 ;;
2032