]> matita.cs.unibo.it Git - helm.git/blob - helm/software/components/ng_tactics/nnAuto.ml
New demodulation tactics (mostly for debugging purposes).
[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 print ?(depth=0) s = 
15   prerr_endline (String.make depth '\t'^Lazy.force s) 
16 let noprint ?(depth=0) _ = () 
17 let debug_print = noprint
18
19 open Continuationals.Stack
20 open NTacStatus
21 module Ast = CicNotationPt
22 let app_counter = ref 0
23
24 (* ======================= utility functions ========================= *)
25 module IntSet = Set.Make(struct type t = int let compare = compare end)
26
27 let get_sgoalty status g =
28  let _,_,metasenv,subst,_ = status#obj in
29  try
30    let _, ctx, ty = NCicUtils.lookup_meta g metasenv in
31    let ty = NCicUntrusted.apply_subst subst ctx ty in
32    let ctx = NCicUntrusted.apply_subst_context 
33      ~fix_projections:true subst ctx
34    in
35      NTacStatus.mk_cic_term ctx ty
36  with NCicUtils.Meta_not_found _ as exn -> fail ~exn (lazy "get_sgoalty")
37 ;;
38
39 let deps status g =
40   let gty = get_sgoalty status g in
41   metas_of_term status gty
42 ;;
43
44 let menv_closure status gl = 
45   let rec closure acc = function
46     | [] -> acc
47     | x::l when IntSet.mem x acc -> closure acc l
48     | x::l -> closure (IntSet.add x acc) (deps status x @ l)
49   in closure IntSet.empty gl
50 ;;
51
52 (* we call a "fact" an object whose hypothesis occur in the goal 
53    or in types of goal-variables *)
54 let branch status ty =  
55   let status, ty, metas = saturate ~delta:0 status ty in
56   noprint (lazy ("saturated ty :" ^ (ppterm status ty)));
57   let g_metas = metas_of_term status ty in
58   let clos = menv_closure status g_metas in
59   (* let _,_,metasenv,_,_ = status#obj in *)
60   let menv = 
61     List.fold_left
62       (fun acc m ->
63          let _, m = term_of_cic_term status m (ctx_of m) in
64          match m with 
65          | NCic.Meta(i,_) -> IntSet.add i acc
66          | _ -> assert false)
67       IntSet.empty metas
68   in 
69   (* IntSet.subset menv clos *)
70   IntSet.cardinal(IntSet.diff menv clos)
71
72 let is_a_fact status ty = branch status ty = 0
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 let height_of_ref (NReference.Ref (uri, x)) = 
99   match x with
100   | NReference.Decl 
101   | NReference.Ind _ 
102   | NReference.Con _
103   | NReference.CoFix _ -> 
104       let _,height,_,_,_ = NCicEnvironment.get_checked_obj uri in
105       height 
106   | NReference.Def h -> h 
107   | NReference.Fix (_,_,h) -> h 
108 ;;
109
110 (*************************** height functions ********************************)
111 let fast_height_of_term t =
112  let h = ref 0 in
113  let rec aux =
114   function
115      NCic.Meta (_,(_,NCic.Ctx l)) -> List.iter aux l
116    | NCic.Meta _ -> ()
117    | NCic.Rel _
118    | NCic.Sort _ -> ()
119    | NCic.Implicit _ -> assert false
120    | NCic.Const nref as t -> 
121 (*
122                    prerr_endline (NCicPp.ppterm ~metasenv:[] ~subst:[]
123                    ~context:[] t ^ ":" ^ string_of_int (height_of_ref nref));            
124 *)
125        h := max !h (height_of_ref nref)
126    | NCic.Prod (_,t1,t2)
127    | NCic.Lambda (_,t1,t2) -> aux t1; aux t2
128    | NCic.LetIn (_,s,ty,t) -> aux s; aux ty; aux t
129    | NCic.Appl l -> List.iter aux l
130    | NCic.Match (_,outty,t,pl) -> aux outty; aux t; List.iter aux pl
131  in
132   aux t; !h
133 ;;
134
135 let height_of_goal g status = 
136   let ty = get_goalty status g in
137   let context = ctx_of ty in
138   let _, ty = term_of_cic_term status ty (ctx_of ty) in
139   let h = ref (fast_height_of_term ty) in
140   List.iter 
141     (function 
142        | _, NCic.Decl ty -> h := max !h (fast_height_of_term ty)
143        | _, NCic.Def (bo,ty) -> 
144            h := max !h (fast_height_of_term ty);
145            h := max !h (fast_height_of_term bo);
146     )
147     context;
148   !h
149 ;;      
150
151 let height_of_goals status = 
152   let open_goals = head_goals status#stack in
153   assert (List.length open_goals > 0);
154   let h = ref 1 in
155   List.iter 
156     (fun open_goal ->
157        h := max !h (height_of_goal open_goal status))
158      open_goals;
159   debug_print (lazy ("altezza sequente: " ^ string_of_int !h));
160   !h
161 ;;
162
163 (* =============================== paramod =========================== *)
164 let solve f status eq_cache goal =
165 (*
166   let f = 
167     if fast then NCicParamod.fast_eq_check
168     else NCicParamod.paramod in
169 *)
170   let n,h,metasenv,subst,o = status#obj in
171   let gname, ctx, gty = List.assoc goal metasenv in
172   let gty = NCicUntrusted.apply_subst subst ctx gty in
173   let build_status (pt, _, metasenv, subst) =
174     try
175       print (lazy ("refining: "^(NCicPp.ppterm ctx subst metasenv pt)));
176       let stamp = Unix.gettimeofday () in 
177       let metasenv, subst, pt, pty =
178         (* NCicRefiner.typeof status
179           (* (status#set_coerc_db NCicCoercion.empty_db) *)
180           metasenv subst ctx pt None in
181           print (lazy ("refined: "^(NCicPp.ppterm ctx subst metasenv pt)));
182           debug_print (lazy ("synt: "^(NCicPp.ppterm ctx subst metasenv pty)));
183           let metasenv, subst =
184             NCicUnification.unify status metasenv subst ctx gty pty *)
185         NCicRefiner.typeof 
186           (status#set_coerc_db NCicCoercion.empty_db) 
187           metasenv subst ctx pt (Some gty) 
188         in 
189           debug_print (lazy (Printf.sprintf "Refined in %fs"
190                      (Unix.gettimeofday() -. stamp))); 
191           let status = status#set_obj (n,h,metasenv,subst,o) in
192           let metasenv = List.filter (fun j,_ -> j <> goal) metasenv in
193           let subst = (goal,(gname,ctx,pt,pty)) :: subst in
194             Some (status#set_obj (n,h,metasenv,subst,o))
195     with 
196         NCicRefiner.RefineFailure msg 
197       | NCicRefiner.Uncertain msg ->
198           debug_print (lazy ("WARNING: refining in fast_eq_check failed" ^
199                         snd (Lazy.force msg))); None
200       | NCicRefiner.AssertFailure msg -> 
201           debug_print (lazy ("WARNING: refining in fast_eq_check failed" ^
202                         Lazy.force msg)); None
203       | _ -> None
204     in
205     HExtlib.filter_map build_status
206       (f status metasenv subst ctx eq_cache (NCic.Rel ~-1,gty))
207 ;;
208
209 let fast_eq_check eq_cache status goal =
210   match solve NCicParamod.fast_eq_check status eq_cache goal with
211   | [] -> raise (Error (lazy "no proof found",None))
212   | s::_ -> s
213 ;;
214
215 let dist_fast_eq_check eq_cache s = 
216   NTactics.distribute_tac (fast_eq_check eq_cache) s
217 ;;
218
219 let auto_eq_check eq_cache status =
220   try 
221     let s = dist_fast_eq_check eq_cache status in
222       [s]
223   with
224     | Error _ -> []
225 ;;
226
227 (* warning: ctx is supposed to be already instantiated w.r.t subst *)
228 let index_local_equations eq_cache status =
229   debug_print (lazy "indexing equations");
230   let open_goals = head_goals status#stack in
231   let open_goal = List.hd open_goals in
232   let ngty = get_goalty status open_goal in
233   let ctx = ctx_of ngty in
234   let c = ref 0 in
235   List.fold_left 
236     (fun eq_cache _ ->
237        c:= !c+1;
238        let t = NCic.Rel !c in
239          try
240            let ty = NCicTypeChecker.typeof [] [] ctx t in
241            if is_a_fact status (mk_cic_term ctx ty) then
242              (debug_print(lazy("eq indexing " ^ (NCicPp.ppterm ctx [] [] ty)));
243               NCicParamod.forward_infer_step eq_cache t ty)
244            else 
245              (debug_print (lazy ("not a fact: " ^ (NCicPp.ppterm ctx [] [] ty)));
246               eq_cache)
247          with 
248            | NCicTypeChecker.TypeCheckerFailure _
249            | NCicTypeChecker.AssertFailure _ -> eq_cache) 
250     eq_cache ctx
251 ;;
252
253 let fast_eq_check_tac ~params s = 
254   let unit_eq = index_local_equations s#eq_cache s in   
255   dist_fast_eq_check unit_eq s
256 ;;
257
258 let paramod eq_cache status goal =
259   match solve NCicParamod.paramod status eq_cache goal with
260   | [] -> raise (Error (lazy "no proof found",None))
261   | s::_ -> s
262 ;;
263
264 let paramod_tac ~params s = 
265   let unit_eq = index_local_equations s#eq_cache s in   
266   NTactics.distribute_tac (paramod unit_eq) s
267 ;;
268
269 let demod eq_cache status goal =
270   match solve NCicParamod.demod status eq_cache goal with
271   | [] -> raise (Error (lazy "no progress",None))
272   | s::_ -> s
273 ;;
274
275 let demod_tac ~params s = 
276   let unit_eq = index_local_equations s#eq_cache s in   
277   NTactics.distribute_tac (demod unit_eq) s
278 ;;
279
280 (*
281 let fast_eq_check_tac_all  ~params eq_cache status = 
282   let g,_,_ = current_goal status in
283   let allstates = fast_eq_check_all status eq_cache g in
284   let pseudo_low_tac s _ _ = s in
285   let pseudo_low_tactics = 
286     List.map pseudo_low_tac allstates 
287   in
288     List.map (fun f -> NTactics.distribute_tac f status) pseudo_low_tactics
289 ;;
290 *)
291
292 (*
293 let demod status eq_cache goal =
294   let n,h,metasenv,subst,o = status#obj in
295   let gname, ctx, gty = List.assoc goal metasenv in
296   let gty = NCicUntrusted.apply_subst subst ctx gty in
297
298 let demod_tac ~params s = 
299   let unit_eq = index_local_equations s#eq_cache s in   
300   dist_fast_eq_check unit_eq s
301 *)
302
303 (*************** subsumption ****************)
304
305 let close_wrt_context =
306   List.fold_left 
307     (fun ty ctx_entry -> 
308         match ctx_entry with 
309        | name, NCic.Decl t -> NCic.Prod(name,t,ty)
310        | name, NCic.Def(bo, _) -> NCicSubstitution.subst bo ty)
311 ;;
312
313 let args_for_context ?(k=1) ctx =
314   let _,args =
315     List.fold_left 
316       (fun (n,l) ctx_entry -> 
317          match ctx_entry with 
318            | name, NCic.Decl t -> n+1,NCic.Rel(n)::l
319            | name, NCic.Def(bo, _) -> n+1,l)
320       (k,[]) ctx in
321     args
322
323 let constant_for_meta ctx ty i =
324   let name = "cic:/foo"^(string_of_int i)^".con" in
325   let uri = NUri.uri_of_string name in
326   let ty = close_wrt_context ty ctx in
327   (* prerr_endline (NCicPp.ppterm [] [] [] ty); *)
328   let attr = (`Generated,`Definition,`Local) in
329   let obj = NCic.Constant([],name,None,ty,attr) in
330     (* Constant  of relevance * string * term option * term * c_attr *)
331     (uri,0,[],[],obj)
332
333 (* not used *)
334 let refresh metasenv =
335   List.fold_left 
336     (fun (metasenv,subst) (i,(iattr,ctx,ty)) ->
337        let ikind = NCicUntrusted.kind_of_meta iattr in
338        let metasenv,j,instance,ty = 
339          NCicMetaSubst.mk_meta ~attrs:iattr 
340            metasenv ctx ~with_type:ty ikind in
341        let s_entry = i,(iattr, ctx, instance, ty) in
342        let metasenv = List.filter (fun x,_ -> i <> x) metasenv in
343          metasenv,s_entry::subst) 
344       (metasenv,[]) metasenv
345
346 (* close metasenv returns a ground instance of all the metas in the
347 metasenv, insantiatied with axioms, and the list of these axioms *)
348 let close_metasenv metasenv subst = 
349   (*
350   let metasenv = NCicUntrusted.apply_subst_metasenv subst metasenv in
351   *)
352   let metasenv = NCicUntrusted.sort_metasenv subst metasenv in 
353     List.fold_left 
354       (fun (subst,objs) (i,(iattr,ctx,ty)) ->
355          let ty = NCicUntrusted.apply_subst subst ctx ty in
356          let ctx = 
357            NCicUntrusted.apply_subst_context ~fix_projections:true 
358              subst ctx in
359          let (uri,_,_,_,obj) as okind = 
360            constant_for_meta ctx ty i in
361          try
362            NCicEnvironment.check_and_add_obj okind;
363            let iref = NReference.reference_of_spec uri NReference.Decl in
364            let iterm =
365              let args = args_for_context ctx in
366                if args = [] then NCic.Const iref 
367                else NCic.Appl(NCic.Const iref::args)
368            in
369            (* prerr_endline (NCicPp.ppterm ctx [] [] iterm); *)
370            let s_entry = i, ([], ctx, iterm, ty)
371            in s_entry::subst,okind::objs
372          with _ -> assert false)
373       (subst,[]) metasenv
374 ;;
375
376 let ground_instances status gl =
377   let _,_,metasenv,subst,_ = status#obj in
378   let subset = menv_closure status gl in
379   let submenv = List.filter (fun (x,_) -> IntSet.mem x subset) metasenv in
380 (*
381   let submenv = metasenv in
382 *)
383   let subst, objs = close_metasenv submenv subst in
384   try
385     List.iter
386       (fun i -> 
387          let (_, ctx, t, _) = List.assoc i subst in
388            debug_print (lazy (NCicPp.ppterm ctx [] [] t));
389            List.iter 
390              (fun (uri,_,_,_,_) as obj -> 
391                 NCicEnvironment.invalidate_item (`Obj (uri, obj))) 
392              objs;
393            ())
394       gl
395   with
396       Not_found -> assert false 
397   (* (ctx,t) *)
398 ;;
399
400 let replace_meta i args target = 
401   let rec aux k = function
402     (* TODO: local context *)
403     | NCic.Meta (j,lc) when i = j ->
404         (match args with
405            | [] -> NCic.Rel 1
406            | _ -> let args = 
407                List.map (NCicSubstitution.subst_meta lc) args in
408                NCic.Appl(NCic.Rel k::args))
409     | NCic.Meta (j,lc) as m ->
410         (match lc with
411            _,NCic.Irl _ -> m
412          | n,NCic.Ctx l ->
413             NCic.Meta
414              (i,(0,NCic.Ctx
415                  (List.map (fun t ->
416                    aux k (NCicSubstitution.lift n t)) l))))
417     | t -> NCicUtils.map (fun _ k -> k+1) k aux t
418  in
419    aux 1 target
420 ;;
421
422 let close_wrt_metasenv subst =
423   List.fold_left 
424     (fun ty (i,(iattr,ctx,mty)) ->
425        let mty = NCicUntrusted.apply_subst subst ctx mty in
426        let ctx = 
427          NCicUntrusted.apply_subst_context ~fix_projections:true 
428            subst ctx in
429        let cty = close_wrt_context mty ctx in
430        let name = "foo"^(string_of_int i) in
431        let ty = NCicSubstitution.lift 1 ty in
432        let args = args_for_context ~k:1 ctx in
433          (* prerr_endline (NCicPp.ppterm ctx [] [] iterm); *)
434        let ty = replace_meta i args ty
435        in
436        NCic.Prod(name,cty,ty))
437 ;;
438
439 let close status g =
440   let _,_,metasenv,subst,_ = status#obj in
441   let subset = menv_closure status [g] in
442   let subset = IntSet.remove g subset in
443   let elems = IntSet.elements subset in 
444   let _, ctx, ty = NCicUtils.lookup_meta g metasenv in
445   let ty = NCicUntrusted.apply_subst subst ctx ty in
446   debug_print (lazy ("metas in " ^ (NCicPp.ppterm ctx [] metasenv ty)));
447   debug_print (lazy (String.concat ", " (List.map string_of_int elems)));
448   let submenv = List.filter (fun (x,_) -> IntSet.mem x subset) metasenv in
449   let submenv = List.rev (NCicUntrusted.sort_metasenv subst submenv) in 
450 (*  
451     let submenv = metasenv in
452 *)
453   let ty = close_wrt_metasenv subst ty submenv in
454     debug_print (lazy (NCicPp.ppterm ctx [] [] ty));
455     ctx,ty
456 ;;
457
458 (****************** smart application ********************)
459
460 let saturate_to_ref metasenv subst ctx nref ty =
461   let height = height_of_ref nref in
462   let rec aux metasenv ty args = 
463     let ty,metasenv,moreargs =  
464       NCicMetaSubst.saturate ~delta:height metasenv subst ctx ty 0 in 
465     match ty with
466       | NCic.Const(NReference.Ref (_,NReference.Def _) as nre) 
467           when nre<>nref ->
468           let _, _, bo, _, _, _ = NCicEnvironment.get_checked_def nre in 
469             aux metasenv ty (args@moreargs)
470       | NCic.Appl(NCic.Const(NReference.Ref (_,NReference.Def _) as nre)::tl) 
471           when nre<>nref ->
472           let _, _, bo, _, _, _ = NCicEnvironment.get_checked_def nre in
473             aux metasenv (NCic.Appl(bo::tl)) (args@moreargs) 
474     | _ -> ty,metasenv,(args@moreargs)
475   in
476     aux metasenv ty []
477
478 let smart_apply t unit_eq status g = 
479   let n,h,metasenv,subst,o = status#obj in
480   let gname, ctx, gty = List.assoc g metasenv in
481   (* let ggty = mk_cic_term context gty in *)
482   let status, t = disambiguate status ctx t None in
483   let status,t = term_of_cic_term status t ctx in
484   let _,_,metasenv,subst,_ = status#obj in
485   let ty = NCicTypeChecker.typeof subst metasenv ctx t in
486   print(lazy("prima"));
487   let ty,metasenv,args = 
488     match gty with
489       | NCic.Const(nref)
490       | NCic.Appl(NCic.Const(nref)::_) -> 
491           saturate_to_ref metasenv subst ctx nref ty
492       | _ -> 
493           NCicMetaSubst.saturate metasenv subst ctx ty 0 in
494   let metasenv,j,inst,_ = NCicMetaSubst.mk_meta metasenv ctx `IsTerm in
495   let status = status#set_obj (n,h,metasenv,subst,o) in
496   let pterm = if args=[] then t else 
497     match t with
498       | NCic.Appl l -> NCic.Appl(l@args) 
499       | _ -> NCic.Appl(t::args) 
500   in
501   print(lazy("pterm " ^ (NCicPp.ppterm ctx [] [] pterm)));
502   print(lazy("pty " ^ (NCicPp.ppterm ctx [] [] ty)));
503   let eq_coerc =       
504     let uri = 
505       NUri.uri_of_string "cic:/matita/ng/Plogic/equality/eq_coerc.con" in
506     let ref = NReference.reference_of_spec uri (NReference.Def(2)) in
507       NCic.Const ref
508   in
509   let smart = 
510     NCic.Appl[eq_coerc;ty;NCic.Implicit `Type;pterm;inst] in
511   let smart = mk_cic_term ctx smart in 
512     try
513       let status = instantiate status g smart in
514       let _,_,metasenv,subst,_ = status#obj in
515       let _,ctx,jty = List.assoc j metasenv in
516       let jty = NCicUntrusted.apply_subst subst ctx jty in
517         print(lazy("goal " ^ (NCicPp.ppterm ctx [] [] jty)));
518         fast_eq_check unit_eq status j
519     with
520       | Error _ as e -> debug_print (lazy "error"); raise e
521
522 let smart_apply_tac t s =
523   let unit_eq = index_local_equations s#eq_cache s in   
524   NTactics.distribute_tac (smart_apply t unit_eq) s
525
526 let smart_apply_auto t eq_cache =
527   NTactics.distribute_tac (smart_apply t eq_cache)
528
529
530 (****************** types **************)
531
532
533 type th_cache = (NCic.context * InvRelDiscriminationTree.t) list
534
535 let keys_of_term status t =
536   let status, orig_ty = typeof status (ctx_of t) t in
537   let _, ty, _ = saturate ~delta:max_int status orig_ty in
538   let keys = [ty] in
539   let keys = 
540     let _, ty = term_of_cic_term status ty (ctx_of ty) in
541     match ty with
542     | NCic.Const (NReference.Ref (_,(NReference.Def h | NReference.Fix (_,_,h)))) 
543     | NCic.Appl (NCic.Const(NReference.Ref(_,(NReference.Def h | NReference.Fix (_,_,h))))::_) 
544        when h > 0 ->
545          let _,ty,_= saturate status ~delta:(h-1) orig_ty in
546          ty::keys
547     | _ -> keys
548   in
549   status, keys
550 ;;
551
552 let mk_th_cache status gl = 
553   List.fold_left 
554     (fun (status, acc) g ->
555        let gty = get_goalty status g in
556        let ctx = ctx_of gty in
557        debug_print(lazy("th cache for: "^ppterm status gty));
558        debug_print(lazy("th cache in: "^ppcontext status ctx));
559        if List.mem_assq ctx acc then status, acc else
560          let idx = InvRelDiscriminationTree.empty in
561          let status,_,idx = 
562            List.fold_left 
563              (fun (status, i, idx) _ -> 
564                 let t = mk_cic_term ctx (NCic.Rel i) in
565                 let status, keys = keys_of_term status t in
566                 debug_print(lazy("indexing: "^ppterm status t ^ ": " ^ string_of_int (List.length keys)));
567                 let idx =
568                   List.fold_left (fun idx k -> 
569                     InvRelDiscriminationTree.index idx k t) idx keys
570                 in
571                 status, i+1, idx)
572              (status, 1, idx) ctx
573           in
574          status, (ctx, idx) :: acc)
575     (status,[]) gl
576 ;;
577
578 let add_to_th t c ty = 
579   let key_c = ctx_of t in
580   if not (List.mem_assq key_c c) then
581       (key_c ,InvRelDiscriminationTree.index 
582                InvRelDiscriminationTree.empty ty t ) :: c 
583   else
584     let rec replace = function
585       | [] -> []
586       | (x, idx) :: tl when x == key_c -> 
587           (x, InvRelDiscriminationTree.index idx ty t) :: tl
588       | x :: tl -> x :: replace tl
589     in 
590       replace c
591 ;;
592
593 let rm_from_th t c ty = 
594   let key_c = ctx_of t in
595   if not (List.mem_assq key_c c) then assert false
596   else
597     let rec replace = function
598       | [] -> []
599       | (x, idx) :: tl when x == key_c -> 
600           (x, InvRelDiscriminationTree.remove_index idx ty t) :: tl
601       | x :: tl -> x :: replace tl
602     in 
603       replace c
604 ;;
605
606 let pp_idx status idx =
607    InvRelDiscriminationTree.iter idx
608       (fun k set ->
609          debug_print(lazy("K: " ^ NCicInverseRelIndexable.string_of_path k));
610          Ncic_termSet.iter 
611            (fun t -> debug_print(lazy("\t"^ppterm status t))) 
612            set)
613 ;;
614
615 let pp_th status = 
616   List.iter 
617     (fun ctx, idx ->
618        debug_print(lazy( "-----------------------------------------------"));
619        debug_print(lazy( (NCicPp.ppcontext ~metasenv:[] ~subst:[] ctx)));
620        debug_print(lazy( "||====>  "));
621        pp_idx status idx)
622 ;;
623
624 let search_in_th gty th = 
625   let c = ctx_of gty in
626   let rec aux acc = function
627    | [] -> (* Ncic_termSet.elements *) acc
628    | (_::tl) as k ->
629        try 
630          let idx = List.assq k th in
631          let acc = Ncic_termSet.union acc 
632            (InvRelDiscriminationTree.retrieve_unifiables idx gty)
633          in
634          aux acc tl
635        with Not_found -> aux acc tl
636   in
637     aux Ncic_termSet.empty c
638 ;;
639
640 type flags = {
641         do_types : bool; (* solve goals in Type *)
642         last : bool; (* last goal: take first solution only  *)
643         maxwidth : int;
644         maxsize  : int;
645         maxdepth : int;
646         timeout  : float;
647 }
648
649 type cache =
650     {facts : th_cache; (* positive results *)
651      under_inspection : cic_term list * th_cache; (* to prune looping *)
652      unit_eq : NCicParamod.state
653     }
654
655 type sort = T | P
656 type goal = int * sort (* goal, depth, sort *)
657 type fail = goal * cic_term
658 type candidate = int * Ast.term (* unique candidate number, candidate *)
659
660 exception Gaveup of IntSet.t (* a sublist of unprovable conjunctive
661                                 atoms of the input goals *)
662 exception Proved of NTacStatus.tac_status
663
664 (* let close_failures _ c = c;; *)
665 (* let prunable _ _ _ = false;; *)
666 (* let cache_examine cache gty = `Notfound;; *)
667 (* let put_in_subst s _ _ _  = s;; *)
668 (* let add_to_cache_and_del_from_orlist_if_green_cut _ _ c _ _ o f _ = c, o, f, false ;; *)
669 (* let cache_add_underinspection c _ _ = c;; *)
670
671 let init_cache ?(facts=[]) ?(under_inspection=[],[]) 
672     ?(unit_eq=NCicParamod.empty_state) _ = 
673     {facts = facts;
674      under_inspection = under_inspection;
675      unit_eq = unit_eq
676     }
677
678 let only signature _context candidate = true
679 (*
680         (* TASSI: nel trie ci mettiamo solo il body, non il ty *)
681   let candidate_ty = 
682    NCicTypeChecker.typeof ~subst:[] ~metasenv:[] [] candidate
683   in
684   let height = fast_height_of_term candidate_ty in
685   let rc = signature >= height in
686   if rc = false then
687     debug_print (lazy ("Filtro: " ^ NCicPp.ppterm ~context:[] ~subst:[]
688           ~metasenv:[] candidate ^ ": " ^ string_of_int height))
689   else 
690     debug_print (lazy ("Tengo: " ^ NCicPp.ppterm ~context:[] ~subst:[]
691           ~metasenv:[] candidate ^ ": " ^ string_of_int height));
692
693   rc *)
694 ;; 
695
696 let candidate_no = ref 0;;
697
698 let openg_no status = List.length (head_goals status#stack)
699
700 let sort_candidates status ctx candidates =
701  let _,_,metasenv,subst,_ = status#obj in
702   let branch cand =
703     let status,ct = disambiguate status ctx ("",0,cand) None in
704     let status,t = term_of_cic_term status ct ctx in
705     let ty = NCicTypeChecker.typeof subst metasenv ctx t in
706     let res = branch status (mk_cic_term ctx ty) in
707     debug_print (lazy ("branch factor for: " ^ (ppterm status ct) ^ " = " 
708                       ^ (string_of_int res)));
709       res
710   in 
711   let candidates = List.map (fun t -> branch t,t) candidates in
712   let candidates = 
713      List.sort (fun (a,_) (b,_) -> a - b) candidates in 
714   let candidates = List.map snd candidates in
715     debug_print (lazy ("candidates =\n" ^ (String.concat "\n" 
716         (List.map CicNotationPp.pp_term candidates))));
717     candidates
718
719 let sort_new_elems l =
720   List.sort (fun (_,s1) (_,s2) -> openg_no s1 - openg_no s2) l
721
722 let try_candidate ?(smart=0) flags depth status eq_cache ctx t =
723  try
724   debug_print ~depth (lazy ("try " ^ CicNotationPp.pp_term t));
725   let status = 
726     if smart= 0 then NTactics.apply_tac ("",0,t) status 
727     else if smart = 1 then smart_apply_auto ("",0,t) eq_cache status 
728     else (* smart = 2: both *)
729       try NTactics.apply_tac ("",0,t) status 
730       with Error _ as exc -> 
731         smart_apply_auto ("",0,t) eq_cache status 
732   in
733 (*
734   let og_no = openg_no status in 
735     if (* og_no > flags.maxwidth || *)
736       ((depth + 1) = flags.maxdepth && og_no <> 0) then
737         (debug_print ~depth (lazy "pruned immediately"); None)
738     else *)
739       (* useless 
740       let status, cict = disambiguate status ctx ("",0,t) None in
741       let status,ct = term_of_cic_term status cict ctx in
742       let _,_,metasenv,subst,_ = status#obj in
743       let ty = NCicTypeChecker.typeof subst metasenv ctx ct in
744       let res = branch status (mk_cic_term ctx ty) in
745       if smart=1 && og_no > res then 
746         (print (lazy ("branch factor for: " ^ (ppterm status cict) ^ " = " 
747                     ^ (string_of_int res) ^ " vs. " ^ (string_of_int og_no)));
748          print ~depth (lazy "strange application"); None)
749       else *)
750         (incr candidate_no;
751          Some ((!candidate_no,t),status))
752  with Error (msg,exn) -> debug_print ~depth (lazy "failed"); None
753 ;;
754
755 let sort_of subst metasenv ctx t =
756   let ty = NCicTypeChecker.typeof subst metasenv ctx t in
757   let metasenv',ty = NCicUnification.fix_sorts metasenv subst ty in
758    assert (metasenv = metasenv');
759    NCicTypeChecker.typeof subst metasenv ctx ty
760 ;;
761   
762 let type0= NUri.uri_of_string ("cic:/matita/pts/Type0.univ")
763 ;;
764
765 let perforate_small subst metasenv context t =
766   let rec aux = function
767     | NCic.Appl (hd::tl) ->
768         let map t =
769           let s = sort_of subst metasenv context t in
770             match s with
771               | NCic.Sort(NCic.Type [`Type,u])
772                   when u=type0 -> NCic.Meta (0,(0,NCic.Irl 0))
773               | _ -> aux t
774         in
775           NCic.Appl (hd::List.map map tl)
776     | t -> t
777   in 
778     aux t
779 ;;
780
781 let get_candidates ?(smart=true) status cache signature gty =
782   let universe = status#auto_cache in
783   let _,_,metasenv,subst,_ = status#obj in
784   let context = ctx_of gty in
785   let t_ast t = 
786      let _status, t = term_of_cic_term status t context 
787      in Ast.NCic t in
788   let c_ast = function 
789     | NCic.Const r -> Ast.NRef r | _ -> assert false in
790   let _, raw_gty = term_of_cic_term status gty context in
791   let cands = NDiscriminationTree.DiscriminationTree.retrieve_unifiables 
792         universe raw_gty in 
793   let local_cands = search_in_th gty cache in
794   debug_print (lazy ("candidates for" ^ NTacStatus.ppterm status gty));
795   debug_print (lazy ("local cands = " ^ (string_of_int (List.length (Ncic_termSet.elements local_cands)))));
796   let together global local = 
797     List.map c_ast 
798       (List.filter (only signature context) 
799         (NDiscriminationTree.TermSet.elements global)) @
800       List.map t_ast (Ncic_termSet.elements local) in
801   let candidates = together cands local_cands in 
802   let candidates = sort_candidates status context candidates in
803   let smart_candidates = 
804     if smart then
805       match raw_gty with
806         | NCic.Appl _ 
807         | NCic.Const _ 
808         | NCic.Rel _ -> 
809             let weak_gty = perforate_small subst metasenv context raw_gty in
810               (*
811               NCic.Appl (hd:: HExtlib.mk_list(NCic.Meta (0,(0,NCic.Irl 0))) 
812                            (List.length tl)) in *)
813             let more_cands = 
814               NDiscriminationTree.DiscriminationTree.retrieve_unifiables 
815                 universe weak_gty in
816             let smart_cands = 
817               NDiscriminationTree.TermSet.diff more_cands cands in
818              let cic_weak_gty = mk_cic_term context weak_gty in
819             let more_local_cands = search_in_th cic_weak_gty cache in
820             let smart_local_cands = 
821               Ncic_termSet.diff more_local_cands local_cands in
822               together smart_cands smart_local_cands 
823               (* together more_cands more_local_cands *) 
824         | _ -> []
825     else [] 
826   in
827   let smart_candidates = sort_candidates status context smart_candidates in
828   (* if smart then smart_candidates, []
829      else candidates, [] *)
830   candidates, smart_candidates
831 ;;
832
833 let applicative_case depth signature status flags gty (cache:cache) =
834   app_counter:= !app_counter+1; 
835   let _,_,metasenv,subst,_ = status#obj in
836   let context = ctx_of gty in
837   let tcache = cache.facts in
838   let is_prod, is_eq =   
839     let status, t = term_of_cic_term status gty context  in 
840     let t = NCicReduction.whd subst context t in
841       match t with
842         | NCic.Prod _ -> true, false
843         | _ -> false, NCicParamod.is_equation metasenv subst context t 
844   in
845   debug_print(lazy (string_of_bool is_eq)); 
846   let candidates, smart_candidates = 
847     get_candidates ~smart:(not is_eq) status tcache signature gty in
848   debug_print ~depth
849     (lazy ("candidates: " ^ string_of_int (List.length candidates)));
850   debug_print ~depth
851     (lazy ("smart candidates: " ^ 
852              string_of_int (List.length smart_candidates)));
853  (*
854   let sm = 0 in 
855   let smart_candidates = [] in *)
856   let sm = if is_eq then 0 else 2 in
857   let maxd = ((depth + 1) = flags.maxdepth) in 
858   let only_one = flags.last && maxd in
859   debug_print (lazy ("only_one: " ^ (string_of_bool only_one))); 
860   debug_print (lazy ("maxd: " ^ (string_of_bool maxd)));
861   let elems =  
862     List.fold_left 
863       (fun elems cand ->
864          if (only_one && (elems <> [])) then elems 
865          else 
866            if (maxd && not(is_prod) & 
867                  not(is_a_fact_ast status subst metasenv context cand)) 
868            then (debug_print (lazy "pruned: not a fact"); elems)
869          else
870            match try_candidate (~smart:sm) 
871              flags depth status cache.unit_eq context cand with
872                | None -> elems
873                | Some x -> x::elems)
874       [] candidates
875   in
876   let more_elems = 
877     if only_one && elems <> [] then elems 
878     else
879       List.fold_left 
880         (fun elems cand ->
881          if (only_one && (elems <> [])) then elems 
882          else 
883            if (maxd && not(is_prod) &&
884                  not(is_a_fact_ast status subst metasenv context cand)) 
885            then (debug_print (lazy "pruned: not a fact"); elems)
886          else
887            match try_candidate (~smart:1) 
888              flags depth status cache.unit_eq context cand with
889                | None -> elems
890                | Some x -> x::elems)
891         [] smart_candidates
892   in
893   elems@more_elems
894 ;;
895
896 exception Found
897 ;;
898
899 (* gty is supposed to be meta-closed *)
900 let is_subsumed depth status gty cache =
901   if cache=[] then false else (
902   debug_print ~depth (lazy("Subsuming " ^ (ppterm status gty))); 
903   let n,h,metasenv,subst,obj = status#obj in
904   let ctx = ctx_of gty in
905   let _ , target = term_of_cic_term status gty ctx in
906   let target = NCicSubstitution.lift 1 target in 
907   (* candidates must only be searched w.r.t the given context *)
908   let candidates = 
909     try
910     let idx = List.assq ctx cache in
911       Ncic_termSet.elements 
912         (InvRelDiscriminationTree.retrieve_generalizations idx gty)
913     with Not_found -> []
914   in
915   debug_print ~depth
916     (lazy ("failure candidates: " ^ string_of_int (List.length candidates)));
917     try
918       List.iter
919         (fun t ->
920            let _ , source = term_of_cic_term status t ctx in
921            let implication = 
922              NCic.Prod("foo",source,target) in
923            let metasenv,j,_,_ = 
924              NCicMetaSubst.mk_meta  
925                metasenv ctx ~with_type:implication `IsType in
926            let status = status#set_obj (n,h,metasenv,subst,obj) in
927            let status = status#set_stack [([1,Open j],[],[],`NoTag)] in 
928            try
929              let status = NTactics.intro_tac "foo" status in
930              let status =
931                NTactics.apply_tac ("",0,Ast.NCic (NCic.Rel 1)) status
932              in 
933                if (head_goals status#stack = []) then raise Found
934                else ()
935            with
936              | Error _ -> ())
937         candidates;false
938     with Found -> debug_print ~depth (lazy "success");true)
939 ;;
940
941 let rec guess_name name ctx = 
942   if name = "_" then guess_name "auto" ctx else
943   if not (List.mem_assoc name ctx) then name else
944   guess_name (name^"'") ctx
945 ;;
946
947 let is_prod status = 
948   let _, ctx, gty = current_goal status in
949   let _, raw_gty = term_of_cic_term status gty ctx in
950   match raw_gty with
951     | NCic.Prod (name,_,_) -> Some (guess_name name ctx)
952     | _ -> None
953
954 let intro ~depth status facts name =
955   let status = NTactics.intro_tac name status in
956   let _, ctx, ngty = current_goal status in
957   let t = mk_cic_term ctx (NCic.Rel 1) in
958   let status, keys = keys_of_term status t in
959   let facts = List.fold_left (add_to_th t) facts keys in
960     debug_print ~depth (lazy ("intro: "^ name));
961   (* unprovability is not stable w.r.t introduction *)
962   status, facts
963 ;;
964
965 let rec intros_facts ~depth status facts =
966   match is_prod status with
967     | Some(name) ->
968         let status,facts =
969           intro ~depth status facts name
970         in intros_facts ~depth status facts 
971     | _ -> status, facts
972 ;; 
973
974 let rec intros ~depth status (cache:cache) =
975     match is_prod status with
976       | Some _ ->
977           let status,facts =
978             intros_facts ~depth status cache.facts 
979           in 
980             (* we reindex the equation from scratch *)
981           let unit_eq = 
982             index_local_equations status#eq_cache status in
983           status, init_cache ~facts ~unit_eq () 
984       | _ -> status, cache
985 ;;
986
987 let reduce ~depth status g = 
988   let n,h,metasenv,subst,o = status#obj in 
989   let attr, ctx, ty = NCicUtils.lookup_meta g metasenv in
990   let ty = NCicUntrusted.apply_subst subst ctx ty in
991   let ty' = NCicReduction.whd ~subst ctx ty in
992   if ty = ty' then []
993   else
994     (debug_print ~depth 
995       (lazy ("reduced to: "^ NCicPp.ppterm ctx subst metasenv ty'));
996     let metasenv = 
997       (g,(attr,ctx,ty'))::(List.filter (fun (i,_) -> i<>g) metasenv) 
998     in
999     let status = status#set_obj (n,h,metasenv,subst,o) in
1000     (* we merge to gain a depth level; the previous goal level should
1001        be empty *)
1002     let status = NTactics.merge_tac status in
1003     incr candidate_no;
1004     [(!candidate_no,Ast.Ident("__whd",None)),status])
1005 ;;
1006
1007 let do_something signature flags status g depth gty cache =
1008   (* whd *)
1009   let l = reduce ~depth status g in
1010   (* if l <> [] then l,cache else *)
1011   (* backward aplications *)
1012   let l1 = 
1013     List.map 
1014       (fun s ->
1015          incr candidate_no;
1016          ((!candidate_no,Ast.Ident("__paramod",None)),s))
1017       (auto_eq_check cache.unit_eq status) 
1018   in
1019   let l2 = 
1020     if ((l1 <> []) && flags.last) then [] else
1021     applicative_case depth signature status flags gty cache 
1022   (* fast paramodulation *) 
1023   in
1024   (* states in l1 have have an empty set of subgoals: no point to sort them *)
1025   debug_print ~depth 
1026     (lazy ("alternatives = " ^ (string_of_int (List.length (l1@l@l2)))));
1027     (* l1 @ (sort_new_elems (l @ l2)), cache *)
1028     l1 @ (List.rev l2) @ l, cache 
1029 ;;
1030
1031 let pp_goal = function
1032   | (_,Continuationals.Stack.Open i) 
1033   | (_,Continuationals.Stack.Closed i) -> string_of_int i 
1034 ;;
1035
1036 let pp_goals status l =
1037   String.concat ", " 
1038     (List.map 
1039        (fun i -> 
1040           let gty = get_goalty status i in
1041             NTacStatus.ppterm status gty)
1042        l)
1043 ;;
1044
1045 module M = 
1046   struct 
1047     type t = int
1048     let compare = Pervasives.compare
1049   end
1050 ;;
1051
1052 module MS = HTopoSort.Make(M)
1053 ;;
1054
1055 let sort_tac status =
1056   let gstatus = 
1057     match status#stack with
1058     | [] -> assert false
1059     | (goals, t, k, tag) :: s ->
1060         let g = head_goals status#stack in
1061         let sortedg = 
1062           (List.rev (MS.topological_sort g (deps status))) in
1063           debug_print (lazy ("old g = " ^ 
1064             String.concat "," (List.map string_of_int g)));
1065           debug_print (lazy ("sorted goals = " ^ 
1066             String.concat "," (List.map string_of_int sortedg)));
1067           let is_it i = function
1068             | (_,Continuationals.Stack.Open j ) 
1069             | (_,Continuationals.Stack.Closed j ) -> i = j
1070           in 
1071           let sorted_goals = 
1072             List.map (fun i -> List.find (is_it i) goals) sortedg
1073           in
1074             (sorted_goals, t, k, tag) :: s
1075   in
1076    status#set_stack gstatus
1077 ;;
1078   
1079 let clean_up_tac status =
1080   let gstatus = 
1081     match status#stack with
1082     | [] -> assert false
1083     | (g, t, k, tag) :: s ->
1084         let is_open = function
1085           | (_,Continuationals.Stack.Open _) -> true
1086           | (_,Continuationals.Stack.Closed _) -> false
1087         in
1088         let g' = List.filter is_open g in
1089           (g', t, k, tag) :: s
1090   in
1091    status#set_stack gstatus
1092 ;;
1093
1094 let focus_tac focus status =
1095   let gstatus = 
1096     match status#stack with
1097     | [] -> assert false
1098     | (g, t, k, tag) :: s ->
1099         let in_focus = function
1100           | (_,Continuationals.Stack.Open i) 
1101           | (_,Continuationals.Stack.Closed i) -> List.mem i focus
1102         in
1103         let focus,others = List.partition in_focus g
1104         in
1105           (* we need to mark it as a BranchTag, otherwise cannot merge later *)
1106           (focus,[],[],`BranchTag) :: (others, t, k, tag) :: s
1107   in
1108    status#set_stack gstatus
1109 ;;
1110
1111 let deep_focus_tac level focus status =
1112   let in_focus = function
1113     | (_,Continuationals.Stack.Open i) 
1114     | (_,Continuationals.Stack.Closed i) -> List.mem i focus
1115   in
1116   let rec slice level gs = 
1117     if level = 0 then [],[],gs else
1118       match gs with 
1119         | [] -> assert false
1120         | (g, t, k, tag) :: s ->
1121             let f,o,gs = slice (level-1) s in           
1122             let f1,o1 = List.partition in_focus g
1123             in
1124             (f1,[],[],`BranchTag)::f, (o1, t, k, tag)::o, gs
1125   in
1126   let gstatus = 
1127     let f,o,s = slice level status#stack in f@o@s
1128   in
1129    status#set_stack gstatus
1130 ;;
1131
1132 let rec stack_goals level gs = 
1133   if level = 0 then []
1134   else match gs with 
1135     | [] -> assert false
1136     | (g,_,_,_)::s -> 
1137         let is_open = function
1138           | (_,Continuationals.Stack.Open i) -> Some i
1139           | (_,Continuationals.Stack.Closed _) -> None
1140         in
1141           HExtlib.filter_map is_open g @ stack_goals (level-1) s
1142 ;;
1143
1144 let open_goals level status = stack_goals level status#stack
1145 ;;
1146
1147 let move_to_side level status =
1148 match status#stack with
1149   | [] -> assert false
1150   | (g,_,_,_)::tl ->
1151       let is_open = function
1152           | (_,Continuationals.Stack.Open i) -> Some i
1153           | (_,Continuationals.Stack.Closed _) -> None
1154         in 
1155       let others = menv_closure status (stack_goals (level-1) tl) in
1156       List.for_all (fun i -> IntSet.mem i others) 
1157         (HExtlib.filter_map is_open g)
1158
1159 let rec auto_clusters ?(top=false)  
1160     flags signature cache depth status : unit =
1161   debug_print ~depth (lazy ("entering auto clusters at depth " ^
1162                            (string_of_int depth)));
1163   (* ignore(Unix.select [] [] [] 0.01); *)
1164   let status = clean_up_tac status in
1165   let goals = head_goals status#stack in
1166   if goals = [] then 
1167     if depth = 0 then raise (Proved status)
1168     else 
1169       let status = NTactics.merge_tac status in
1170         let cache =
1171         let l,tree = cache.under_inspection in
1172           match l with 
1173             | [] -> cache (* possible because of intros that cleans the cache *)
1174             | a::tl -> let tree = rm_from_th a tree a in
1175                {cache with under_inspection = tl,tree} 
1176         in 
1177          auto_clusters flags signature cache (depth-1) status
1178   else if List.length goals < 2 then
1179     auto_main flags signature cache depth status
1180   else
1181     let all_goals = open_goals (depth+1) status in
1182     debug_print ~depth (lazy ("goals = " ^ 
1183       String.concat "," (List.map string_of_int all_goals)));
1184     let classes = HExtlib.clusters (deps status) all_goals in
1185     List.iter 
1186         (fun gl ->
1187            if List.length gl > flags.maxwidth then 
1188              (debug_print ~depth (lazy "FAIL GLOBAL WIDTH"); 
1189               raise (Gaveup IntSet.empty))
1190            else ()) classes;
1191     if List.length classes = 1 then
1192       let flags = 
1193         {flags with last = (List.length all_goals = 1)} in 
1194         (* no need to cluster *)
1195       auto_main flags signature cache depth status 
1196     else
1197     let classes = if top then List.rev classes else classes in
1198       debug_print ~depth
1199         (lazy 
1200            (String.concat "\n" 
1201            (List.map
1202               (fun l -> 
1203                  ("cluster:" ^ String.concat "," (List.map string_of_int l)))
1204            classes)));
1205       let status,b = 
1206         List.fold_left
1207           (fun (status,b) gl ->
1208              let flags = 
1209                {flags with last = (List.length gl = 1)} in 
1210              let lold = List.length status#stack in 
1211               debug_print ~depth (lazy ("stack length = " ^ 
1212                         (string_of_int lold)));
1213              let fstatus = deep_focus_tac (depth+1) gl status in
1214              try 
1215                debug_print ~depth (lazy ("focusing on" ^ 
1216                               String.concat "," (List.map string_of_int gl)));
1217                auto_main flags signature cache depth fstatus; assert false
1218              with 
1219                | Proved(status) -> 
1220                    let status = NTactics.merge_tac status in
1221                    let lnew = List.length status#stack in 
1222                      assert (lold = lnew);
1223                    (status,true)
1224                | Gaveup _ when top -> (status,b)
1225           )
1226           (status,false) classes
1227       in
1228       let rec final_merge n s =
1229         if n = 0 then s else final_merge (n-1) (NTactics.merge_tac s)
1230       in let status = final_merge depth status 
1231       in if b then raise (Proved status) else raise (Gaveup IntSet.empty)
1232
1233 and
1234         
1235 (* BRAND NEW VERSION *)         
1236 auto_main flags signature (cache:cache) depth status: unit =
1237   debug_print ~depth (lazy "entering auto main");
1238   debug_print ~depth (lazy ("stack length = " ^ 
1239                         (string_of_int (List.length status#stack))));
1240   (* ignore(Unix.select [] [] [] 0.01); *)
1241   let status = sort_tac (clean_up_tac status) in
1242   let goals = head_goals status#stack in
1243   match goals with
1244     | [] when depth = 0 -> raise (Proved status)
1245     | []  -> 
1246         let status = NTactics.merge_tac status in
1247         let cache =
1248           let l,tree = cache.under_inspection in
1249             match l with 
1250               | [] -> cache (* possible because of intros that cleans the cache *)
1251               | a::tl -> let tree = rm_from_th a tree a in
1252                   {cache with under_inspection = tl,tree} 
1253         in 
1254           auto_clusters flags signature cache (depth-1) status
1255     | orig::_ ->
1256         if depth > 0 && move_to_side depth status
1257         then 
1258           let status = NTactics.merge_tac status in
1259           let cache =
1260             let l,tree = cache.under_inspection in
1261               match l with 
1262                 | [] -> cache (* possible because of intros that cleans the cache*)
1263                 | a::tl -> let tree = rm_from_th a tree a in
1264                     {cache with under_inspection = tl,tree} 
1265           in 
1266             auto_clusters flags signature cache (depth-1) status 
1267         else
1268         let ng = List.length goals in
1269         (* moved inside auto_clusters *)
1270         if ng > flags.maxwidth then 
1271           (print ~depth (lazy "FAIL LOCAL WIDTH"); raise (Gaveup IntSet.empty))
1272         else if depth = flags.maxdepth then 
1273           raise (Gaveup IntSet.empty)
1274         else 
1275         let status = NTactics.branch_tac ~force:true status in
1276         let status, cache = intros ~depth status cache in
1277         let g,gctx, gty = current_goal status in
1278         let ctx,ty = close status g in
1279         let closegty = mk_cic_term ctx ty in
1280         let status, gty = apply_subst status gctx gty in
1281         debug_print ~depth (lazy("Attacking goal " ^ (string_of_int g) ^" : "^ppterm status gty)); 
1282         if is_subsumed depth status closegty (snd cache.under_inspection) then 
1283           (debug_print ~depth (lazy "SUBSUMED");
1284            raise (Gaveup IntSet.add g IntSet.empty))
1285         else
1286         let new_sig = height_of_goal g status in
1287         if new_sig < signature then 
1288           (debug_print (lazy ("news = " ^ (string_of_int new_sig)));
1289            debug_print (lazy ("olds = " ^ (string_of_int signature)))); 
1290         let alternatives, cache = 
1291           do_something signature flags status g depth gty cache in
1292         let loop_cache =
1293           let l,tree = cache.under_inspection in
1294           let l,tree = closegty::l, add_to_th closegty tree closegty in
1295           {cache with under_inspection = l,tree} in 
1296         List.iter 
1297           (fun ((_,t),status) ->
1298              debug_print ~depth 
1299                (lazy ("(re)considering goal " ^ 
1300                        (string_of_int g) ^" : "^ppterm status gty)); 
1301              debug_print (~depth:depth) 
1302                (lazy ("Case: " ^ CicNotationPp.pp_term t));
1303              let depth,cache =
1304                if t=Ast.Ident("__whd",None) then depth, cache 
1305                else depth+1,loop_cache in 
1306              try
1307                auto_clusters flags signature (cache:cache) depth status
1308              with Gaveup _ ->
1309                debug_print ~depth (lazy "Failed");())
1310           alternatives;
1311         raise (debug_print(lazy "no more candidates"); Gaveup IntSet.empty)
1312 ;;
1313
1314 let int name l def = 
1315   try int_of_string (List.assoc name l)
1316   with Failure _ | Not_found -> def
1317 ;;
1318
1319 let auto_tac ~params:(_univ,flags) status =
1320   let oldstatus = status in
1321   let status = (status:> NTacStatus.tac_status) in
1322   let goals = head_goals status#stack in
1323   let status, facts = mk_th_cache status goals in
1324   let unit_eq = index_local_equations status#eq_cache status in 
1325   let cache = init_cache ~facts ~unit_eq  () in 
1326 (*   pp_th status facts; *)
1327 (*
1328   NDiscriminationTree.DiscriminationTree.iter status#auto_cache (fun p t -> 
1329     debug_print (lazy(
1330       NDiscriminationTree.NCicIndexable.string_of_path p ^ " |--> " ^
1331       String.concat "\n    " (List.map (
1332       NCicPp.ppterm ~metasenv:[] ~context:[] ~subst:[])
1333         (NDiscriminationTree.TermSet.elements t))
1334       )));
1335 *)
1336   let depth = int "depth" flags 3 in 
1337   let size  = int "size" flags 10 in 
1338   let width = int "width" flags 4 (* (3+List.length goals)*) in 
1339   (* XXX fix sort *)
1340 (*   let goals = List.map (fun i -> (i,P)) goals in *)
1341   let signature = height_of_goals status in 
1342   let flags = { 
1343           last = true;
1344           maxwidth = width;
1345           maxsize = size;
1346           maxdepth = depth;
1347           timeout = Unix.gettimeofday() +. 3000.;
1348           do_types = false; 
1349   } in
1350   let initial_time = Unix.gettimeofday() in
1351   app_counter:= 0;
1352   let rec up_to x y =
1353     if x > y then
1354       (print(lazy
1355         ("TIME ELAPSED:"^string_of_float(Unix.gettimeofday()-.initial_time)));
1356        debug_print(lazy
1357         ("Applicative nodes:"^string_of_int !app_counter)); 
1358        raise (Error (lazy "auto gave up", None)))
1359     else
1360       let _ = debug_print (lazy("\n\nRound "^string_of_int x^"\n")) in
1361       let flags = { flags with maxdepth = x } 
1362       in 
1363         try auto_clusters (~top:true) flags signature cache 0 status;assert false 
1364 (*
1365         try auto_main flags signature cache 0 status;assert false
1366 *)
1367         with
1368           | Gaveup _ -> up_to (x+1) y
1369           | Proved s -> 
1370               debug_print (lazy ("proved at depth " ^ string_of_int x));
1371               let stack = 
1372                 match s#stack with
1373                   | (g,t,k,f) :: rest -> (filter_open g,t,k,f):: rest
1374                   | _ -> assert false
1375               in
1376               let s = s#set_stack stack in
1377                 oldstatus#set_status s 
1378   in
1379   let s = up_to depth depth in
1380     debug_print(lazy
1381         ("TIME ELAPSED:"^string_of_float(Unix.gettimeofday()-.initial_time)));
1382     debug_print(lazy
1383         ("Applicative nodes:"^string_of_int !app_counter));
1384     s
1385 ;;
1386