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