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