]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/ng_tactics/nnAuto.ml
Added an implicit parameter to branch_tac to allow branching on a
[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 print ?(depth=0) s = 
16   prerr_endline (String.make depth '\t'^Lazy.force s) 
17 let debug_print ?(depth=0) s = 
18   if !debug then print ~depth s else ()
19
20 let debug_do f = if !debug then f () else ()
21
22 open Continuationals.Stack
23 open NTacStatus
24 module Ast = CicNotationPt
25 let app_counter = ref 0
26
27 (* ======================= utility functions ========================= *)
28 module IntSet = Set.Make(struct type t = int let compare = compare end)
29
30 let get_sgoalty status g =
31  let _,_,metasenv,subst,_ = status#obj in
32  try
33    let _, ctx, ty = NCicUtils.lookup_meta g metasenv in
34    let ty = NCicUntrusted.apply_subst subst ctx ty in
35    let ctx = NCicUntrusted.apply_subst_context 
36      ~fix_projections:true subst ctx
37    in
38      NTacStatus.mk_cic_term ctx ty
39  with NCicUtils.Meta_not_found _ as exn -> fail ~exn (lazy "get_sgoalty")
40 ;;
41
42 let deps status g =
43   let gty = get_sgoalty status g in
44   metas_of_term status gty
45 ;;
46
47 let menv_closure status gl = 
48   let rec closure acc = function
49     | [] -> acc
50     | x::l when IntSet.mem x acc -> closure acc l
51     | x::l -> closure (IntSet.add x acc) (deps status x @ l)
52   in closure IntSet.empty gl
53 ;;
54
55 (* we call a "fact" an object whose hypothesis occur in the goal 
56    or in types of goal-variables *)
57 let is_a_fact status ty =  
58   let status, ty, metas = saturate ~delta:0 status ty in
59   debug_print (lazy ("saturated ty :" ^ (ppterm status ty)));
60   let g_metas = metas_of_term status ty in
61   let clos = menv_closure status g_metas in
62   (* let _,_,metasenv,_,_ = status#obj in *)
63   let menv = 
64     List.fold_left
65       (fun acc m ->
66          let _, m = term_of_cic_term status m (ctx_of m) in
67          match m with 
68          | NCic.Meta(i,_) -> IntSet.add i acc
69          | _ -> assert false)
70       IntSet.empty metas
71   in IntSet.subset menv clos;;
72
73 let is_a_fact_obj s uri = 
74   let obj = NCicEnvironment.get_checked_obj uri in
75   match obj with
76     | (_,_,[],[],NCic.Constant(_,_,Some(t),ty,_)) ->
77         is_a_fact s (mk_cic_term [] ty)
78 (* aggiungere i costruttori *)
79     | _ -> false
80
81 let is_a_fact_ast status subst metasenv ctx cand = 
82  debug_print ~depth:0 
83    (lazy ("------- checking " ^ CicNotationPp.pp_term cand)); 
84  let status, t = disambiguate status ctx ("",0,cand) None in
85  let status,t = term_of_cic_term status t ctx in
86  let ty = NCicTypeChecker.typeof subst metasenv ctx t in
87    is_a_fact status (mk_cic_term ctx ty)
88
89 let current_goal status = 
90   let open_goals = head_goals status#stack in
91   assert (List.length open_goals  = 1);
92   let open_goal = List.hd open_goals in
93   let gty = get_goalty status open_goal in
94   let ctx = ctx_of gty in
95     open_goal, ctx, gty
96
97
98 (* =============================== paramod =========================== *)
99 let solve fast status eq_cache goal =
100   let f = 
101     if fast then NCicParamod.fast_eq_check
102     else NCicParamod.paramod in
103   let n,h,metasenv,subst,o = status#obj in
104   let gname, ctx, gty = List.assoc goal metasenv in
105   let gty = NCicUntrusted.apply_subst subst ctx gty in
106   let build_status (pt, _, metasenv, subst) =
107     try
108       debug_print (lazy ("refining: "^(NCicPp.ppterm ctx subst metasenv pt)));
109       let stamp = Unix.gettimeofday () in 
110       let metasenv, subst, pt, pty =
111         NCicRefiner.typeof status
112                 (* (status#set_coerc_db NCicCoercion.empty_db) *)
113           metasenv subst ctx pt None in
114         debug_print (lazy ("refined: "^(NCicPp.ppterm ctx subst metasenv pt)));
115         debug_print (lazy ("synt: "^(NCicPp.ppterm ctx subst metasenv pty)));
116         let metasenv, subst =
117           NCicUnification.unify status metasenv subst ctx gty pty 
118         (* the previous code is much less expensive than directly refining
119            pt with expected type pty 
120            in 
121            prerr_endline ("exp: "^(NCicPp.ppterm ctx subst metasenv gty));
122            NCicRefiner.typeof 
123                     (status#set_coerc_db NCicCoercion.empty_db) 
124              metasenv subst ctx pt (Some gty) *)
125         in 
126           debug_print (lazy (Printf.sprintf "Refined in %fs"
127                      (Unix.gettimeofday() -. stamp))); 
128           let status = status#set_obj (n,h,metasenv,subst,o) in
129           let metasenv = List.filter (fun j,_ -> j <> goal) metasenv in
130           let subst = (goal,(gname,ctx,pt,pty)) :: subst in
131             Some (status#set_obj (n,h,metasenv,subst,o))
132     with 
133         NCicRefiner.RefineFailure msg 
134       | NCicRefiner.Uncertain msg ->
135           debug_print (lazy ("WARNING: refining in fast_eq_check failed" ^
136                         snd (Lazy.force msg))); None
137       | NCicRefiner.AssertFailure msg -> 
138           debug_print (lazy ("WARNING: refining in fast_eq_check failed" ^
139                         Lazy.force msg)); None
140       | _ -> None
141     in
142     HExtlib.filter_map build_status
143       (f status metasenv subst ctx eq_cache (NCic.Rel ~-1,gty))
144 ;;
145
146 let fast_eq_check eq_cache status goal =
147   match solve true status eq_cache goal with
148   | [] -> raise (Error (lazy "no proof found",None))
149   | s::_ -> s
150 ;;
151
152 let dist_fast_eq_check eq_cache s = 
153   NTactics.distribute_tac (fast_eq_check eq_cache) s
154 ;;
155
156 let auto_eq_check eq_cache status =
157   try 
158     let s = dist_fast_eq_check eq_cache status in
159       [s]
160   with
161     | Error _ -> []
162 ;;
163
164 (* warning: ctx is supposed to be already instantiated w.r.t subst *)
165 let index_local_equations eq_cache status =
166   debug_print (lazy "indexing equations");
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 | NReference.Fix (_,_,h)))) 
1304     | NCic.Appl (NCic.Const(NReference.Ref(_,(NReference.Def h | NReference.Fix (_,_,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                 let status, keys = keys_of_term status t in
1327                 debug_print(lazy("indexing: "^ppterm status t ^ ": " ^ string_of_int (List.length keys)));
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 rm_from_th t c ty = 
1355   let key_c = ctx_of t in
1356   if not (List.mem_assq key_c c) then assert false
1357   else
1358     let rec replace = function
1359       | [] -> []
1360       | (x, idx) :: tl when x == key_c -> 
1361           (x, InvRelDiscriminationTree.remove_index idx ty t) :: tl
1362       | x :: tl -> x :: replace tl
1363     in 
1364       replace c
1365 ;;
1366
1367 let pp_idx status idx =
1368    InvRelDiscriminationTree.iter idx
1369       (fun k set ->
1370          debug_print(lazy("K: " ^ NCicInverseRelIndexable.string_of_path k));
1371          Ncic_termSet.iter 
1372            (fun t -> debug_print(lazy("\t"^ppterm status t))) 
1373            set)
1374 ;;
1375
1376 let pp_th status = 
1377   List.iter 
1378     (fun ctx, idx ->
1379        debug_print(lazy( "-----------------------------------------------"));
1380        debug_print(lazy( (NCicPp.ppcontext ~metasenv:[] ~subst:[] ctx)));
1381        debug_print(lazy( "||====>  "));
1382        pp_idx status idx)
1383 ;;
1384
1385 let search_in_th gty th = 
1386   let c = ctx_of gty in
1387   let rec aux acc = function
1388    | [] -> (* Ncic_termSet.elements *) acc
1389    | (_::tl) as k ->
1390        try 
1391          let idx = List.assq k th in
1392          let acc = Ncic_termSet.union acc 
1393            (InvRelDiscriminationTree.retrieve_unifiables idx gty)
1394          in
1395          aux acc tl
1396        with Not_found -> aux acc tl
1397   in
1398     aux Ncic_termSet.empty c
1399 ;;
1400
1401 type flags = {
1402         do_types : bool; (* solve goals in Type *)
1403         last : bool; (* last goal: take first solution only  *)
1404         maxwidth : int;
1405         maxsize  : int;
1406         maxdepth : int;
1407         timeout  : float;
1408 }
1409
1410 type cache =
1411     {facts : th_cache; (* positive results *)
1412      under_inspection : cic_term list * th_cache; (* to prune looping *)
1413      unit_eq : NCicParamod.state
1414     }
1415
1416 type sort = T | P
1417 type goal = int * sort (* goal, depth, sort *)
1418 type fail = goal * cic_term
1419 type candidate = int * Ast.term (* unique candidate number, candidate *)
1420
1421 exception Gaveup of IntSet.t (* a sublist of unprovable conjunctive
1422                                 atoms of the input goals *)
1423 exception Proved of NTacStatus.tac_status
1424
1425 let height_of_ref (NReference.Ref (uri, x)) = 
1426   match x with
1427   | NReference.Decl 
1428   | NReference.Ind _ 
1429   | NReference.Con _
1430   | NReference.CoFix _ -> 
1431       let _,height,_,_,_ = NCicEnvironment.get_checked_obj uri in
1432       height 
1433   | NReference.Def h -> h 
1434   | NReference.Fix (_,_,h) -> h 
1435 ;;
1436
1437 let fast_height_of_term t =
1438  let h = ref 0 in
1439  let rec aux =
1440   function
1441      NCic.Meta (_,(_,NCic.Ctx l)) -> List.iter aux l
1442    | NCic.Meta _ -> ()
1443    | NCic.Rel _
1444    | NCic.Sort _ -> ()
1445    | NCic.Implicit _ -> assert false
1446    | NCic.Const nref as t -> 
1447 (*
1448                    prerr_endline (NCicPp.ppterm ~metasenv:[] ~subst:[]
1449                    ~context:[] t ^ ":" ^ string_of_int (height_of_ref nref));            
1450 *)
1451        h := max !h (height_of_ref nref)
1452    | NCic.Prod (_,t1,t2)
1453    | NCic.Lambda (_,t1,t2) -> aux t1; aux t2
1454    | NCic.LetIn (_,s,ty,t) -> aux s; aux ty; aux t
1455    | NCic.Appl l -> List.iter aux l
1456    | NCic.Match (_,outty,t,pl) -> aux outty; aux t; List.iter aux pl
1457  in
1458   aux t; !h
1459 ;;
1460
1461 let height_of_goals status = 
1462   let open_goals = head_goals status#stack in
1463   assert (List.length open_goals > 0);
1464   let h = ref 1 in
1465   List.iter 
1466     (fun open_goal ->
1467       let ty = get_goalty status open_goal in
1468       let context = ctx_of ty in
1469       let _, ty = term_of_cic_term status ty (ctx_of ty) in
1470       h := max !h (fast_height_of_term ty);
1471       List.iter 
1472         (function 
1473         | _, NCic.Decl ty -> h := max !h (fast_height_of_term ty)
1474         | _, NCic.Def (bo,ty) -> 
1475             h := max !h (fast_height_of_term ty);
1476             h := max !h (fast_height_of_term bo);
1477             ) 
1478         context)
1479      open_goals;
1480   prerr_endline ("altezza sequente: " ^ string_of_int !h);
1481   !h
1482 ;;
1483
1484 (* let close_failures _ c = c;; *)
1485 (* let prunable _ _ _ = false;; *)
1486 (* let cache_examine cache gty = `Notfound;; *)
1487 (* let put_in_subst s _ _ _  = s;; *)
1488 (* let add_to_cache_and_del_from_orlist_if_green_cut _ _ c _ _ o f _ = c, o, f, false ;; *)
1489 (* let cache_add_underinspection c _ _ = c;; *)
1490
1491 let init_cache ?(facts=[]) ?(under_inspection=[],[]) 
1492     ?(unit_eq=NCicParamod.empty_state) _ = 
1493     {facts = facts;
1494      under_inspection = under_inspection;
1495      unit_eq = unit_eq
1496     }
1497
1498 let only signature _context candidate = 
1499         (* TASSI: nel trie ci mettiamo solo il body, non il ty *)
1500   let candidate_ty = 
1501    NCicTypeChecker.typeof ~subst:[] ~metasenv:[] [] candidate
1502   in
1503   let height = fast_height_of_term candidate_ty in
1504   let rc = signature >= height in
1505   if rc = false then
1506     debug_print (lazy ("Filtro: " ^ NCicPp.ppterm ~context:[] ~subst:[]
1507           ~metasenv:[] candidate ^ ": " ^ string_of_int height))
1508   else 
1509     debug_print (lazy ("Tengo: " ^ NCicPp.ppterm ~context:[] ~subst:[]
1510           ~metasenv:[] candidate ^ ": " ^ string_of_int height));
1511
1512   rc
1513 ;; 
1514
1515 let candidate_no = ref 0;;
1516
1517 let openg_no status = List.length (head_goals status#stack)
1518
1519 let sort_new_elems l =
1520   List.sort (fun (_,s1) (_,s2) -> openg_no s1 - openg_no s2) l
1521
1522 let try_candidate ?(smart=0) flags depth status eq_cache t =
1523  try
1524    debug_print ~depth (lazy ("------------ try " ^ CicNotationPp.pp_term t));
1525   let status = 
1526     if smart= 0 then NTactics.apply_tac ("",0,t) status 
1527     else if smart = 1 then smart_apply_auto ("",0,t) eq_cache status 
1528     else (* smart = 2: both *)
1529       try NTactics.apply_tac ("",0,t) status 
1530       with Error _ -> 
1531         smart_apply_auto ("",0,t) eq_cache status in 
1532   let og_no = openg_no status in 
1533     if (* og_no > flags.maxwidth || *)
1534       ((depth + 1) = flags.maxdepth && og_no <> 0) then
1535         (debug_print ~depth (lazy "pruned immediately"); None)
1536    else
1537      (incr candidate_no;
1538       Some ((!candidate_no,t),status))
1539  with Error (msg,exn) -> debug_print ~depth (lazy "failed"); None
1540 ;;
1541
1542 let get_candidates ?(smart=true) status cache signature gty =
1543   let universe = status#auto_cache in
1544   let context = ctx_of gty in
1545   let t_ast t = 
1546      let _status, t = term_of_cic_term status t context 
1547      in Ast.NCic t in
1548   let c_ast = function 
1549     | NCic.Const r -> Ast.NRef r | _ -> assert false in
1550   let _, raw_gty = term_of_cic_term status gty context in
1551   let cands = NDiscriminationTree.DiscriminationTree.retrieve_unifiables 
1552         universe raw_gty in
1553   let local_cands = search_in_th gty cache in
1554   debug_print (lazy ("candidates for" ^ NTacStatus.ppterm status gty));
1555   debug_print (lazy ("local cands = " ^ (string_of_int (List.length (Ncic_termSet.elements local_cands)))));
1556   let together global local =
1557     List.map c_ast 
1558       (List.filter (only signature context) 
1559         (NDiscriminationTree.TermSet.elements global)) @
1560       List.map t_ast (Ncic_termSet.elements local) in
1561   let candidates = together cands local_cands in
1562   let smart_candidates = 
1563     if smart then
1564       match raw_gty with
1565         | NCic.Appl (hd::tl) -> 
1566             let weak_gty = 
1567               NCic.Appl (hd:: HExtlib.mk_list(NCic.Meta (0,(0,NCic.Irl 0))) 
1568                            (List.length tl)) in
1569             let more_cands = 
1570               NDiscriminationTree.DiscriminationTree.retrieve_unifiables 
1571                 universe weak_gty in
1572             let smart_cands = 
1573               NDiscriminationTree.TermSet.diff more_cands cands in
1574              let cic_weak_gty = mk_cic_term context weak_gty in
1575             let more_local_cands = search_in_th cic_weak_gty cache in
1576             let smart_local_cands = 
1577               Ncic_termSet.diff more_local_cands local_cands in
1578               together smart_cands smart_local_cands  
1579         | _ -> []
1580     else [] 
1581   in
1582     candidates, smart_candidates
1583 ;;
1584
1585 let applicative_case depth signature status flags gty (cache:cache) =
1586   app_counter:= !app_counter+1; 
1587   let _,_,metasenv,subst,_ = status#obj in
1588   let context = ctx_of gty in
1589   let tcache = cache.facts in
1590   let is_eq =   
1591     let status, t = term_of_cic_term status gty context  in 
1592     NCicParamod.is_equation metasenv subst context t 
1593   in
1594   debug_print(lazy (string_of_bool is_eq)); 
1595   let candidates, smart_candidates = 
1596     get_candidates ~smart:(not is_eq) status tcache signature gty in
1597   debug_print ~depth
1598     (lazy ("candidates: " ^ string_of_int (List.length candidates)));
1599   debug_print ~depth
1600     (lazy ("smart candidates: " ^ 
1601              string_of_int (List.length smart_candidates)));
1602 (*
1603   let sm = 0 in 
1604   let smart_candidates = [] in *)
1605   let sm = if is_eq then 0 else 2 in
1606   let maxd = ((depth + 1) = flags.maxdepth) in 
1607   let only_one = flags.last && maxd in
1608   debug_print (lazy ("only_one: " ^ (string_of_bool only_one))); 
1609   debug_print (lazy ("maxd: " ^ (string_of_bool maxd)));
1610   let elems =  
1611     List.fold_left 
1612       (fun elems cand ->
1613          if (only_one && (elems <> [])) then elems 
1614          else 
1615            if (maxd && not(is_a_fact_ast status subst metasenv context cand)) 
1616            then (debug_print (lazy "pruned: not a fact"); elems)
1617          else
1618            match try_candidate (~smart:sm) 
1619              flags depth status cache.unit_eq cand with
1620                | None -> elems
1621                | Some x -> x::elems)
1622       [] candidates
1623   in
1624   let more_elems = 
1625     if only_one && elems <> [] then elems 
1626     else
1627       List.fold_left 
1628         (fun elems cand ->
1629          if (only_one && (elems <> [])) then elems 
1630          else 
1631            if (maxd && not(is_a_fact_ast status subst metasenv context cand)) 
1632            then (debug_print (lazy "pruned: not a fact"); elems)
1633          else
1634            match try_candidate (~smart:1) 
1635              flags depth status cache.unit_eq cand with
1636                | None -> elems
1637                | Some x -> x::elems)
1638         [] smart_candidates
1639   in
1640   elems@more_elems
1641 ;;
1642
1643 exception Found
1644 ;;
1645
1646 (* gty is supposed to be meta-closed *)
1647 let is_subsumed depth status gty cache =
1648   if cache=[] then false else (
1649   print ~depth (lazy("Subsuming " ^ (ppterm status gty))); 
1650   let n,h,metasenv,subst,obj = status#obj in
1651   let ctx = ctx_of gty in
1652   let _ , target = term_of_cic_term status gty ctx in
1653   let target = NCicSubstitution.lift 1 target in 
1654   (* candidates must only be searched w.r.t the given context *)
1655   let candidates = 
1656     try
1657     let idx = List.assq ctx cache in
1658       Ncic_termSet.elements 
1659         (InvRelDiscriminationTree.retrieve_generalizations idx gty)
1660     with Not_found -> []
1661   in
1662   debug_print ~depth
1663     (lazy ("failure candidates: " ^ string_of_int (List.length candidates)));
1664     try
1665       List.iter
1666         (fun t ->
1667            let _ , source = term_of_cic_term status t ctx in
1668            let implication = 
1669              NCic.Prod("foo",source,target) in
1670            let metasenv,j,_,_ = 
1671              NCicMetaSubst.mk_meta  
1672                metasenv ctx ~with_type:implication `IsType in
1673            let status = status#set_obj (n,h,metasenv,subst,obj) in
1674            let status = status#set_stack [([1,Open j],[],[],`NoTag)] in 
1675            try
1676              let status = NTactics.intro_tac "foo" status in
1677              let status =
1678                NTactics.apply_tac ("",0,Ast.NCic (NCic.Rel 1)) status
1679              in 
1680                if (head_goals status#stack = []) then raise Found
1681                else ()
1682            with
1683              | Error _ -> ())
1684         candidates;false
1685     with Found -> debug_print ~depth (lazy "success");true)
1686 ;;
1687
1688 let rec guess_name name ctx = 
1689   if name = "_" then guess_name "auto" ctx else
1690   if not (List.mem_assoc name ctx) then name else
1691   guess_name (name^"'") ctx
1692 ;;
1693
1694 let is_prod status = 
1695   let _, ctx, gty = current_goal status in
1696   let _, raw_gty = term_of_cic_term status gty ctx in
1697   match raw_gty with
1698     | NCic.Prod (name,_,_) -> Some (guess_name name ctx)
1699     | _ -> None
1700
1701 let intro ~depth status facts name =
1702   let status = NTactics.intro_tac name status in
1703   let _, ctx, ngty = current_goal status in
1704   let t = mk_cic_term ctx (NCic.Rel 1) in
1705   let status, keys = keys_of_term status t in
1706   let facts = List.fold_left (add_to_th t) facts keys in
1707     debug_print ~depth (lazy ("intro: "^ name));
1708   (* unprovability is not stable w.r.t introduction *)
1709   status, facts
1710 ;;
1711
1712 let rec intros_facts ~depth status facts =
1713   match is_prod status with
1714     | Some(name) ->
1715         let status,facts =
1716           intro ~depth status facts name
1717         in intros_facts ~depth status facts 
1718     | _ -> status, facts
1719 ;; 
1720
1721 let rec intros ~depth status (cache:cache) =
1722     match is_prod status with
1723       | Some _ ->
1724           let status,facts =
1725             intros_facts ~depth status cache.facts 
1726           in 
1727             (* we reindex the equation from scratch *)
1728           let unit_eq = 
1729             index_local_equations status#eq_cache status in
1730           status, init_cache ~facts ~unit_eq () 
1731       | _ -> status, cache
1732 ;;
1733
1734 let reduce ~depth status g = 
1735   let n,h,metasenv,subst,o = status#obj in 
1736   let attr, ctx, ty = NCicUtils.lookup_meta g metasenv in
1737   let ty = NCicUntrusted.apply_subst subst ctx ty in
1738   let ty' = NCicReduction.whd ~subst ctx ty in
1739   if ty = ty' then []
1740   else
1741     (debug_print ~depth 
1742       (lazy ("reduced to: "^ NCicPp.ppterm ctx subst metasenv ty'));
1743     let metasenv = 
1744       (g,(attr,ctx,ty'))::(List.filter (fun (i,_) -> i<>g) metasenv) 
1745     in
1746     let status = status#set_obj (n,h,metasenv,subst,o) in
1747     (* we merge to gain a depth level; the previous goal level should
1748        be empty *)
1749     let status = NTactics.merge_tac status in
1750     incr candidate_no;
1751     [(!candidate_no,Ast.Ident("__whd",None)),status])
1752 ;;
1753
1754 let do_something signature flags status g depth gty cache =
1755   (* whd *)
1756   let l = reduce ~depth status g in
1757   (* backward aplications *)
1758   let l1 = 
1759     List.map 
1760       (fun s ->
1761          incr candidate_no;
1762          ((!candidate_no,Ast.Ident("__paramod",None)),s))
1763       (auto_eq_check cache.unit_eq status) 
1764   in
1765   let l2 = 
1766     (* if (l1 <> []) then [] else *)
1767     applicative_case depth signature status flags gty cache 
1768   (* fast paramodulation *) 
1769   in
1770   (* states in l1 have have an empty set of subgoals: no point to sort them *)
1771   debug_print ~depth 
1772     (lazy ("alternatives = " ^ (string_of_int (List.length (l1@l@l2)))));
1773     l1 @ (sort_new_elems (l@l2)), cache
1774 ;;
1775
1776 let pp_goal = function
1777   | (_,Continuationals.Stack.Open i) 
1778   | (_,Continuationals.Stack.Closed i) -> string_of_int i 
1779 ;;
1780
1781 let pp_goals status l =
1782   String.concat ", " 
1783     (List.map 
1784        (fun i -> 
1785           let gty = get_goalty status i in
1786             NTacStatus.ppterm status gty)
1787        l)
1788 ;;
1789
1790 module M = 
1791   struct 
1792     type t = int
1793     let compare = Pervasives.compare
1794   end
1795 ;;
1796
1797 module MS = HTopoSort.Make(M)
1798 ;;
1799
1800 let sort_tac status =
1801   let gstatus = 
1802     match status#stack with
1803     | [] -> assert false
1804     | (goals, t, k, tag) :: s ->
1805         let g = head_goals status#stack in
1806         let sortedg = 
1807           (List.rev (MS.topological_sort g (deps status))) in
1808           debug_print (lazy ("old g = " ^ 
1809             String.concat "," (List.map string_of_int g)));
1810           debug_print (lazy ("sorted goals = " ^ 
1811             String.concat "," (List.map string_of_int sortedg)));
1812           let is_it i = function
1813             | (_,Continuationals.Stack.Open j ) 
1814             | (_,Continuationals.Stack.Closed j ) -> i = j
1815           in 
1816           let sorted_goals = 
1817             List.map (fun i -> List.find (is_it i) goals) sortedg
1818           in
1819             (sorted_goals, t, k, tag) :: s
1820   in
1821    status#set_stack gstatus
1822 ;;
1823   
1824 let clean_up_tac status =
1825   let gstatus = 
1826     match status#stack with
1827     | [] -> assert false
1828     | (g, t, k, tag) :: s ->
1829         let is_open = function
1830           | (_,Continuationals.Stack.Open _) -> true
1831           | (_,Continuationals.Stack.Closed _) -> false
1832         in
1833         let g' = List.filter is_open g in
1834           (g', t, k, tag) :: s
1835   in
1836    status#set_stack gstatus
1837 ;;
1838
1839 let focus_tac focus status =
1840   let gstatus = 
1841     match status#stack with
1842     | [] -> assert false
1843     | (g, t, k, tag) :: s ->
1844         let in_focus = function
1845           | (_,Continuationals.Stack.Open i) 
1846           | (_,Continuationals.Stack.Closed i) -> List.mem i focus
1847         in
1848         let focus,others = List.partition in_focus g
1849         in
1850           (* we need to mark it as a BranchTag, otherwise cannot merge later *)
1851           (focus,[],[],`BranchTag) :: (others, t, k, tag) :: s
1852   in
1853    status#set_stack gstatus
1854 ;;
1855
1856 let deep_focus_tac level focus status =
1857   let in_focus = function
1858     | (_,Continuationals.Stack.Open i) 
1859     | (_,Continuationals.Stack.Closed i) -> List.mem i focus
1860   in
1861   let rec slice level gs = 
1862     if level = 0 then [],[],gs else
1863       match gs with 
1864         | [] -> assert false
1865         | (g, t, k, tag) :: s ->
1866             let f,o,gs = slice (level-1) s in           
1867             let f1,o1 = List.partition in_focus g
1868         in
1869           (* we need to mark it as a BranchTag, otherwise cannot merge later *)
1870           (f1,[],[],`BranchTag)::f, (o1, t, k, tag)::o, gs
1871   in
1872   let gstatus = 
1873     let f,o,s = slice level status#stack in f@o@s
1874   in
1875    status#set_stack gstatus
1876 ;;
1877
1878 let open_goals level status = 
1879   let rec aux level gs = 
1880     if level = 0 then []
1881     else match gs with 
1882       | [] -> assert false
1883       | _ :: s -> head_goals gs @ aux (level-1) s
1884   in
1885   aux level status#stack
1886 ;;
1887
1888 let rec auto_clusters ?(top=false)  
1889     flags signature cache depth status : unit =
1890   debug_print ~depth (lazy ("entering auto clusters at depth " ^
1891                            (string_of_int depth)));
1892   (* ignore(Unix.select [] [] [] 0.01); *)
1893   let status = clean_up_tac status in
1894   let goals = head_goals status#stack in
1895   if goals = [] then 
1896     if depth = 0 then raise (Proved status)
1897     else 
1898       let status = NTactics.merge_tac status in
1899         auto_clusters flags signature (cache:cache) (depth-1) status
1900   else if List.length goals < 2 then 
1901     auto_main flags signature cache depth status 
1902   else
1903     let all_goals = open_goals (depth+1) status in
1904     debug_print ~depth (lazy ("goals = " ^ 
1905       String.concat "," (List.map string_of_int all_goals)));
1906     let classes = HExtlib.clusters (deps status) all_goals in
1907     let classes = if top then List.rev classes else classes in
1908       debug_print ~depth
1909         (lazy 
1910            (String.concat "\n" 
1911            (List.map
1912               (fun l -> 
1913                  ("cluster:" ^ String.concat "," (List.map string_of_int l)))
1914            classes)));
1915       let status,b = 
1916         List.fold_left
1917           (fun (status,b) gl ->
1918              let lold = List.length status#stack in 
1919               debug_print ~depth (lazy ("stack length = " ^ 
1920                         (string_of_int lold)));
1921              let fstatus = deep_focus_tac (depth+1) gl status in
1922              try 
1923                debug_print ~depth (lazy ("focusing on" ^ 
1924                               String.concat "," (List.map string_of_int gl)));
1925                auto_main flags signature cache depth fstatus; assert false
1926              with 
1927                | Proved(status) -> 
1928                    let status = NTactics.merge_tac status in
1929                    let lnew = List.length status#stack in 
1930                      assert (lold = lnew);
1931                    (status,true)
1932                | Gaveup _ when top -> (status,b)
1933           )
1934           (status,false) classes
1935       in
1936       let rec final_merge n s =
1937         if n = 0 then s else final_merge (n-1) (NTactics.merge_tac s)
1938       in let status = final_merge depth status 
1939       in if b then raise (Proved status) else raise (Gaveup IntSet.empty)
1940
1941 and
1942         
1943 (* BRAND NEW VERSION *)         
1944 auto_main flags signature (cache:cache) depth status: unit =
1945   debug_print ~depth (lazy "entering auto main");
1946   debug_print ~depth (lazy ("stack length = " ^ 
1947                         (string_of_int (List.length status#stack))));
1948   (* ignore(Unix.select [] [] [] 0.01); *)
1949   let status = sort_tac (clean_up_tac status) in
1950   let goals = head_goals status#stack in
1951   match goals with
1952     | [] when depth = 0 -> raise (Proved status)
1953     | []  -> 
1954         let status = NTactics.merge_tac status in
1955         let cache =
1956           let l,tree = cache.under_inspection in
1957             match l with 
1958               | [] -> assert false
1959               | a::tl -> let tree = rm_from_th a tree a in
1960                   {cache with under_inspection = tl,tree} 
1961         in 
1962           auto_clusters flags signature (cache:cache) (depth-1) status
1963     | orig::_ ->
1964         let ng = List.length goals in 
1965         if ng > flags.maxwidth then 
1966           (print (lazy "FAIL WIDTH"); raise (Gaveup IntSet.empty))
1967         else if depth = flags.maxdepth then raise (Gaveup IntSet.empty)
1968         else
1969         let status = NTactics.branch_tac ~force:true status in
1970         let status, cache = intros ~depth status cache in
1971         let g,gctx, gty = current_goal status in
1972         let ctx,ty = close status g in
1973         let closegty = mk_cic_term ctx ty in
1974         let status, gty = apply_subst status gctx gty in
1975         debug_print ~depth (lazy("Attacking goal " ^ (string_of_int g) ^" : "^ppterm status gty)); 
1976         if is_subsumed depth status closegty (snd cache.under_inspection) then 
1977           (print ~depth (lazy "SUBSUMED");
1978            raise (Gaveup IntSet.add g IntSet.empty))
1979         else 
1980         let do_flags = 
1981           {flags with last = flags.last && ng=1} in 
1982         let alternatives, cache = 
1983           do_something signature do_flags status g depth gty cache in
1984         let loop_cache =
1985           let l,tree = cache.under_inspection in
1986           let l,tree = closegty::l, add_to_th closegty tree closegty in
1987           {cache with under_inspection = l,tree} in 
1988         List.iter 
1989           (fun ((_,t),status) ->
1990              debug_print ~depth 
1991                (lazy("(re)considering goal " ^ 
1992                        (string_of_int g) ^" : "^ppterm status gty)); 
1993              debug_print (~depth:depth) 
1994                (lazy ("Case: " ^ CicNotationPp.pp_term t));
1995              let depth,cache =
1996                if t=Ast.Ident("__whd",None) then depth, cache 
1997                else depth+1,loop_cache in 
1998              try
1999                auto_clusters flags signature (cache:cache) depth status
2000              with Gaveup _ ->
2001                debug_print ~depth (lazy "Failed");())
2002           alternatives;
2003         raise (Gaveup IntSet.empty)
2004 ;;
2005
2006 let int name l def = 
2007   try int_of_string (List.assoc name l)
2008   with Failure _ | Not_found -> def
2009 ;;
2010
2011 let auto_tac ~params:(_univ,flags) status =
2012   let oldstatus = status in
2013   let status = (status:> NTacStatus.tac_status) in
2014   let goals = head_goals status#stack in
2015   let status, facts = mk_th_cache status goals in
2016   let unit_eq = index_local_equations status#eq_cache status in 
2017   let cache = init_cache ~facts ~unit_eq  () in 
2018 (*   pp_th status facts; *)
2019 (*
2020   NDiscriminationTree.DiscriminationTree.iter status#auto_cache (fun p t -> 
2021     debug_print (lazy(
2022       NDiscriminationTree.NCicIndexable.string_of_path p ^ " |--> " ^
2023       String.concat "\n    " (List.map (
2024       NCicPp.ppterm ~metasenv:[] ~context:[] ~subst:[])
2025         (NDiscriminationTree.TermSet.elements t))
2026       )));
2027 *)
2028   let depth = int "depth" flags 3 in 
2029   let size  = int "size" flags 10 in 
2030   let width = int "width" flags 4 (* (3+List.length goals)*) in 
2031   (* XXX fix sort *)
2032 (*   let goals = List.map (fun i -> (i,P)) goals in *)
2033   let signature = height_of_goals status in 
2034   let flags = { 
2035           last = true;
2036           maxwidth = width;
2037           maxsize = size;
2038           maxdepth = depth;
2039           timeout = Unix.gettimeofday() +. 3000.;
2040           do_types = false; 
2041   } in
2042   let initial_time = Unix.gettimeofday() in
2043   app_counter:= 0;
2044   let rec up_to x y =
2045     if x > y then
2046       (print(lazy
2047         ("TIME ELAPSED:"^string_of_float(Unix.gettimeofday()-.initial_time)));
2048        debug_print(lazy
2049         ("Applicative nodes:"^string_of_int !app_counter)); 
2050        raise (Error (lazy "auto gave up", None)))
2051     else
2052       let _ = debug_print (lazy("\n\nRound "^string_of_int x^"\n")) in
2053       let flags = { flags with maxdepth = x } 
2054       in 
2055         try auto_clusters (~top:true) flags signature cache 0 status;assert false 
2056 (*
2057         try auto_main flags signature cache 0 status;assert false
2058 *)
2059         with
2060           | Gaveup _ -> up_to (x+1) y
2061           | Proved s -> 
2062               debug_print (lazy ("proved at depth " ^ string_of_int x));
2063               let stack = 
2064                 match s#stack with
2065                   | (g,t,k,f) :: rest -> (filter_open g,t,k,f):: rest
2066                   | _ -> assert false
2067               in
2068               let s = s#set_stack stack in
2069                 oldstatus#set_status s 
2070   in
2071   let s = up_to depth depth in
2072     debug_print(lazy
2073         ("TIME ELAPSED:"^string_of_float(Unix.gettimeofday()-.initial_time)));
2074     debug_print(lazy
2075         ("Applicative nodes:"^string_of_int !app_counter));
2076     s
2077 ;;
2078