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