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