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.
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_______________________________________________________________ *)
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
19 open Continuationals.Stack
21 module Ast = CicNotationPt
22 let app_counter = ref 0
24 (* ======================= utility functions ========================= *)
25 module IntSet = Set.Make(struct type t = int let compare = compare end)
27 let get_sgoalty status g =
28 let _,_,metasenv,subst,_ = status#obj in
30 let _, ctx, ty = NCicUtils.lookup_meta g metasenv in
31 let ty = NCicUntrusted.apply_subst subst ctx ty in
32 let ctx = NCicUntrusted.apply_subst_context
33 ~fix_projections:true subst ctx
35 NTacStatus.mk_cic_term ctx ty
36 with NCicUtils.Meta_not_found _ as exn -> fail ~exn (lazy "get_sgoalty")
40 let gty = get_sgoalty status g in
41 metas_of_term status gty
44 let menv_closure status gl =
45 let rec closure acc = function
47 | x::l when IntSet.mem x acc -> closure acc l
48 | x::l -> closure (IntSet.add x acc) (deps status x @ l)
49 in closure IntSet.empty gl
52 (* we call a "fact" an object whose hypothesis occur in the goal
53 or in types of goal-variables *)
54 let branch status ty =
55 let status, ty, metas = saturate ~delta:0 status ty in
56 noprint (lazy ("saturated ty :" ^ (ppterm status ty)));
57 let g_metas = metas_of_term status ty in
58 let clos = menv_closure status g_metas in
59 (* let _,_,metasenv,_,_ = status#obj in *)
63 let _, m = term_of_cic_term status m (ctx_of m) in
65 | NCic.Meta(i,_) -> IntSet.add i acc
69 (* IntSet.subset menv clos *)
70 IntSet.cardinal(IntSet.diff menv clos)
72 let is_a_fact status ty = branch status ty = 0
74 let is_a_fact_obj s uri =
75 let obj = NCicEnvironment.get_checked_obj uri in
77 | (_,_,[],[],NCic.Constant(_,_,Some(t),ty,_)) ->
78 is_a_fact s (mk_cic_term [] ty)
79 (* aggiungere i costruttori *)
82 let is_a_fact_ast status subst metasenv ctx cand =
84 (lazy ("------- checking " ^ CicNotationPp.pp_term cand));
85 let status, t = disambiguate status ctx ("",0,cand) None in
86 let status,t = term_of_cic_term status t ctx in
87 let ty = NCicTypeChecker.typeof subst metasenv ctx t in
88 is_a_fact status (mk_cic_term ctx ty)
90 let current_goal status =
91 let open_goals = head_goals status#stack in
92 assert (List.length open_goals = 1);
93 let open_goal = List.hd open_goals in
94 let gty = get_goalty status open_goal in
95 let ctx = ctx_of gty in
98 let height_of_ref (NReference.Ref (uri, x)) =
103 | NReference.CoFix _ ->
104 let _,height,_,_,_ = NCicEnvironment.get_checked_obj uri in
106 | NReference.Def h -> h
107 | NReference.Fix (_,_,h) -> h
110 (*************************** height functions ********************************)
111 let fast_height_of_term t =
115 NCic.Meta (_,(_,NCic.Ctx l)) -> List.iter aux l
119 | NCic.Implicit _ -> assert false
120 | NCic.Const nref as t ->
122 prerr_endline (NCicPp.ppterm ~metasenv:[] ~subst:[]
123 ~context:[] t ^ ":" ^ string_of_int (height_of_ref nref));
125 h := max !h (height_of_ref nref)
126 | NCic.Prod (_,t1,t2)
127 | NCic.Lambda (_,t1,t2) -> aux t1; aux t2
128 | NCic.LetIn (_,s,ty,t) -> aux s; aux ty; aux t
129 | NCic.Appl l -> List.iter aux l
130 | NCic.Match (_,outty,t,pl) -> aux outty; aux t; List.iter aux pl
135 let height_of_goal g status =
136 let ty = get_goalty status g in
137 let context = ctx_of ty in
138 let _, ty = term_of_cic_term status ty (ctx_of ty) in
139 let h = ref (fast_height_of_term ty) in
142 | _, NCic.Decl ty -> h := max !h (fast_height_of_term ty)
143 | _, NCic.Def (bo,ty) ->
144 h := max !h (fast_height_of_term ty);
145 h := max !h (fast_height_of_term bo);
151 let height_of_goals status =
152 let open_goals = head_goals status#stack in
153 assert (List.length open_goals > 0);
157 h := max !h (height_of_goal open_goal status))
159 debug_print (lazy ("altezza sequente: " ^ string_of_int !h));
163 (* =============================== paramod =========================== *)
164 let solve f status eq_cache goal =
167 if fast then NCicParamod.fast_eq_check
168 else NCicParamod.paramod in
170 let n,h,metasenv,subst,o = status#obj in
171 let gname, ctx, gty = List.assoc goal metasenv in
172 let gty = NCicUntrusted.apply_subst subst ctx gty in
173 let build_status (pt, _, metasenv, subst) =
175 debug_print (lazy ("refining: "^(NCicPp.ppterm ctx subst metasenv pt)));
176 let stamp = Unix.gettimeofday () in
177 let metasenv, subst, pt, pty =
178 (* NCicRefiner.typeof status
179 (* (status#set_coerc_db NCicCoercion.empty_db) *)
180 metasenv subst ctx pt None in
181 print (lazy ("refined: "^(NCicPp.ppterm ctx subst metasenv pt)));
182 debug_print (lazy ("synt: "^(NCicPp.ppterm ctx subst metasenv pty)));
183 let metasenv, subst =
184 NCicUnification.unify status metasenv subst ctx gty pty *)
186 (status#set_coerc_db NCicCoercion.empty_db)
187 metasenv subst ctx pt (Some gty)
189 debug_print (lazy (Printf.sprintf "Refined in %fs"
190 (Unix.gettimeofday() -. stamp)));
191 let status = status#set_obj (n,h,metasenv,subst,o) in
192 let metasenv = List.filter (fun j,_ -> j <> goal) metasenv in
193 let subst = (goal,(gname,ctx,pt,pty)) :: subst in
194 Some (status#set_obj (n,h,metasenv,subst,o))
196 NCicRefiner.RefineFailure msg
197 | NCicRefiner.Uncertain msg ->
198 debug_print (lazy ("WARNING: refining in fast_eq_check failed" ^
199 snd (Lazy.force msg))); None
200 | NCicRefiner.AssertFailure msg ->
201 debug_print (lazy ("WARNING: refining in fast_eq_check failed" ^
202 Lazy.force msg)); None
205 HExtlib.filter_map build_status
206 (f status metasenv subst ctx eq_cache (NCic.Rel ~-1,gty))
209 let fast_eq_check eq_cache status goal =
210 match solve NCicParamod.fast_eq_check status eq_cache goal with
211 | [] -> raise (Error (lazy "no proof found",None))
215 let dist_fast_eq_check eq_cache s =
216 NTactics.distribute_tac (fast_eq_check eq_cache) s
219 let auto_eq_check eq_cache status =
221 let s = dist_fast_eq_check eq_cache status in
227 (* warning: ctx is supposed to be already instantiated w.r.t subst *)
228 let index_local_equations eq_cache status =
229 debug_print (lazy "indexing equations");
230 let open_goals = head_goals status#stack in
231 let open_goal = List.hd open_goals in
232 let ngty = get_goalty status open_goal in
233 let ctx = ctx_of ngty in
238 let t = NCic.Rel !c in
240 let ty = NCicTypeChecker.typeof [] [] ctx t in
241 if is_a_fact status (mk_cic_term ctx ty) then
242 (debug_print(lazy("eq indexing " ^ (NCicPp.ppterm ctx [] [] ty)));
243 NCicParamod.forward_infer_step eq_cache t ty)
245 (debug_print (lazy ("not a fact: " ^ (NCicPp.ppterm ctx [] [] ty)));
248 | NCicTypeChecker.TypeCheckerFailure _
249 | NCicTypeChecker.AssertFailure _ -> eq_cache)
253 let fast_eq_check_tac ~params s =
254 let unit_eq = index_local_equations s#eq_cache s in
255 dist_fast_eq_check unit_eq s
258 let paramod eq_cache status goal =
259 match solve NCicParamod.paramod status eq_cache goal with
260 | [] -> raise (Error (lazy "no proof found",None))
264 let paramod_tac ~params s =
265 let unit_eq = index_local_equations s#eq_cache s in
266 NTactics.distribute_tac (paramod unit_eq) s
269 let demod eq_cache status goal =
270 match solve NCicParamod.demod status eq_cache goal with
271 | [] -> raise (Error (lazy "no progress",None))
275 let demod_tac ~params s =
276 let unit_eq = index_local_equations s#eq_cache s in
277 NTactics.distribute_tac (demod unit_eq) s
281 let fast_eq_check_tac_all ~params eq_cache status =
282 let g,_,_ = current_goal status in
283 let allstates = fast_eq_check_all status eq_cache g in
284 let pseudo_low_tac s _ _ = s in
285 let pseudo_low_tactics =
286 List.map pseudo_low_tac allstates
288 List.map (fun f -> NTactics.distribute_tac f status) pseudo_low_tactics
293 let demod status eq_cache goal =
294 let n,h,metasenv,subst,o = status#obj in
295 let gname, ctx, gty = List.assoc goal metasenv in
296 let gty = NCicUntrusted.apply_subst subst ctx gty in
298 let demod_tac ~params s =
299 let unit_eq = index_local_equations s#eq_cache s in
300 dist_fast_eq_check unit_eq s
303 (*************** subsumption ****************)
305 let close_wrt_context =
309 | name, NCic.Decl t -> NCic.Prod(name,t,ty)
310 | name, NCic.Def(bo, _) -> NCicSubstitution.subst bo ty)
313 let args_for_context ?(k=1) ctx =
316 (fun (n,l) ctx_entry ->
318 | name, NCic.Decl t -> n+1,NCic.Rel(n)::l
319 | name, NCic.Def(bo, _) -> n+1,l)
323 let constant_for_meta ctx ty i =
324 let name = "cic:/foo"^(string_of_int i)^".con" in
325 let uri = NUri.uri_of_string name in
326 let ty = close_wrt_context ty ctx in
327 (* prerr_endline (NCicPp.ppterm [] [] [] ty); *)
328 let attr = (`Generated,`Definition,`Local) in
329 let obj = NCic.Constant([],name,None,ty,attr) in
330 (* Constant of relevance * string * term option * term * c_attr *)
334 let refresh metasenv =
336 (fun (metasenv,subst) (i,(iattr,ctx,ty)) ->
337 let ikind = NCicUntrusted.kind_of_meta iattr in
338 let metasenv,j,instance,ty =
339 NCicMetaSubst.mk_meta ~attrs:iattr
340 metasenv ctx ~with_type:ty ikind in
341 let s_entry = i,(iattr, ctx, instance, ty) in
342 let metasenv = List.filter (fun x,_ -> i <> x) metasenv in
343 metasenv,s_entry::subst)
344 (metasenv,[]) metasenv
346 (* close metasenv returns a ground instance of all the metas in the
347 metasenv, insantiatied with axioms, and the list of these axioms *)
348 let close_metasenv metasenv subst =
350 let metasenv = NCicUntrusted.apply_subst_metasenv subst metasenv in
352 let metasenv = NCicUntrusted.sort_metasenv subst metasenv in
354 (fun (subst,objs) (i,(iattr,ctx,ty)) ->
355 let ty = NCicUntrusted.apply_subst subst ctx ty in
357 NCicUntrusted.apply_subst_context ~fix_projections:true
359 let (uri,_,_,_,obj) as okind =
360 constant_for_meta ctx ty i in
362 NCicEnvironment.check_and_add_obj okind;
363 let iref = NReference.reference_of_spec uri NReference.Decl in
365 let args = args_for_context ctx in
366 if args = [] then NCic.Const iref
367 else NCic.Appl(NCic.Const iref::args)
369 (* prerr_endline (NCicPp.ppterm ctx [] [] iterm); *)
370 let s_entry = i, ([], ctx, iterm, ty)
371 in s_entry::subst,okind::objs
372 with _ -> assert false)
376 let ground_instances status gl =
377 let _,_,metasenv,subst,_ = status#obj in
378 let subset = menv_closure status gl in
379 let submenv = List.filter (fun (x,_) -> IntSet.mem x subset) metasenv in
381 let submenv = metasenv in
383 let subst, objs = close_metasenv submenv subst in
387 let (_, ctx, t, _) = List.assoc i subst in
388 debug_print (lazy (NCicPp.ppterm ctx [] [] t));
390 (fun (uri,_,_,_,_) as obj ->
391 NCicEnvironment.invalidate_item (`Obj (uri, obj)))
396 Not_found -> assert false
400 let replace_meta i args target =
401 let rec aux k = function
402 (* TODO: local context *)
403 | NCic.Meta (j,lc) when i = j ->
407 List.map (NCicSubstitution.subst_meta lc) args in
408 NCic.Appl(NCic.Rel k::args))
409 | NCic.Meta (j,lc) as m ->
416 aux k (NCicSubstitution.lift n t)) l))))
417 | t -> NCicUtils.map (fun _ k -> k+1) k aux t
422 let close_wrt_metasenv subst =
424 (fun ty (i,(iattr,ctx,mty)) ->
425 let mty = NCicUntrusted.apply_subst subst ctx mty in
427 NCicUntrusted.apply_subst_context ~fix_projections:true
429 let cty = close_wrt_context mty ctx in
430 let name = "foo"^(string_of_int i) in
431 let ty = NCicSubstitution.lift 1 ty in
432 let args = args_for_context ~k:1 ctx in
433 (* prerr_endline (NCicPp.ppterm ctx [] [] iterm); *)
434 let ty = replace_meta i args ty
436 NCic.Prod(name,cty,ty))
440 let _,_,metasenv,subst,_ = status#obj in
441 let subset = menv_closure status [g] in
442 let subset = IntSet.remove g subset in
443 let elems = IntSet.elements subset in
444 let _, ctx, ty = NCicUtils.lookup_meta g metasenv in
445 let ty = NCicUntrusted.apply_subst subst ctx ty in
446 debug_print (lazy ("metas in " ^ (NCicPp.ppterm ctx [] metasenv ty)));
447 debug_print (lazy (String.concat ", " (List.map string_of_int elems)));
448 let submenv = List.filter (fun (x,_) -> IntSet.mem x subset) metasenv in
449 let submenv = List.rev (NCicUntrusted.sort_metasenv subst submenv) in
451 let submenv = metasenv in
453 let ty = close_wrt_metasenv subst ty submenv in
454 debug_print (lazy (NCicPp.ppterm ctx [] [] ty));
458 (****************** smart application ********************)
460 let saturate_to_ref metasenv subst ctx nref ty =
461 let height = height_of_ref nref in
462 let rec aux metasenv ty args =
463 let ty,metasenv,moreargs =
464 NCicMetaSubst.saturate ~delta:height metasenv subst ctx ty 0 in
466 | NCic.Const(NReference.Ref (_,NReference.Def _) as nre)
468 let _, _, bo, _, _, _ = NCicEnvironment.get_checked_def nre in
469 aux metasenv ty (args@moreargs)
470 | NCic.Appl(NCic.Const(NReference.Ref (_,NReference.Def _) as nre)::tl)
472 let _, _, bo, _, _, _ = NCicEnvironment.get_checked_def nre in
473 aux metasenv (NCic.Appl(bo::tl)) (args@moreargs)
474 | _ -> ty,metasenv,(args@moreargs)
478 let smart_apply t unit_eq status g =
479 let n,h,metasenv,subst,o = status#obj in
480 let gname, ctx, gty = List.assoc g metasenv in
481 (* let ggty = mk_cic_term context gty in *)
482 let status, t = disambiguate status ctx t None in
483 let status,t = term_of_cic_term status t ctx in
484 let _,_,metasenv,subst,_ = status#obj in
485 let ty = NCicTypeChecker.typeof subst metasenv ctx t in
486 let ty,metasenv,args =
489 | NCic.Appl(NCic.Const(nref)::_) ->
490 saturate_to_ref metasenv subst ctx nref ty
492 NCicMetaSubst.saturate metasenv subst ctx ty 0 in
493 let metasenv,j,inst,_ = NCicMetaSubst.mk_meta metasenv ctx `IsTerm in
494 let status = status#set_obj (n,h,metasenv,subst,o) in
495 let pterm = if args=[] then t else
497 | NCic.Appl l -> NCic.Appl(l@args)
498 | _ -> NCic.Appl(t::args)
500 noprint(lazy("pterm " ^ (NCicPp.ppterm ctx [] [] pterm)));
501 noprint(lazy("pty " ^ (NCicPp.ppterm ctx [] [] ty)));
504 NUri.uri_of_string "cic:/matita/ng/Plogic/equality/eq_coerc.con" in
505 let ref = NReference.reference_of_spec uri (NReference.Def(2)) in
509 NCic.Appl[eq_coerc;ty;NCic.Implicit `Type;pterm;inst] in
510 let smart = mk_cic_term ctx smart in
512 let status = instantiate status g smart in
513 let _,_,metasenv,subst,_ = status#obj in
514 let _,ctx,jty = List.assoc j metasenv in
515 let jty = NCicUntrusted.apply_subst subst ctx jty in
516 print(lazy("goal " ^ (NCicPp.ppterm ctx [] [] jty)));
517 fast_eq_check unit_eq status j
519 | Error _ as e -> debug_print (lazy "error"); raise e
521 let smart_apply_tac t s =
522 let unit_eq = index_local_equations s#eq_cache s in
523 NTactics.distribute_tac (smart_apply t unit_eq) s
525 let smart_apply_auto t eq_cache =
526 NTactics.distribute_tac (smart_apply t eq_cache)
529 (****************** types **************)
532 type th_cache = (NCic.context * InvRelDiscriminationTree.t) list
534 let keys_of_term status t =
535 let status, orig_ty = typeof status (ctx_of t) t in
536 let _, ty, _ = saturate ~delta:max_int status orig_ty in
539 let _, ty = term_of_cic_term status ty (ctx_of ty) in
541 | NCic.Const (NReference.Ref (_,(NReference.Def h | NReference.Fix (_,_,h))))
542 | NCic.Appl (NCic.Const(NReference.Ref(_,(NReference.Def h | NReference.Fix (_,_,h))))::_)
544 let _,ty,_= saturate status ~delta:(h-1) orig_ty in
551 let mk_th_cache status gl =
553 (fun (status, acc) g ->
554 let gty = get_goalty status g in
555 let ctx = ctx_of gty in
556 debug_print(lazy("th cache for: "^ppterm status gty));
557 debug_print(lazy("th cache in: "^ppcontext status ctx));
558 if List.mem_assq ctx acc then status, acc else
559 let idx = InvRelDiscriminationTree.empty in
562 (fun (status, i, idx) _ ->
563 let t = mk_cic_term ctx (NCic.Rel i) in
564 let status, keys = keys_of_term status t in
565 debug_print(lazy("indexing: "^ppterm status t ^ ": " ^ string_of_int (List.length keys)));
567 List.fold_left (fun idx k ->
568 InvRelDiscriminationTree.index idx k t) idx keys
573 status, (ctx, idx) :: acc)
577 let add_to_th t c ty =
578 let key_c = ctx_of t in
579 if not (List.mem_assq key_c c) then
580 (key_c ,InvRelDiscriminationTree.index
581 InvRelDiscriminationTree.empty ty t ) :: c
583 let rec replace = function
585 | (x, idx) :: tl when x == key_c ->
586 (x, InvRelDiscriminationTree.index idx ty t) :: tl
587 | x :: tl -> x :: replace tl
592 let rm_from_th t c ty =
593 let key_c = ctx_of t in
594 if not (List.mem_assq key_c c) then assert false
596 let rec replace = function
598 | (x, idx) :: tl when x == key_c ->
599 (x, InvRelDiscriminationTree.remove_index idx ty t) :: tl
600 | x :: tl -> x :: replace tl
605 let pp_idx status idx =
606 InvRelDiscriminationTree.iter idx
608 debug_print(lazy("K: " ^ NCicInverseRelIndexable.string_of_path k));
610 (fun t -> debug_print(lazy("\t"^ppterm status t)))
617 debug_print(lazy( "-----------------------------------------------"));
618 debug_print(lazy( (NCicPp.ppcontext ~metasenv:[] ~subst:[] ctx)));
619 debug_print(lazy( "||====> "));
623 let search_in_th gty th =
624 let c = ctx_of gty in
625 let rec aux acc = function
626 | [] -> (* Ncic_termSet.elements *) acc
629 let idx = List.assq k th in
630 let acc = Ncic_termSet.union acc
631 (InvRelDiscriminationTree.retrieve_unifiables idx gty)
634 with Not_found -> aux acc tl
636 aux Ncic_termSet.empty c
640 do_types : bool; (* solve goals in Type *)
641 last : bool; (* last goal: take first solution only *)
649 {facts : th_cache; (* positive results *)
650 under_inspection : cic_term list * th_cache; (* to prune looping *)
651 unit_eq : NCicParamod.state
655 type goal = int * sort (* goal, depth, sort *)
656 type fail = goal * cic_term
657 type candidate = int * Ast.term (* unique candidate number, candidate *)
659 exception Gaveup of IntSet.t (* a sublist of unprovable conjunctive
660 atoms of the input goals *)
661 exception Proved of NTacStatus.tac_status
663 (* let close_failures _ c = c;; *)
664 (* let prunable _ _ _ = false;; *)
665 (* let cache_examine cache gty = `Notfound;; *)
666 (* let put_in_subst s _ _ _ = s;; *)
667 (* let add_to_cache_and_del_from_orlist_if_green_cut _ _ c _ _ o f _ = c, o, f, false ;; *)
668 (* let cache_add_underinspection c _ _ = c;; *)
670 let init_cache ?(facts=[]) ?(under_inspection=[],[])
671 ?(unit_eq=NCicParamod.empty_state) _ =
673 under_inspection = under_inspection;
677 let only signature _context candidate = true
679 (* TASSI: nel trie ci mettiamo solo il body, non il ty *)
681 NCicTypeChecker.typeof ~subst:[] ~metasenv:[] [] candidate
683 let height = fast_height_of_term candidate_ty in
684 let rc = signature >= height in
686 debug_print (lazy ("Filtro: " ^ NCicPp.ppterm ~context:[] ~subst:[]
687 ~metasenv:[] candidate ^ ": " ^ string_of_int height))
689 debug_print (lazy ("Tengo: " ^ NCicPp.ppterm ~context:[] ~subst:[]
690 ~metasenv:[] candidate ^ ": " ^ string_of_int height));
695 let candidate_no = ref 0;;
697 let openg_no status = List.length (head_goals status#stack)
699 let sort_candidates status ctx candidates =
700 let _,_,metasenv,subst,_ = status#obj in
702 let status,ct = disambiguate status ctx ("",0,cand) None in
703 let status,t = term_of_cic_term status ct ctx in
704 let ty = NCicTypeChecker.typeof subst metasenv ctx t in
705 let res = branch status (mk_cic_term ctx ty) in
706 debug_print (lazy ("branch factor for: " ^ (ppterm status ct) ^ " = "
707 ^ (string_of_int res)));
710 let candidates = List.map (fun t -> branch t,t) candidates in
712 List.sort (fun (a,_) (b,_) -> a - b) candidates in
713 let candidates = List.map snd candidates in
714 debug_print (lazy ("candidates =\n" ^ (String.concat "\n"
715 (List.map CicNotationPp.pp_term candidates))));
718 let sort_new_elems l =
719 List.sort (fun (_,s1) (_,s2) -> openg_no s1 - openg_no s2) l
721 let try_candidate ?(smart=0) flags depth status eq_cache ctx t =
723 debug_print ~depth (lazy ("try " ^ CicNotationPp.pp_term t));
725 if smart= 0 then NTactics.apply_tac ("",0,t) status
726 else if smart = 1 then smart_apply_auto ("",0,t) eq_cache status
727 else (* smart = 2: both *)
728 try NTactics.apply_tac ("",0,t) status
729 with Error _ as exc ->
730 smart_apply_auto ("",0,t) eq_cache status
733 let og_no = openg_no status in
734 if (* og_no > flags.maxwidth || *)
735 ((depth + 1) = flags.maxdepth && og_no <> 0) then
736 (debug_print ~depth (lazy "pruned immediately"); None)
739 let status, cict = disambiguate status ctx ("",0,t) None in
740 let status,ct = term_of_cic_term status cict ctx in
741 let _,_,metasenv,subst,_ = status#obj in
742 let ty = NCicTypeChecker.typeof subst metasenv ctx ct in
743 let res = branch status (mk_cic_term ctx ty) in
744 if smart=1 && og_no > res then
745 (print (lazy ("branch factor for: " ^ (ppterm status cict) ^ " = "
746 ^ (string_of_int res) ^ " vs. " ^ (string_of_int og_no)));
747 print ~depth (lazy "strange application"); None)
750 Some ((!candidate_no,t),status))
751 with Error (msg,exn) -> debug_print ~depth (lazy "failed"); None
754 let sort_of subst metasenv ctx t =
755 let ty = NCicTypeChecker.typeof subst metasenv ctx t in
756 let metasenv',ty = NCicUnification.fix_sorts metasenv subst ty in
757 assert (metasenv = metasenv');
758 NCicTypeChecker.typeof subst metasenv ctx ty
761 let type0= NUri.uri_of_string ("cic:/matita/pts/Type0.univ")
764 let perforate_small subst metasenv context t =
765 let rec aux = function
766 | NCic.Appl (hd::tl) ->
768 let s = sort_of subst metasenv context t in
770 | NCic.Sort(NCic.Type [`Type,u])
771 when u=type0 -> NCic.Meta (0,(0,NCic.Irl 0))
774 NCic.Appl (hd::List.map map tl)
780 let get_candidates ?(smart=true) status cache signature gty =
781 let universe = status#auto_cache in
782 let _,_,metasenv,subst,_ = status#obj in
783 let context = ctx_of gty in
785 let _status, t = term_of_cic_term status t context
788 | NCic.Const r -> Ast.NRef r | _ -> assert false in
789 let _, raw_gty = term_of_cic_term status gty context in
790 let cands = NDiscriminationTree.DiscriminationTree.retrieve_unifiables
792 let local_cands = search_in_th gty cache in
793 debug_print (lazy ("candidates for" ^ NTacStatus.ppterm status gty));
794 debug_print (lazy ("local cands = " ^ (string_of_int (List.length (Ncic_termSet.elements local_cands)))));
795 let together global local =
797 (List.filter (only signature context)
798 (NDiscriminationTree.TermSet.elements global)) @
799 List.map t_ast (Ncic_termSet.elements local) in
800 let candidates = together cands local_cands in
801 let candidates = sort_candidates status context candidates in
802 let smart_candidates =
808 let weak_gty = perforate_small subst metasenv context raw_gty in
810 NCic.Appl (hd:: HExtlib.mk_list(NCic.Meta (0,(0,NCic.Irl 0)))
811 (List.length tl)) in *)
813 NDiscriminationTree.DiscriminationTree.retrieve_unifiables
816 NDiscriminationTree.TermSet.diff more_cands cands in
817 let cic_weak_gty = mk_cic_term context weak_gty in
818 let more_local_cands = search_in_th cic_weak_gty cache in
819 let smart_local_cands =
820 Ncic_termSet.diff more_local_cands local_cands in
821 together smart_cands smart_local_cands
822 (* together more_cands more_local_cands *)
826 let smart_candidates = sort_candidates status context smart_candidates in
827 (* if smart then smart_candidates, []
828 else candidates, [] *)
829 candidates, smart_candidates
832 let applicative_case depth signature status flags gty (cache:cache) =
833 app_counter:= !app_counter+1;
834 let _,_,metasenv,subst,_ = status#obj in
835 let context = ctx_of gty in
836 let tcache = cache.facts in
838 let status, t = term_of_cic_term status gty context in
839 let t = NCicReduction.whd subst context t in
841 | NCic.Prod _ -> true, false
842 | _ -> false, NCicParamod.is_equation metasenv subst context t
844 debug_print(lazy (string_of_bool is_eq));
845 let candidates, smart_candidates =
846 get_candidates ~smart:(not is_eq) status tcache signature gty in
848 (lazy ("candidates: " ^ string_of_int (List.length candidates)));
850 (lazy ("smart candidates: " ^
851 string_of_int (List.length smart_candidates)));
854 let smart_candidates = [] in *)
855 let sm = if is_eq then 0 else 2 in
856 let maxd = ((depth + 1) = flags.maxdepth) in
857 let only_one = flags.last && maxd in
858 debug_print (lazy ("only_one: " ^ (string_of_bool only_one)));
859 debug_print (lazy ("maxd: " ^ (string_of_bool maxd)));
863 if (only_one && (elems <> [])) then elems
865 if (maxd && not(is_prod) &
866 not(is_a_fact_ast status subst metasenv context cand))
867 then (debug_print (lazy "pruned: not a fact"); elems)
869 match try_candidate (~smart:sm)
870 flags depth status cache.unit_eq context cand with
872 | Some x -> x::elems)
876 if only_one && elems <> [] then elems
880 if (only_one && (elems <> [])) then elems
882 if (maxd && not(is_prod) &&
883 not(is_a_fact_ast status subst metasenv context cand))
884 then (debug_print (lazy "pruned: not a fact"); elems)
886 match try_candidate (~smart:1)
887 flags depth status cache.unit_eq context cand with
889 | Some x -> x::elems)
898 (* gty is supposed to be meta-closed *)
899 let is_subsumed depth status gty cache =
900 if cache=[] then false else (
901 debug_print ~depth (lazy("Subsuming " ^ (ppterm status gty)));
902 let n,h,metasenv,subst,obj = status#obj in
903 let ctx = ctx_of gty in
904 let _ , target = term_of_cic_term status gty ctx in
905 let target = NCicSubstitution.lift 1 target in
906 (* candidates must only be searched w.r.t the given context *)
909 let idx = List.assq ctx cache in
910 Ncic_termSet.elements
911 (InvRelDiscriminationTree.retrieve_generalizations idx gty)
915 (lazy ("failure candidates: " ^ string_of_int (List.length candidates)));
919 let _ , source = term_of_cic_term status t ctx in
921 NCic.Prod("foo",source,target) in
923 NCicMetaSubst.mk_meta
924 metasenv ctx ~with_type:implication `IsType in
925 let status = status#set_obj (n,h,metasenv,subst,obj) in
926 let status = status#set_stack [([1,Open j],[],[],`NoTag)] in
928 let status = NTactics.intro_tac "foo" status in
930 NTactics.apply_tac ("",0,Ast.NCic (NCic.Rel 1)) status
932 if (head_goals status#stack = []) then raise Found
937 with Found -> debug_print ~depth (lazy "success");true)
940 let rec guess_name name ctx =
941 if name = "_" then guess_name "auto" ctx else
942 if not (List.mem_assoc name ctx) then name else
943 guess_name (name^"'") ctx
947 let _, ctx, gty = current_goal status in
948 let _, raw_gty = term_of_cic_term status gty ctx in
950 | NCic.Prod (name,_,_) -> Some (guess_name name ctx)
953 let intro ~depth status facts name =
954 let status = NTactics.intro_tac name status in
955 let _, ctx, ngty = current_goal status in
956 let t = mk_cic_term ctx (NCic.Rel 1) in
957 let status, keys = keys_of_term status t in
958 let facts = List.fold_left (add_to_th t) facts keys in
959 debug_print ~depth (lazy ("intro: "^ name));
960 (* unprovability is not stable w.r.t introduction *)
964 let rec intros_facts ~depth status facts =
965 match is_prod status with
968 intro ~depth status facts name
969 in intros_facts ~depth status facts
973 let rec intros ~depth status (cache:cache) =
974 match is_prod status with
977 intros_facts ~depth status cache.facts
979 (* we reindex the equation from scratch *)
981 index_local_equations status#eq_cache status in
982 status, init_cache ~facts ~unit_eq ()
986 let reduce ~depth status g =
987 let n,h,metasenv,subst,o = status#obj in
988 let attr, ctx, ty = NCicUtils.lookup_meta g metasenv in
989 let ty = NCicUntrusted.apply_subst subst ctx ty in
990 let ty' = NCicReduction.whd ~subst ctx ty in
994 (lazy ("reduced to: "^ NCicPp.ppterm ctx subst metasenv ty'));
996 (g,(attr,ctx,ty'))::(List.filter (fun (i,_) -> i<>g) metasenv)
998 let status = status#set_obj (n,h,metasenv,subst,o) in
999 (* we merge to gain a depth level; the previous goal level should
1001 let status = NTactics.merge_tac status in
1003 [(!candidate_no,Ast.Ident("__whd",None)),status])
1006 let do_something signature flags status g depth gty cache =
1008 let l = reduce ~depth status g in
1009 (* if l <> [] then l,cache else *)
1010 (* backward aplications *)
1015 ((!candidate_no,Ast.Ident("__paramod",None)),s))
1016 (auto_eq_check cache.unit_eq status)
1019 if ((l1 <> []) && flags.last) then [] else
1020 applicative_case depth signature status flags gty cache
1021 (* fast paramodulation *)
1023 (* states in l1 have have an empty set of subgoals: no point to sort them *)
1025 (lazy ("alternatives = " ^ (string_of_int (List.length (l1@l@l2)))));
1026 (* l1 @ (sort_new_elems (l @ l2)), cache *)
1027 l1 @ (List.rev l2) @ l, cache
1030 let pp_goal = function
1031 | (_,Continuationals.Stack.Open i)
1032 | (_,Continuationals.Stack.Closed i) -> string_of_int i
1035 let pp_goals status l =
1039 let gty = get_goalty status i in
1040 NTacStatus.ppterm status gty)
1047 let compare = Pervasives.compare
1051 module MS = HTopoSort.Make(M)
1054 let sort_tac status =
1056 match status#stack with
1057 | [] -> assert false
1058 | (goals, t, k, tag) :: s ->
1059 let g = head_goals status#stack in
1061 (List.rev (MS.topological_sort g (deps status))) in
1062 debug_print (lazy ("old g = " ^
1063 String.concat "," (List.map string_of_int g)));
1064 debug_print (lazy ("sorted goals = " ^
1065 String.concat "," (List.map string_of_int sortedg)));
1066 let is_it i = function
1067 | (_,Continuationals.Stack.Open j )
1068 | (_,Continuationals.Stack.Closed j ) -> i = j
1071 List.map (fun i -> List.find (is_it i) goals) sortedg
1073 (sorted_goals, t, k, tag) :: s
1075 status#set_stack gstatus
1078 let clean_up_tac status =
1080 match status#stack with
1081 | [] -> assert false
1082 | (g, t, k, tag) :: s ->
1083 let is_open = function
1084 | (_,Continuationals.Stack.Open _) -> true
1085 | (_,Continuationals.Stack.Closed _) -> false
1087 let g' = List.filter is_open g in
1088 (g', t, k, tag) :: s
1090 status#set_stack gstatus
1093 let focus_tac focus status =
1095 match status#stack with
1096 | [] -> assert false
1097 | (g, t, k, tag) :: s ->
1098 let in_focus = function
1099 | (_,Continuationals.Stack.Open i)
1100 | (_,Continuationals.Stack.Closed i) -> List.mem i focus
1102 let focus,others = List.partition in_focus g
1104 (* we need to mark it as a BranchTag, otherwise cannot merge later *)
1105 (focus,[],[],`BranchTag) :: (others, t, k, tag) :: s
1107 status#set_stack gstatus
1110 let deep_focus_tac level focus status =
1111 let in_focus = function
1112 | (_,Continuationals.Stack.Open i)
1113 | (_,Continuationals.Stack.Closed i) -> List.mem i focus
1115 let rec slice level gs =
1116 if level = 0 then [],[],gs else
1118 | [] -> assert false
1119 | (g, t, k, tag) :: s ->
1120 let f,o,gs = slice (level-1) s in
1121 let f1,o1 = List.partition in_focus g
1123 (f1,[],[],`BranchTag)::f, (o1, t, k, tag)::o, gs
1126 let f,o,s = slice level status#stack in f@o@s
1128 status#set_stack gstatus
1131 let rec stack_goals level gs =
1132 if level = 0 then []
1134 | [] -> assert false
1136 let is_open = function
1137 | (_,Continuationals.Stack.Open i) -> Some i
1138 | (_,Continuationals.Stack.Closed _) -> None
1140 HExtlib.filter_map is_open g @ stack_goals (level-1) s
1143 let open_goals level status = stack_goals level status#stack
1146 let move_to_side level status =
1147 match status#stack with
1148 | [] -> assert false
1150 let is_open = function
1151 | (_,Continuationals.Stack.Open i) -> Some i
1152 | (_,Continuationals.Stack.Closed _) -> None
1154 let others = menv_closure status (stack_goals (level-1) tl) in
1155 List.for_all (fun i -> IntSet.mem i others)
1156 (HExtlib.filter_map is_open g)
1158 let rec auto_clusters ?(top=false)
1159 flags signature cache depth status : unit =
1160 debug_print ~depth (lazy ("entering auto clusters at depth " ^
1161 (string_of_int depth)));
1162 (* ignore(Unix.select [] [] [] 0.01); *)
1163 let status = clean_up_tac status in
1164 let goals = head_goals status#stack in
1166 if depth = 0 then raise (Proved status)
1168 let status = NTactics.merge_tac status in
1170 let l,tree = cache.under_inspection in
1172 | [] -> cache (* possible because of intros that cleans the cache *)
1173 | a::tl -> let tree = rm_from_th a tree a in
1174 {cache with under_inspection = tl,tree}
1176 auto_clusters flags signature cache (depth-1) status
1177 else if List.length goals < 2 then
1178 auto_main flags signature cache depth status
1180 let all_goals = open_goals (depth+1) status in
1181 debug_print ~depth (lazy ("goals = " ^
1182 String.concat "," (List.map string_of_int all_goals)));
1183 let classes = HExtlib.clusters (deps status) all_goals in
1186 if List.length gl > flags.maxwidth then
1187 (debug_print ~depth (lazy "FAIL GLOBAL WIDTH");
1188 raise (Gaveup IntSet.empty))
1190 if List.length classes = 1 then
1192 {flags with last = (List.length all_goals = 1)} in
1193 (* no need to cluster *)
1194 auto_main flags signature cache depth status
1196 let classes = if top then List.rev classes else classes in
1202 ("cluster:" ^ String.concat "," (List.map string_of_int l)))
1206 (fun (status,b) gl ->
1208 {flags with last = (List.length gl = 1)} in
1209 let lold = List.length status#stack in
1210 debug_print ~depth (lazy ("stack length = " ^
1211 (string_of_int lold)));
1212 let fstatus = deep_focus_tac (depth+1) gl status in
1214 debug_print ~depth (lazy ("focusing on" ^
1215 String.concat "," (List.map string_of_int gl)));
1216 auto_main flags signature cache depth fstatus; assert false
1219 let status = NTactics.merge_tac status in
1220 let lnew = List.length status#stack in
1221 assert (lold = lnew);
1223 | Gaveup _ when top -> (status,b)
1225 (status,false) classes
1227 let rec final_merge n s =
1228 if n = 0 then s else final_merge (n-1) (NTactics.merge_tac s)
1229 in let status = final_merge depth status
1230 in if b then raise (Proved status) else raise (Gaveup IntSet.empty)
1234 (* BRAND NEW VERSION *)
1235 auto_main flags signature (cache:cache) depth status: unit =
1236 debug_print ~depth (lazy "entering auto main");
1237 debug_print ~depth (lazy ("stack length = " ^
1238 (string_of_int (List.length status#stack))));
1239 (* ignore(Unix.select [] [] [] 0.01); *)
1240 let status = sort_tac (clean_up_tac status) in
1241 let goals = head_goals status#stack in
1243 | [] when depth = 0 -> raise (Proved status)
1245 let status = NTactics.merge_tac status in
1247 let l,tree = cache.under_inspection in
1249 | [] -> cache (* possible because of intros that cleans the cache *)
1250 | a::tl -> let tree = rm_from_th a tree a in
1251 {cache with under_inspection = tl,tree}
1253 auto_clusters flags signature cache (depth-1) status
1255 if depth > 0 && move_to_side depth status
1257 let status = NTactics.merge_tac status in
1259 let l,tree = cache.under_inspection in
1261 | [] -> cache (* possible because of intros that cleans the cache*)
1262 | a::tl -> let tree = rm_from_th a tree a in
1263 {cache with under_inspection = tl,tree}
1265 auto_clusters flags signature cache (depth-1) status
1267 let ng = List.length goals in
1268 (* moved inside auto_clusters *)
1269 if ng > flags.maxwidth then
1270 (print ~depth (lazy "FAIL LOCAL WIDTH"); raise (Gaveup IntSet.empty))
1271 else if depth = flags.maxdepth then
1272 raise (Gaveup IntSet.empty)
1274 let status = NTactics.branch_tac ~force:true status in
1275 let status, cache = intros ~depth status cache in
1276 let g,gctx, gty = current_goal status in
1277 let ctx,ty = close status g in
1278 let closegty = mk_cic_term ctx ty in
1279 let status, gty = apply_subst status gctx gty in
1280 debug_print ~depth (lazy("Attacking goal " ^ (string_of_int g) ^" : "^ppterm status gty));
1281 if is_subsumed depth status closegty (snd cache.under_inspection) then
1282 (debug_print ~depth (lazy "SUBSUMED");
1283 raise (Gaveup IntSet.add g IntSet.empty))
1285 let new_sig = height_of_goal g status in
1286 if new_sig < signature then
1287 (debug_print (lazy ("news = " ^ (string_of_int new_sig)));
1288 debug_print (lazy ("olds = " ^ (string_of_int signature))));
1289 let alternatives, cache =
1290 do_something signature flags status g depth gty cache in
1292 let l,tree = cache.under_inspection in
1293 let l,tree = closegty::l, add_to_th closegty tree closegty in
1294 {cache with under_inspection = l,tree} in
1296 (fun ((_,t),status) ->
1298 (lazy ("(re)considering goal " ^
1299 (string_of_int g) ^" : "^ppterm status gty));
1300 debug_print (~depth:depth)
1301 (lazy ("Case: " ^ CicNotationPp.pp_term t));
1303 if t=Ast.Ident("__whd",None) then depth, cache
1304 else depth+1,loop_cache in
1306 auto_clusters flags signature (cache:cache) depth status
1308 debug_print ~depth (lazy "Failed");())
1310 raise (debug_print(lazy "no more candidates"); Gaveup IntSet.empty)
1313 let int name l def =
1314 try int_of_string (List.assoc name l)
1315 with Failure _ | Not_found -> def
1318 let auto_tac ~params:(_univ,flags) status =
1319 let oldstatus = status in
1320 let status = (status:> NTacStatus.tac_status) in
1321 let goals = head_goals status#stack in
1322 let status, facts = mk_th_cache status goals in
1323 let unit_eq = index_local_equations status#eq_cache status in
1324 let cache = init_cache ~facts ~unit_eq () in
1325 (* pp_th status facts; *)
1327 NDiscriminationTree.DiscriminationTree.iter status#auto_cache (fun p t ->
1329 NDiscriminationTree.NCicIndexable.string_of_path p ^ " |--> " ^
1330 String.concat "\n " (List.map (
1331 NCicPp.ppterm ~metasenv:[] ~context:[] ~subst:[])
1332 (NDiscriminationTree.TermSet.elements t))
1335 let depth = int "depth" flags 3 in
1336 let size = int "size" flags 10 in
1337 let width = int "width" flags 4 (* (3+List.length goals)*) in
1339 (* let goals = List.map (fun i -> (i,P)) goals in *)
1340 let signature = height_of_goals status in
1346 timeout = Unix.gettimeofday() +. 3000.;
1349 let initial_time = Unix.gettimeofday() in
1354 ("TIME ELAPSED:"^string_of_float(Unix.gettimeofday()-.initial_time)));
1356 ("Applicative nodes:"^string_of_int !app_counter));
1357 raise (Error (lazy "auto gave up", None)))
1359 let _ = debug_print (lazy("\n\nRound "^string_of_int x^"\n")) in
1360 let flags = { flags with maxdepth = x }
1362 try auto_clusters (~top:true) flags signature cache 0 status;assert false
1364 try auto_main flags signature cache 0 status;assert false
1367 | Gaveup _ -> up_to (x+1) y
1369 debug_print (lazy ("proved at depth " ^ string_of_int x));
1372 | (g,t,k,f) :: rest -> (filter_open g,t,k,f):: rest
1375 let s = s#set_stack stack in
1376 oldstatus#set_status s
1378 let s = up_to depth depth in
1380 ("TIME ELAPSED:"^string_of_float(Unix.gettimeofday()-.initial_time)));
1382 ("Applicative nodes:"^string_of_int !app_counter));