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_______________________________________________________________ *)
15 let debug_print ?(depth=0) s =
16 if !debug then prerr_endline (String.make depth '\t'^Lazy.force s) else ()
17 (* let print = debug_print *)
18 let print ?(depth=0) s =
19 prerr_endline (String.make depth '\t'^Lazy.force s)
21 let debug_do f = if !debug then f () else ()
23 open Continuationals.Stack
25 module Ast = CicNotationPt
26 let app_counter = ref 0
28 (* ======================= utility functions ========================= *)
29 module IntSet = Set.Make(struct type t = int let compare = compare end)
31 let get_sgoalty status g =
32 let _,_,metasenv,subst,_ = status#obj in
34 let _, ctx, ty = NCicUtils.lookup_meta g metasenv in
35 let ty = NCicUntrusted.apply_subst subst ctx ty in
36 let ctx = NCicUntrusted.apply_subst_context
37 ~fix_projections:true subst ctx
39 NTacStatus.mk_cic_term ctx ty
40 with NCicUtils.Meta_not_found _ as exn -> fail ~exn (lazy "get_sgoalty")
44 let gty = get_sgoalty status g in
45 metas_of_term status gty
48 let menv_closure status gl =
49 let rec closure acc = function
51 | x::l when IntSet.mem x acc -> closure acc l
52 | x::l -> closure (IntSet.add x acc) (deps status x @ l)
53 in closure IntSet.empty gl
56 (* we call a "fact" an object whose hypothesis occur in the goal
57 or in types of goal-variables *)
58 let is_a_fact status ty =
59 let status, ty, metas = saturate ~delta:0 status ty in
60 debug_print (lazy ("saturated ty :" ^ (ppterm status ty)));
61 let g_metas = metas_of_term status ty in
62 let clos = menv_closure status g_metas in
63 (* let _,_,metasenv,_,_ = status#obj in *)
67 let _, m = term_of_cic_term status m (ctx_of m) in
69 | NCic.Meta(i,_) -> IntSet.add i acc
72 in IntSet.subset menv clos;;
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
99 (* =============================== paramod =========================== *)
100 let solve fast status eq_cache goal =
102 if fast then NCicParamod.fast_eq_check
103 else NCicParamod.paramod in
104 let n,h,metasenv,subst,o = status#obj in
105 let gname, ctx, gty = List.assoc goal metasenv in
106 let gty = NCicUntrusted.apply_subst subst ctx gty in
107 let build_status (pt, _, metasenv, subst) =
109 debug_print (lazy ("refining: "^(NCicPp.ppterm ctx subst metasenv pt)));
110 let stamp = Unix.gettimeofday () in
111 let metasenv, subst, pt, pty =
112 NCicRefiner.typeof status
113 (* (status#set_coerc_db NCicCoercion.empty_db) *)
114 metasenv subst ctx pt None in
115 debug_print (lazy ("refined: "^(NCicPp.ppterm ctx subst metasenv pt)));
116 debug_print (lazy ("synt: "^(NCicPp.ppterm ctx subst metasenv pty)));
117 let metasenv, subst =
118 NCicUnification.unify status metasenv subst ctx gty pty
119 (* the previous code is much less expensive than directly refining
120 pt with expected type pty
122 prerr_endline ("exp: "^(NCicPp.ppterm ctx subst metasenv gty));
124 (status#set_coerc_db NCicCoercion.empty_db)
125 metasenv subst ctx pt (Some gty) *)
127 debug_print (lazy (Printf.sprintf "Refined in %fs"
128 (Unix.gettimeofday() -. stamp)));
129 let status = status#set_obj (n,h,metasenv,subst,o) in
130 let metasenv = List.filter (fun j,_ -> j <> goal) metasenv in
131 let subst = (goal,(gname,ctx,pt,pty)) :: subst in
132 Some (status#set_obj (n,h,metasenv,subst,o))
134 NCicRefiner.RefineFailure msg
135 | NCicRefiner.Uncertain msg ->
136 debug_print (lazy ("WARNING: refining in fast_eq_check failed" ^
137 snd (Lazy.force msg))); None
138 | NCicRefiner.AssertFailure msg ->
139 debug_print (lazy ("WARNING: refining in fast_eq_check failed" ^
140 Lazy.force msg)); None
143 HExtlib.filter_map build_status
144 (f status metasenv subst ctx eq_cache (NCic.Rel ~-1,gty))
147 let fast_eq_check eq_cache status goal =
148 match solve true status eq_cache goal with
149 | [] -> raise (Error (lazy "no proof found",None))
153 let dist_fast_eq_check eq_cache s =
154 NTactics.distribute_tac (fast_eq_check eq_cache) s
157 let auto_eq_check eq_cache status =
159 let s = dist_fast_eq_check eq_cache status in
165 (* warning: ctx is supposed to be already instantiated w.r.t subst *)
166 let index_local_equations eq_cache status =
167 let open_goals = head_goals status#stack in
168 let open_goal = List.hd open_goals in
169 let ngty = get_goalty status open_goal in
170 let ctx = ctx_of ngty in
175 let t = NCic.Rel !c in
177 let ty = NCicTypeChecker.typeof [] [] ctx t in
178 if is_a_fact status (mk_cic_term ctx ty) then
179 (debug_print(lazy("eq indexing " ^ (NCicPp.ppterm ctx [] [] ty)));
180 NCicParamod.forward_infer_step eq_cache t ty)
182 (debug_print (lazy ("not a fact: " ^ (NCicPp.ppterm ctx [] [] ty)));
185 | NCicTypeChecker.TypeCheckerFailure _
186 | NCicTypeChecker.AssertFailure _ -> eq_cache)
190 let fast_eq_check_tac ~params s =
191 let unit_eq = index_local_equations s#eq_cache s in
192 dist_fast_eq_check unit_eq s
195 let paramod eq_cache status goal =
196 match solve false status eq_cache goal with
197 | [] -> raise (Error (lazy "no proof found",None))
201 let paramod_tac ~params s =
202 let unit_eq = index_local_equations s#eq_cache s in
203 NTactics.distribute_tac (paramod unit_eq) s
207 let fast_eq_check_tac_all ~params eq_cache status =
208 let g,_,_ = current_goal status in
209 let allstates = fast_eq_check_all status eq_cache g in
210 let pseudo_low_tac s _ _ = s in
211 let pseudo_low_tactics =
212 List.map pseudo_low_tac allstates
214 List.map (fun f -> NTactics.distribute_tac f status) pseudo_low_tactics
219 let demod status eq_cache goal =
220 let n,h,metasenv,subst,o = status#obj in
221 let gname, ctx, gty = List.assoc goal metasenv in
222 let gty = NCicUntrusted.apply_subst subst ctx gty in
224 let demod_tac ~params s =
225 let unit_eq = index_local_equations s#eq_cache s in
226 dist_fast_eq_check unit_eq s
229 (*************** subsumption ****************)
231 let close_wrt_context =
235 | name, NCic.Decl t -> NCic.Prod(name,t,ty)
236 | name, NCic.Def(bo, _) -> NCicSubstitution.subst bo ty)
239 let args_for_context ?(k=1) ctx =
242 (fun (n,l) ctx_entry ->
244 | name, NCic.Decl t -> n+1,NCic.Rel(n)::l
245 | name, NCic.Def(bo, _) -> n+1,l)
249 let constant_for_meta ctx ty i =
250 let name = "cic:/foo"^(string_of_int i)^".con" in
251 let uri = NUri.uri_of_string name in
252 let ty = close_wrt_context ty ctx in
253 (* prerr_endline (NCicPp.ppterm [] [] [] ty); *)
254 let attr = (`Generated,`Definition,`Local) in
255 let obj = NCic.Constant([],name,None,ty,attr) in
256 (* Constant of relevance * string * term option * term * c_attr *)
260 let refresh metasenv =
262 (fun (metasenv,subst) (i,(iattr,ctx,ty)) ->
263 let ikind = NCicUntrusted.kind_of_meta iattr in
264 let metasenv,j,instance,ty =
265 NCicMetaSubst.mk_meta ~attrs:iattr
266 metasenv ctx ~with_type:ty ikind in
267 let s_entry = i,(iattr, ctx, instance, ty) in
268 let metasenv = List.filter (fun x,_ -> i <> x) metasenv in
269 metasenv,s_entry::subst)
270 (metasenv,[]) metasenv
272 (* close metasenv returns a ground instance of all the metas in the
273 metasenv, insantiatied with axioms, and the list of these axioms *)
274 let close_metasenv metasenv subst =
276 let metasenv = NCicUntrusted.apply_subst_metasenv subst metasenv in
278 let metasenv = NCicUntrusted.sort_metasenv subst metasenv in
280 (fun (subst,objs) (i,(iattr,ctx,ty)) ->
281 let ty = NCicUntrusted.apply_subst subst ctx ty in
283 NCicUntrusted.apply_subst_context ~fix_projections:true
285 let (uri,_,_,_,obj) as okind =
286 constant_for_meta ctx ty i in
288 NCicEnvironment.check_and_add_obj okind;
289 let iref = NReference.reference_of_spec uri NReference.Decl in
291 let args = args_for_context ctx in
292 if args = [] then NCic.Const iref
293 else NCic.Appl(NCic.Const iref::args)
295 (* prerr_endline (NCicPp.ppterm ctx [] [] iterm); *)
296 let s_entry = i, ([], ctx, iterm, ty)
297 in s_entry::subst,okind::objs
298 with _ -> assert false)
302 let ground_instances status gl =
303 let _,_,metasenv,subst,_ = status#obj in
304 let subset = menv_closure status gl in
305 let submenv = List.filter (fun (x,_) -> IntSet.mem x subset) metasenv in
307 let submenv = metasenv in
309 let subst, objs = close_metasenv submenv subst in
313 let (_, ctx, t, _) = List.assoc i subst in
314 debug_print (lazy (NCicPp.ppterm ctx [] [] t));
316 (fun (uri,_,_,_,_) as obj ->
317 NCicEnvironment.invalidate_item (`Obj (uri, obj)))
322 Not_found -> assert false
326 let replace_meta i args target =
327 let rec aux k = function
328 (* TODO: local context *)
329 | NCic.Meta (j,lc) when i = j ->
333 List.map (NCicSubstitution.subst_meta lc) args in
334 NCic.Appl(NCic.Rel k::args))
335 | NCic.Meta (j,lc) as m ->
342 aux k (NCicSubstitution.lift n t)) l))))
343 | t -> NCicUtils.map (fun _ k -> k+1) k aux t
348 let close_wrt_metasenv subst =
350 (fun ty (i,(iattr,ctx,mty)) ->
351 let mty = NCicUntrusted.apply_subst subst ctx mty in
353 NCicUntrusted.apply_subst_context ~fix_projections:true
355 let cty = close_wrt_context mty ctx in
356 let name = "foo"^(string_of_int i) in
357 let ty = NCicSubstitution.lift 1 ty in
358 let args = args_for_context ~k:1 ctx in
359 (* prerr_endline (NCicPp.ppterm ctx [] [] iterm); *)
360 let ty = replace_meta i args ty
362 NCic.Prod(name,cty,ty))
366 let _,_,metasenv,subst,_ = status#obj in
367 let subset = menv_closure status [g] in
368 let subset = IntSet.remove g subset in
369 let elems = IntSet.elements subset in
370 let _, ctx, ty = NCicUtils.lookup_meta g metasenv in
371 let ty = NCicUntrusted.apply_subst subst ctx ty in
372 debug_print (lazy ("metas in " ^ (NCicPp.ppterm ctx [] metasenv ty)));
373 debug_print (lazy (String.concat ", " (List.map string_of_int elems)));
374 let submenv = List.filter (fun (x,_) -> IntSet.mem x subset) metasenv in
375 let submenv = List.rev (NCicUntrusted.sort_metasenv subst submenv) in
377 let submenv = metasenv in
379 let ty = close_wrt_metasenv subst ty submenv in
380 debug_print (lazy (NCicPp.ppterm ctx [] [] ty));
386 (* =================================== auto =========================== *)
387 (****************** AUTO ********************
389 let calculate_timeout flags =
390 if flags.timeout = 0. then
391 (debug_print (lazy "AUTO WITH NO TIMEOUT");
392 {flags with timeout = infinity})
396 let is_equational_case goalty flags =
397 let ensure_equational t =
398 if is_an_equational_goal t then true
401 (flags.use_paramod && is_an_equational_goal goalty) ||
402 (flags.use_only_paramod && ensure_equational goalty)
405 type menv = Cic.metasenv
406 type subst = Cic.substitution
407 type goal = ProofEngineTypes.goal * int * AutoTypes.sort
408 let candidate_no = ref 0;;
409 type candidate = int * Cic.term Lazy.t
410 type cache = AutoCache.cache
413 (* the goal (mainly for depth) and key of the goal *)
414 goal * AutoCache.cache_key
416 (* goal has to be proved *)
418 (* goal has to be cached as a success obtained using candidate as the first
420 | S of goal * AutoCache.cache_key * candidate * int
422 (* menv, subst, size, operations done (only S), operations to do, failures to cache if any op fails *)
423 menv * subst * int * op list * op list * fail list
425 (* list of computations that may lead to the solution: all op list will
426 * end with the same (S(g,_)) *)
429 (* menv, subst, alternatives, tables, cache *)
430 | Proved of menv * subst * elem list * AutomationCache.tables * cache
431 | Gaveup of AutomationCache.tables * cache
434 (* the status exported to the external observer *)
436 (* context, (goal,candidate) list, and_list, history *)
437 Cic.context * (int * Cic.term * bool * int * (int * Cic.term Lazy.t) list) list *
438 (int * Cic.term * int) list * Cic.term Lazy.t list
441 let rec aux acc = function
442 | (D g)::tl -> aux (acc@[g]) tl
448 let calculate_goal_ty (goalno,_,_) s m =
450 let _,cc,goalty = CicUtil.lookup_meta goalno m in
451 (* XXX applicare la subst al contesto? *)
452 Some (cc, CicMetaSubst.apply_subst s goalty)
453 with CicUtil.Meta_not_found i when i = goalno -> None
456 let calculate_closed_goal_ty (goalno,_,_) s =
458 let cc,_,goalty = List.assoc goalno s in
459 (* XXX applicare la subst al contesto? *)
460 Some (cc, CicMetaSubst.apply_subst s goalty)
465 let pp_status ctx status =
467 let names = Utils.names_of_context ctx in
470 ProofEngineReduction.replace
471 ~equality:(fun a b -> match b with Cic.Meta _ -> true | _ -> false)
472 ~what:[Cic.Rel 1] ~with_what:[Cic.Implicit None] ~where:x
476 let string_of_do m s (gi,_,_ as g) d =
477 match calculate_goal_ty g s m with
478 | Some (_,gty) -> Printf.sprintf "D(%d, %s, %d)" gi (pp gty) d
479 | None -> Printf.sprintf "D(%d, _, %d)" gi d
481 let string_of_s m su k (ci,ct) gi =
482 Printf.sprintf "S(%d, %s, %s, %d)" gi (pp k) (pp (Lazy.force ct)) ci
484 let string_of_ol m su l =
488 | D (g,d,s) -> string_of_do m su (g,d,s) d
489 | S ((gi,_,_),k,c,_) -> string_of_s m su k c gi)
492 let string_of_fl m s fl =
494 (List.map (fun ((i,_,_),ty) ->
495 Printf.sprintf "(%d, %s)" i (pp ty)) fl)
497 let rec aux = function
499 | (m,s,_,_,ol,fl)::tl ->
500 Printf.eprintf "< [%s] ;;; [%s]>\n"
501 (string_of_ol m s ol) (string_of_fl m s fl);
504 Printf.eprintf "-------------------------- status -------------------\n";
506 Printf.eprintf "-----------------------------------------------------\n";
509 let auto_status = ref [] ;;
510 let auto_context = ref [];;
511 let in_pause = ref false;;
512 let pause b = in_pause := b;;
513 let cond = Condition.create ();;
514 let mutex = Mutex.create ();;
515 let hint = ref None;;
516 let prune_hint = ref [];;
518 let step _ = Condition.signal cond;;
519 let give_hint n = hint := Some n;;
520 let give_prune_hint hint =
521 prune_hint := hint :: !prune_hint
528 Condition.wait cond mutex;
533 let get_auto_status _ =
534 let status = !auto_status in
535 let and_list,elems,last =
538 | (m,s,_,don,gl,fail)::tl ->
541 (fun (id,d,_ as g) ->
542 match calculate_goal_ty g s m with
543 | Some (_,x) -> Some (id,x,d) | None -> None)
547 (* these are the S goalsin the or list *)
550 (fun (m,s,_,don,gl,fail) ->
552 (function S (g,k,c,_) -> Some (g,k,c) | _ -> None)
556 (* this function eats id from a list l::[id,x] returning x, l *)
557 let eat_tail_if_eq id l =
558 let rec aux (s, l) = function
560 | ((id1,_,_),k1,c)::tl when id = id1 ->
562 | None -> aux (Some c,l) tl
563 | Some _ -> assert false)
564 | ((id1,_,_),k1,c as e)::tl -> aux (s, e::l) tl
566 let c, l = aux (None, []) l in
569 let eat_in_parallel id l =
570 let rec aux (b,eaten, new_l as acc) l =
574 match eat_tail_if_eq id l with
575 | None, l -> aux (b@[false], eaten, new_l@[l]) tl
576 | Some t,l -> aux (b@[true],eaten@[t], new_l@[l]) tl
580 let rec eat_all rows l =
584 match List.rev elem with
585 | ((to_eat,depth,_),k,_)::next_lunch ->
586 let b, eaten, l = eat_in_parallel to_eat l in
587 let eaten = HExtlib.list_uniq eaten in
588 let eaten = List.rev eaten in
589 let b = true (* List.hd (List.rev b) *) in
590 let rows = rows @ [to_eat,k,b,depth,eaten] in
592 | [] -> eat_all rows or_list
594 eat_all [] (List.rev orlist)
598 (function (S (_,_,(_,c),_)) -> Some c | _ -> None)
601 (* let rows = List.filter (fun (_,l) -> l <> []) rows in *)
602 and_list, rows, history
604 !auto_context, elems, and_list, last
607 (* Works if there is no dependency over proofs *)
608 let is_a_green_cut goalty =
609 CicUtil.is_meta_closed goalty
611 let rec first_s = function
612 | (D _)::tl -> first_s tl
613 | (S (g,k,c,s))::tl -> Some ((g,k,c,s),tl)
616 let list_union l1 l2 =
617 (* TODO ottimizzare compare *)
618 HExtlib.list_uniq (List.sort compare (l1 @ l1))
620 let rec eq_todo l1 l2 =
622 | (D g1) :: tl1,(D g2) :: tl2 when g1=g2 -> eq_todo tl1 tl2
623 | (S (g1,k1,(c1,lt1),i1)) :: tl1, (S (g2,k2,(c2,lt2),i2)) :: tl2
624 when i1 = i2 && g1 = g2 && k1 = k2 && c1 = c2 ->
625 if Lazy.force lt1 = Lazy.force lt2 then eq_todo tl1 tl2 else false
629 let eat_head todo id fl orlist =
630 let rec aux acc = function
632 | (m, s, _, _, todo1, fl1)::tl as orlist ->
634 match first_s todo1 with
635 | None -> orlist, acc
636 | Some (((gno,_,_),_,_,_), todo11) ->
637 (* TODO confronto tra todo da ottimizzare *)
638 if gno = id && eq_todo todo11 todo then
639 aux (list_union fl1 acc) tl
647 let close_proof p ty menv context =
649 List.map fst (CicUtil.metas_of_term p @ CicUtil.metas_of_term ty)
651 let menv = List.filter (fun (i,_,_) -> List.exists ((=)i) metas) menv in
652 naif_closure p menv context
654 (* XXX capire bene quando aggiungere alla cache *)
655 let add_to_cache_and_del_from_orlist_if_green_cut
656 g s m cache key todo orlist fl ctx size minsize
658 let cache = cache_remove_underinspection cache key in
659 (* prima per fare la irl usavamo il contesto vero e proprio e non quello
661 match calculate_closed_goal_ty g s with
662 | None -> assert false
663 | Some (canonical_ctx , gty) ->
664 let goalno,depth,sort = g in
665 let irl = mk_irl canonical_ctx in
666 let goal = Cic.Meta(goalno, irl) in
667 let proof = CicMetaSubst.apply_subst s goal in
668 let green_proof, closed_proof =
669 let b = is_a_green_cut proof in
671 b, (* close_proof proof gty m ctx *) proof
675 debug_print (lazy ("TENTATIVE CACHE: " ^ CicPp.ppterm key));
676 if is_a_green_cut key then
677 (* if the initia goal was closed, we cut alternatives *)
678 let _ = debug_print (lazy ("MANGIO: " ^ string_of_int goalno)) in
679 let orlist, fl = eat_head todo goalno fl orlist in
681 if size < minsize then
682 (debug_print (lazy ("NO CACHE: 2 (size <= minsize)"));cache)
684 (* if the proof is closed we cache it *)
685 if green_proof then cache_add_success cache key proof
686 else (* cache_add_success cache key closed_proof *)
687 (debug_print (lazy ("NO CACHE: (no gree proof)"));cache)
689 cache, orlist, fl, true
692 debug_print (lazy ("TENTATIVE CACHE: " ^ CicPp.ppterm gty));
693 if size < minsize then
694 (debug_print (lazy ("NO CACHE: (size <= minsize)")); cache) else
695 (* if the substituted goal and the proof are closed we cache it *)
696 if is_a_green_cut gty then
697 if green_proof then cache_add_success cache gty proof
698 else (* cache_add_success cache gty closed_proof *)
699 (debug_print (lazy ("NO CACHE: (no green proof (gty))"));cache)
703 CicTypeChecker.type_of_aux' ~subst:s
704 m ctx closed_proof CicUniv.oblivion_ugraph
706 if is_a_green_cut ty then
707 cache_add_success cache ty closed_proof
710 | CicTypeChecker.TypeCheckerFailure _ ->*)
711 (debug_print (lazy ("NO CACHE: (no green gty )"));cache)
713 cache, orlist, fl, false
715 let close_failures (fl : fail list) (cache : cache) =
717 (fun cache ((gno,depth,_),gty) ->
718 if CicUtil.is_meta_closed gty then
719 ( debug_print (lazy ("FAIL: INDUCED: " ^ string_of_int gno));
720 cache_add_failure cache gty depth)
725 let put_in_subst subst metasenv (goalno,_,_) canonical_ctx t ty =
726 let entry = goalno, (canonical_ctx, t,ty) in
727 assert_subst_are_disjoint subst [entry];
728 let subst = entry :: subst in
730 let metasenv = CicMetaSubst.apply_subst_metasenv subst metasenv in
735 let mk_fake_proof metasenv subst (goalno,_,_) goalty context =
736 None,metasenv,subst ,(lazy (Cic.Meta(goalno,mk_irl context))),goalty, []
740 tables cache depth fake_proof goalno goalty subst context
743 let active,passive,bag = tables in
744 let ppterm = ppterm context in
745 let status = (fake_proof,goalno) in
746 if flags.use_only_paramod then
748 debug_print (lazy ("PARAMODULATION SU: " ^
749 string_of_int goalno ^ " " ^ ppterm goalty ));
750 let goal_steps, saturation_steps, timeout =
751 max_int,max_int,flags.timeout
754 Saturation.given_clause bag status active passive
755 goal_steps saturation_steps timeout
757 | None, active, passive, bag ->
758 [], (active,passive,bag), cache, flags
759 | Some(subst',(_,metasenv,_subst,proof,_, _),open_goals),active,
761 assert_subst_are_disjoint subst subst';
762 let subst = subst@subst' in
764 order_new_goals metasenv subst open_goals ppterm
767 List.map (fun (x,sort) -> x,depth-1,sort) open_goals
770 [(!candidate_no,proof),metasenv,subst,open_goals],
771 (active,passive,bag), cache, flags
775 debug_print (lazy ("NARROWING DEL GOAL: " ^
776 string_of_int goalno ^ " " ^ ppterm goalty ));
777 let goal_steps, saturation_steps, timeout =
781 Saturation.solve_narrowing bag status active passive goal_steps
783 | None, active, passive, bag ->
784 [], (active,passive,bag), cache, flags
785 | Some(subst',(_,metasenv,_subst,proof,_, _),open_goals),active,
787 assert_subst_are_disjoint subst subst';
788 let subst = subst@subst' in
790 order_new_goals metasenv subst open_goals ppterm
793 List.map (fun (x,sort) -> x,depth-1,sort) open_goals
796 [(!candidate_no,proof),metasenv,subst,open_goals],
797 (active,passive,bag), cache, flags
801 let params = ([],["use_context","false"]) in
802 let automation_cache = {
803 AutomationCache.tables = tables ;
804 AutomationCache.univ = Universe.empty; }
807 let ((_,metasenv,subst,_,_,_),open_goals) =
809 solve_rewrite ~params ~automation_cache
812 let proof = lazy (Cic.Meta (-1,[])) in
813 [(!candidate_no,proof),metasenv,subst,[]],tables, cache, flags
814 with ProofEngineTypes.Fail _ -> [], tables, cache, flags
816 let res = Saturation.all_subsumed bag status active passive in
819 (fun (subst',(_,metasenv,_subst,proof,_, _),open_goals) ->
820 assert_subst_are_disjoint subst subst';
821 let subst = subst@subst' in
823 order_new_goals metasenv subst open_goals ppterm
826 List.map (fun (x,sort) -> x,depth-1,sort) open_goals
829 (!candidate_no,proof),metasenv,subst,open_goals)
832 res', (active,passive,bag), cache, flags
839 List.sort (fun (_,_,_,l1) (_,_,_,l2) ->
840 let p1 = List.length (prop_only l1) in
841 let p2 = List.length (prop_only l2) in
842 if p1 = p2 then List.length l1 - List.length l2 else p1-p2)
846 let try_candidate dbd
847 goalty tables subst fake_proof goalno depth context cand
849 let ppterm = ppterm context in
851 let actives, passives, bag = tables in
852 let (_,metasenv,subst,_,_,_), open_goals =
853 ProofEngineTypes.apply_tactic
854 (PrimitiveTactics.apply_tac ~term:cand)
857 let tables = actives, passives,
858 Equality.push_maxmeta bag
859 (max (Equality.maxmeta bag) (CicMkImplicit.new_meta metasenv subst))
861 debug_print (lazy (" OK: " ^ ppterm cand));
862 let metasenv = CicRefine.pack_coercion_metasenv metasenv in
863 let open_goals = order_new_goals metasenv subst open_goals ppterm in
864 let open_goals = List.map (fun (x,sort) -> x,depth-1,sort) open_goals in
866 Some ((!candidate_no,lazy cand),metasenv,subst,open_goals), tables
868 | ProofEngineTypes.Fail s -> None,tables
869 | CicUnification.Uncertain s -> None,tables
872 let applicative_case dbd
873 tables depth subst fake_proof goalno goalty metasenv context
874 signature universe cache flags
878 | Cic.Appl (hd::tl) ->
879 Cic.Appl (hd :: HExtlib.mk_list (Cic.Meta (0,[])) (List.length tl))
882 let goalty_aux = goalty in
884 get_candidates flags.skip_trie_filtering universe cache goalty_aux
886 (* if the goal is an equality we skip the congruence theorems
888 if is_equational_case goalty flags
889 then List.filter not_default_eq_term candidates
892 let candidates = List.filter (only signature context metasenv) candidates
896 (fun (tables,elems) cand ->
898 try_candidate dbd goalty
899 tables subst fake_proof goalno depth context cand
901 | None, tables -> tables, elems
902 | Some x, tables -> tables, x::elems)
903 (tables,[]) candidates
905 let elems = sort_new_elems elems in
909 let try_smart_candidate dbd
910 goalty tables subst fake_proof goalno depth context cand
912 let ppterm = ppterm context in
914 let params = ([],[]) in
915 let automation_cache = {
916 AutomationCache.tables = tables ;
917 AutomationCache.univ = Universe.empty; }
919 debug_print (lazy ("candidato per " ^ string_of_int goalno
920 ^ ": " ^ CicPp.ppterm cand));
922 let (_,metasenv,subst,_,_,_) = fake_proof in
923 prerr_endline ("metasenv:\n" ^ CicMetaSubst.ppmetasenv [] metasenv);
924 prerr_endline ("subst:\n" ^ CicMetaSubst.ppsubst ~metasenv subst);
926 let ((_,metasenv,subst,_,_,_),open_goals) =
927 apply_smart ~dbd ~term:cand ~params ~automation_cache
930 let metasenv = CicRefine.pack_coercion_metasenv metasenv in
931 let open_goals = order_new_goals metasenv subst open_goals ppterm in
932 let open_goals = List.map (fun (x,sort) -> x,depth-1,sort) open_goals in
934 Some ((!candidate_no,lazy cand),metasenv,subst,open_goals), tables
936 | ProofEngineTypes.Fail s -> None,tables
937 | CicUnification.Uncertain s -> None,tables
940 let smart_applicative_case dbd
941 tables depth subst fake_proof goalno goalty metasenv context signature
946 | Cic.Appl (hd::tl) ->
947 Cic.Appl (hd :: HExtlib.mk_list (Cic.Meta (0,[])) (List.length tl))
950 let smart_candidates =
951 get_candidates flags.skip_trie_filtering universe cache goalty_aux
954 get_candidates flags.skip_trie_filtering universe cache goalty
956 let smart_candidates =
958 (fun x -> not(List.mem x candidates)) smart_candidates
961 (lazy ("smart_candidates" ^ " = " ^
962 (String.concat "\n" (List.map CicPp.ppterm smart_candidates)))) in
963 debug_print debug_msg;
964 let candidates = List.filter (only signature context metasenv) candidates in
965 let smart_candidates =
966 List.filter (only signature context metasenv) smart_candidates
969 let penalty cand depth =
970 if only signature context metasenv cand then depth else ((prerr_endline (
971 "penalizzo " ^ CicPp.ppterm cand));depth -1)
976 (fun (tables,elems) cand ->
978 try_candidate dbd goalty
979 tables subst fake_proof goalno depth context cand
982 (* if normal application fails we try to be smart *)
983 (match try_smart_candidate dbd goalty
984 tables subst fake_proof goalno depth context cand
986 | None, tables -> tables, elems
987 | Some x, tables -> tables, x::elems)
988 | Some x, tables -> tables, x::elems)
989 (tables,[]) candidates
991 let tables, smart_elems =
993 (fun (tables,elems) cand ->
995 try_smart_candidate dbd goalty
996 tables subst fake_proof goalno depth context cand
998 | None, tables -> tables, elems
999 | Some x, tables -> tables, x::elems)
1000 (tables,[]) smart_candidates
1002 let elems = sort_new_elems (elems @ smart_elems) in
1003 elems, tables, cache
1006 let equational_and_applicative_case dbd
1007 signature universe flags m s g gty tables cache context
1009 let goalno, depth, sort = g in
1010 let fake_proof = mk_fake_proof m s g gty context in
1011 if is_equational_case gty flags then
1012 let elems,tables,cache, flags =
1013 equational_case tables cache
1014 depth fake_proof goalno gty s context flags
1016 let more_elems, tables, cache =
1017 if flags.use_only_paramod then
1020 applicative_case dbd
1021 tables depth s fake_proof goalno
1022 gty m context signature universe cache flags
1024 elems@more_elems, tables, cache, flags
1026 let elems, tables, cache =
1027 match LibraryObjects.eq_URI () with
1029 smart_applicative_case dbd tables depth s fake_proof goalno
1030 gty m context signature universe cache flags
1032 applicative_case dbd tables depth s fake_proof goalno
1033 gty m context signature universe cache flags
1035 elems, tables, cache, flags
1037 let rec condition_for_hint i = function
1039 | S (_,_,(j,_),_):: tl -> j <> i (* && condition_for_hint i tl *)
1040 | _::tl -> condition_for_hint i tl
1042 let prunable_for_size flags s m todo =
1043 let rec aux b = function
1044 | (S _)::tl -> aux b tl
1045 | (D (_,_,T))::tl -> aux b tl
1047 (match calculate_goal_ty g s m with
1049 | Some (canonical_ctx, gty) ->
1051 Utils.weight_of_term
1052 ~consider_metas:false ~count_metas_occurrences:true gty in
1053 let newb = b || gsize > flags.maxgoalsizefactor in
1060 let prunable ty todo =
1061 let rec aux b = function
1062 | (S(_,k,_,_))::tl -> aux (b || Equality.meta_convertibility k ty) tl
1063 | (D (_,_,T))::tl -> aux b tl
1071 let prunable menv subst ty todo =
1072 let rec aux = function
1073 | (S(_,k,_,_))::tl ->
1074 (match Equality.meta_convertibility_subst k ty menv with
1077 no_progress variant tl (* || aux tl*))
1078 | (D (_,_,T))::tl -> aux tl
1080 and no_progress variant = function
1081 | [] -> (*prerr_endline "++++++++++++++++++++++++ no_progress";*) true
1082 | D ((n,_,P) as g)::tl ->
1083 (match calculate_goal_ty g subst menv with
1084 | None -> no_progress variant tl
1086 (match calculate_goal_ty g variant menv with
1087 | None -> assert false
1089 if gty = gty' then no_progress variant tl
1091 (prerr_endline (string_of_int n);
1092 prerr_endline (CicPp.ppterm gty);
1093 prerr_endline (CicPp.ppterm gty');
1094 prerr_endline "---------- subst";
1095 prerr_endline (CicMetaSubst.ppsubst ~metasenv:menv subst);
1096 prerr_endline "---------- variant";
1097 prerr_endline (CicMetaSubst.ppsubst ~metasenv:menv variant);
1098 prerr_endline "---------- menv";
1099 prerr_endline (CicMetaSubst.ppmetasenv [] menv);
1100 no_progress variant tl) *)
1102 | _::tl -> no_progress variant tl
1107 let condition_for_prune_hint prune (m, s, size, don, todo, fl) =
1109 HExtlib.filter_map (function S (_,_,(c,_),_) -> Some c | _ -> None) todo
1111 List.for_all (fun i -> List.for_all (fun j -> i<>j) prune) s
1113 let filter_prune_hint c l =
1114 let prune = !prune_hint in
1115 prune_hint := []; (* possible race... *)
1116 if prune = [] then c,l
1118 cache_reset_underinspection c,
1119 List.filter (condition_for_prune_hint prune) l
1125 auto_all_solutions dbd tables universe cache context metasenv gl flags
1130 MetadataConstraints.UriManagerSet.union set
1131 (MetadataQuery.signature_of metasenv g)
1133 MetadataConstraints.UriManagerSet.empty gl
1135 let goals = order_new_goals metasenv [] gl CicPp.ppterm in
1138 (fun (x,s) -> D (x,flags.maxdepth,s)) goals
1140 let elems = [metasenv,[],1,[],goals,[]] in
1141 let rec aux tables solutions cache elems flags =
1142 match auto_main dbd tables context flags signature universe cache elems with
1143 | Gaveup (tables,cache) ->
1144 solutions,cache, tables
1145 | Proved (metasenv,subst,others,tables,cache) ->
1146 if Unix.gettimeofday () > flags.timeout then
1147 ((subst,metasenv)::solutions), cache, tables
1149 aux tables ((subst,metasenv)::solutions) cache others flags
1151 let rc = aux tables [] cache elems flags in
1153 | [],cache,tables -> [],cache,tables
1154 | solutions, cache,tables ->
1157 (fun (subst,newmetasenv) ->
1159 ProofEngineHelpers.compare_metasenvs ~oldmetasenv:metasenv ~newmetasenv
1161 if opened = [] then Some subst else None)
1164 solutions,cache,tables
1167 (******************* AUTO ***************)
1170 let auto dbd flags metasenv tables universe cache context metasenv gl =
1171 let initial_time = Unix.gettimeofday() in
1175 MetadataConstraints.UriManagerSet.union set
1176 (MetadataQuery.signature_of metasenv g)
1178 MetadataConstraints.UriManagerSet.empty gl
1180 let goals = order_new_goals metasenv [] gl CicPp.ppterm in
1181 let goals = List.map (fun (x,s) -> D(x,flags.maxdepth,s)) goals in
1182 let elems = [metasenv,[],1,[],goals,[]] in
1183 match auto_main dbd tables context flags signature universe cache elems with
1184 | Proved (metasenv,subst,_, tables,cache) ->
1186 ("TIME:"^string_of_float(Unix.gettimeofday()-.initial_time)));
1187 Some (subst,metasenv), cache
1188 | Gaveup (tables,cache) ->
1190 ("TIME:"^string_of_float(Unix.gettimeofday()-.initial_time)));
1194 let auto_tac ~(dbd:HSql.dbd) ~params:(univ,params) ~automation_cache (proof, goal) =
1195 let flags = flags_of_params params () in
1196 let use_library = flags.use_library in
1197 let universe, tables, cache =
1198 init_cache_and_tables
1199 ~dbd ~use_library ~use_context:(not flags.skip_context)
1200 automation_cache univ (proof, goal)
1202 let _,metasenv,subst,_,_, _ = proof in
1203 let _,context,goalty = CicUtil.lookup_meta goal metasenv in
1204 let signature = MetadataQuery.signature_of metasenv goal in
1209 CicTypeChecker.type_of_aux' metasenv context t
1210 CicUniv.oblivion_ugraph
1212 MetadataConstraints.UriManagerSet.union set
1213 (MetadataConstraints.constants_of ty)
1218 if flags.close_more then
1220 tables context (proof, goal)
1221 (auto_all_solutions dbd) signature universe cache
1222 else tables,cache in
1223 let initial_time = Unix.gettimeofday() in
1224 let (_,oldmetasenv,_,_,_, _) = proof in
1227 metasenv,subst,1,[],[D (goal,flags.maxdepth,P)],[]
1229 match auto_main dbd tables context flags signature universe cache [elem] with
1230 | Proved (metasenv,subst,_, tables,cache) ->
1232 ("TIME:"^string_of_float(Unix.gettimeofday()-.initial_time)));
1233 let proof,metasenv =
1234 ProofEngineHelpers.subst_meta_and_metasenv_in_proof
1235 proof goal subst metasenv
1238 ProofEngineHelpers.compare_metasenvs ~oldmetasenv
1239 ~newmetasenv:metasenv
1242 | Gaveup (tables,cache) ->
1245 string_of_float(Unix.gettimeofday()-.initial_time)));
1246 raise (ProofEngineTypes.Fail (lazy "Auto gave up"))
1250 (****************** smart application ********************)
1253 let smart_apply t unit_eq status g =
1254 let n,h,metasenv,subst,o = status#obj in
1255 let gname, ctx, gty = List.assoc g metasenv in
1256 (* let ggty = mk_cic_term context gty in *)
1257 let status, t = disambiguate status ctx t None in
1258 let status,t = term_of_cic_term status t ctx in
1259 let ty = NCicTypeChecker.typeof subst metasenv ctx t in
1260 let ty,metasenv,args = NCicMetaSubst.saturate metasenv subst ctx ty 0 in
1261 let metasenv,j,inst,_ = NCicMetaSubst.mk_meta metasenv ctx `IsTerm in
1262 let status = status#set_obj (n,h,metasenv,subst,o) in
1263 let pterm = if args=[] then t else NCic.Appl(t::args) in
1266 NUri.uri_of_string "cic:/matita/ng/Plogic/equality/eq_coerc.con" in
1267 let ref = NReference.reference_of_spec uri (NReference.Def(2)) in
1271 NCic.Appl[eq_coerc;ty;NCic.Implicit `Type;pterm;inst] in
1272 let smart = mk_cic_term ctx smart in
1274 let status = instantiate status g smart in
1275 let _,_,metasenv,subst,_ = status#obj in
1276 let _,ctx,jty = List.assoc j metasenv in
1277 let jty = NCicUntrusted.apply_subst subst ctx jty in
1278 debug_print(lazy("goal " ^ (NCicPp.ppterm ctx [] [] jty)));
1279 fast_eq_check unit_eq status j
1281 | Error _ as e -> debug_print (lazy "error"); raise e
1283 let smart_apply_tac t s =
1284 let unit_eq = index_local_equations s#eq_cache s in
1285 NTactics.distribute_tac (smart_apply t unit_eq) s
1287 let smart_apply_auto t eq_cache =
1288 NTactics.distribute_tac (smart_apply t eq_cache)
1291 (****************** types **************)
1294 type th_cache = (NCic.context * InvRelDiscriminationTree.t) list
1296 let keys_of_term status t =
1297 let status, orig_ty = typeof status (ctx_of t) t in
1298 let _, ty, _ = saturate ~delta:max_int status orig_ty in
1301 let _, ty = term_of_cic_term status ty (ctx_of ty) in
1303 | NCic.Const (NReference.Ref (_,NReference.Def h))
1304 | NCic.Appl (NCic.Const(NReference.Ref(_,NReference.Def h))::_)
1306 let _,ty,_= saturate status ~delta:(h-1) orig_ty in
1313 let mk_th_cache status gl =
1315 (fun (status, acc) g ->
1316 let gty = get_goalty status g in
1317 let ctx = ctx_of gty in
1318 debug_print(lazy("th cache for: "^ppterm status gty));
1319 debug_print(lazy("th cache in: "^ppcontext status ctx));
1320 if List.mem_assq ctx acc then status, acc else
1321 let idx = InvRelDiscriminationTree.empty in
1324 (fun (status, i, idx) _ ->
1325 let t = mk_cic_term ctx (NCic.Rel i) in
1326 debug_print(lazy("indexing: "^ppterm status t));
1327 let status, keys = keys_of_term status t in
1329 List.fold_left (fun idx k ->
1330 InvRelDiscriminationTree.index idx k t) idx keys
1333 (status, 1, idx) ctx
1335 status, (ctx, idx) :: acc)
1339 let add_to_th t c ty =
1340 let key_c = ctx_of t in
1341 if not (List.mem_assq key_c c) then
1342 (key_c ,InvRelDiscriminationTree.index
1343 InvRelDiscriminationTree.empty ty t ) :: c
1345 let rec replace = function
1347 | (x, idx) :: tl when x == key_c ->
1348 (x, InvRelDiscriminationTree.index idx ty t) :: tl
1349 | x :: tl -> x :: replace tl
1354 let pp_idx status idx =
1355 InvRelDiscriminationTree.iter idx
1357 debug_print(lazy("K: " ^ NCicInverseRelIndexable.string_of_path k));
1359 (fun t -> debug_print(lazy("\t"^ppterm status t)))
1366 debug_print(lazy( "-----------------------------------------------"));
1367 debug_print(lazy( (NCicPp.ppcontext ~metasenv:[] ~subst:[] ctx)));
1368 debug_print(lazy( "||====> "));
1372 let search_in_th gty th =
1373 let c = ctx_of gty in
1374 let rec aux acc = function
1375 | [] -> (* Ncic_termSet.elements *) acc
1378 let idx = List.assq k th in
1379 let acc = Ncic_termSet.union acc
1380 (InvRelDiscriminationTree.retrieve_unifiables idx gty)
1383 with Not_found -> aux acc tl
1385 aux Ncic_termSet.empty c
1389 do_types : bool; (* solve goals in Type *)
1390 last : bool; (* last goal: take first solution only *)
1398 {facts : th_cache; (* positive results *)
1399 under_inspection : th_cache; (* to prune looping *)
1400 unit_eq : NCicParamod.state
1404 type goal = int * sort (* goal, depth, sort *)
1405 type fail = goal * cic_term
1406 type candidate = int * Ast.term (* unique candidate number, candidate *)
1408 exception Gaveup of IntSet.t (* a sublist of unprovable conjunctive
1409 atoms of the input goals *)
1410 exception Proved of NTacStatus.tac_status
1412 (* let close_failures _ c = c;; *)
1413 (* let prunable _ _ _ = false;; *)
1414 (* let cache_examine cache gty = `Notfound;; *)
1415 (* let put_in_subst s _ _ _ = s;; *)
1416 (* let add_to_cache_and_del_from_orlist_if_green_cut _ _ c _ _ o f _ = c, o, f, false ;; *)
1417 (* let cache_add_underinspection c _ _ = c;; *)
1419 let init_cache ?(facts=[]) ?(under_inspection=[])
1420 ?(unit_eq=NCicParamod.empty_state) _ =
1422 under_inspection = under_inspection;
1426 let only _ _ _ = true;;
1428 let candidate_no = ref 0;;
1430 let openg_no status = List.length (head_goals status#stack)
1432 let sort_new_elems l =
1433 List.sort (fun (_,s1) (_,s2) -> openg_no s1 - openg_no s2) l
1435 let try_candidate ?(smart=0) flags depth status eq_cache t =
1437 debug_print ~depth (lazy ("------------ try " ^ CicNotationPp.pp_term t));
1439 if smart= 0 then NTactics.apply_tac ("",0,t) status
1440 else if smart = 1 then smart_apply_auto ("",0,t) eq_cache status
1441 else (* smart = 2: both *)
1442 try NTactics.apply_tac ("",0,t) status
1444 smart_apply_auto ("",0,t) eq_cache status in
1445 let og_no = openg_no status in
1446 if (* og_no > flags.maxwidth || *)
1447 ((depth + 1) = flags.maxdepth && og_no <> 0) then
1448 (debug_print ~depth (lazy "pruned immediately"); None)
1451 Some ((!candidate_no,t),status))
1452 with Error (msg,exn) -> debug_print ~depth (lazy "failed"); None
1455 let get_candidates ?(smart=true) status cache signature gty =
1456 let universe = status#auto_cache in
1457 let context = ctx_of gty in
1459 let _status, t = term_of_cic_term status t context
1461 let c_ast = function
1462 | NCic.Const r -> Ast.NRef r | _ -> assert false in
1463 let _, raw_gty = term_of_cic_term status gty context in
1464 let cands = NDiscriminationTree.DiscriminationTree.retrieve_unifiables
1466 let local_cands = search_in_th gty cache in
1467 let together global local =
1469 (List.filter (only signature context)
1470 (NDiscriminationTree.TermSet.elements global)) @
1471 List.map t_ast (Ncic_termSet.elements local) in
1472 let candidates = together cands local_cands in
1473 let smart_candidates =
1476 | NCic.Appl (hd::tl) ->
1478 NCic.Appl (hd:: HExtlib.mk_list(NCic.Meta (0,(0,NCic.Irl 0)))
1479 (List.length tl)) in
1481 NDiscriminationTree.DiscriminationTree.retrieve_unifiables
1482 universe weak_gty in
1484 NDiscriminationTree.TermSet.diff more_cands cands in
1485 let cic_weak_gty = mk_cic_term context weak_gty in
1486 let more_local_cands = search_in_th cic_weak_gty cache in
1487 let smart_local_cands =
1488 Ncic_termSet.diff more_local_cands local_cands in
1489 together smart_cands smart_local_cands
1493 candidates, smart_candidates
1496 let applicative_case depth signature status flags gty (cache:cache) =
1497 app_counter:= !app_counter+1;
1498 let _,_,metasenv,subst,_ = status#obj in
1499 let context = ctx_of gty in
1500 let tcache = cache.facts in
1502 let status, t = term_of_cic_term status gty context in
1503 NCicParamod.is_equation metasenv subst context t
1505 debug_print(lazy (string_of_bool is_eq));
1506 let candidates, smart_candidates =
1507 get_candidates ~smart:(not is_eq) status tcache signature gty in
1509 (lazy ("candidates: " ^ string_of_int (List.length candidates)));
1511 (lazy ("smart candidates: " ^
1512 string_of_int (List.length smart_candidates)));
1515 let smart_candidates = [] in *)
1516 let sm = if is_eq then 0 else 2 in
1517 let maxd = ((depth + 1) = flags.maxdepth) in
1518 let only_one = flags.last && maxd in
1519 debug_print (lazy ("only_one: " ^ (string_of_bool only_one)));
1520 debug_print (lazy ("maxd: " ^ (string_of_bool maxd)));
1524 if (only_one && (elems <> [])) then elems
1526 if (maxd && not(is_a_fact_ast status subst metasenv context cand))
1527 then (debug_print (lazy "pruned: not a fact"); elems)
1529 match try_candidate (~smart:sm)
1530 flags depth status cache.unit_eq cand with
1532 | Some x -> x::elems)
1536 if only_one && elems <> [] then elems
1540 if (only_one && (elems <> [])) then elems
1542 if (maxd && not(is_a_fact_ast status subst metasenv context cand))
1543 then (debug_print (lazy "pruned: not a fact"); elems)
1545 match try_candidate (~smart:1)
1546 flags depth status cache.unit_eq cand with
1548 | Some x -> x::elems)
1557 (* gty is supposed to be meta-closed *)
1558 let is_subsumed depth status gty cache =
1559 if cache=[] then false else (
1560 debug_print ~depth (lazy("Subsuming " ^ (ppterm status gty)));
1561 let n,h,metasenv,subst,obj = status#obj in
1562 let ctx = ctx_of gty in
1563 let _ , target = term_of_cic_term status gty ctx in
1564 let target = NCicSubstitution.lift 1 target in
1565 (* candidates must only be searched w.r.t the given context *)
1568 let idx = List.assq ctx cache in
1569 Ncic_termSet.elements
1570 (InvRelDiscriminationTree.retrieve_generalizations idx gty)
1571 with Not_found -> []
1574 (lazy ("failure candidates: " ^ string_of_int (List.length candidates)));
1578 let _ , source = term_of_cic_term status t ctx in
1580 NCic.Prod("foo",source,target) in
1581 let metasenv,j,_,_ =
1582 NCicMetaSubst.mk_meta
1583 metasenv ctx ~with_type:implication `IsType in
1584 let status = status#set_obj (n,h,metasenv,subst,obj) in
1585 let status = status#set_stack [([1,Open j],[],[],`NoTag)] in
1587 let status = NTactics.intro_tac "foo" status in
1589 NTactics.apply_tac ("",0,Ast.NCic (NCic.Rel 1)) status
1591 if (head_goals status#stack = []) then raise Found
1596 with Found -> debug_print ~depth (lazy "success");true)
1599 let rec guess_name name ctx =
1600 if name = "_" then guess_name "auto" ctx else
1601 if not (List.mem_assoc name ctx) then name else
1602 guess_name (name^"'") ctx
1605 let is_prod status =
1606 let _, ctx, gty = current_goal status in
1607 let _, raw_gty = term_of_cic_term status gty ctx in
1609 | NCic.Prod (name,_,_) -> Some (guess_name name ctx)
1612 let intro ~depth status facts name =
1613 let status = NTactics.intro_tac name status in
1614 let _, ctx, ngty = current_goal status in
1615 let t = mk_cic_term ctx (NCic.Rel 1) in
1616 let status, keys = keys_of_term status t in
1617 let facts = List.fold_left (add_to_th t) facts keys in
1618 debug_print ~depth (lazy ("intro: "^ name));
1619 (* unprovability is not stable w.r.t introduction *)
1623 let rec intros_facts ~depth status facts =
1624 match is_prod status with
1627 intro ~depth status facts name
1628 in intros_facts ~depth status facts
1629 | _ -> status, facts
1632 let rec intros ~depth status (cache:cache) =
1633 match is_prod status with
1636 intros_facts ~depth status cache.facts
1638 (* we reindex the equation from scratch *)
1640 index_local_equations status#eq_cache status in
1641 (* under_inspection must be set to empty *)
1642 status, init_cache ~facts ~unit_eq ()
1643 | _ -> status, cache
1646 let reduce ~depth status g =
1647 let n,h,metasenv,subst,o = status#obj in
1648 let attr, ctx, ty = NCicUtils.lookup_meta g metasenv in
1649 let ty = NCicUntrusted.apply_subst subst ctx ty in
1650 let ty' = NCicReduction.whd ~subst ctx ty in
1654 (lazy ("reduced to: "^ NCicPp.ppterm ctx subst metasenv ty'));
1656 (g,(attr,ctx,ty'))::(List.filter (fun (i,_) -> i<>g) metasenv)
1658 let status = status#set_obj (n,h,metasenv,subst,o) in
1660 [(!candidate_no,Ast.Ident("__whd",None)),status])
1663 let do_something signature flags status g depth gty cache =
1665 let l = reduce ~depth status g in
1666 (* backward aplications *)
1671 ((!candidate_no,Ast.Ident("__paramod",None)),s))
1672 (auto_eq_check cache.unit_eq status) in
1674 if (l1 <> []) then []
1675 else applicative_case depth signature status flags gty cache
1676 (* fast paramodulation *)
1678 (* states in l1 have have an empty set of subgoals: no point to sort them *)
1679 l1 @ (sort_new_elems (l@l2)), cache
1682 let pp_goal = function
1683 | (_,Continuationals.Stack.Open i)
1684 | (_,Continuationals.Stack.Closed i) -> string_of_int i
1687 let pp_goals status l =
1691 let gty = get_goalty status i in
1692 NTacStatus.ppterm status gty)
1699 let compare = Pervasives.compare
1703 module MS = HTopoSort.Make(M)
1706 let sort_tac status =
1708 match status#stack with
1709 | [] -> assert false
1710 | (goals, t, k, tag) :: s ->
1711 let g = head_goals status#stack in
1713 (List.rev (MS.topological_sort g (deps status))) in
1714 debug_print (lazy ("old g = " ^
1715 String.concat "," (List.map string_of_int g)));
1716 debug_print (lazy ("sorted goals = " ^
1717 String.concat "," (List.map string_of_int sortedg)));
1718 let is_it i = function
1719 | (_,Continuationals.Stack.Open j )
1720 | (_,Continuationals.Stack.Closed j ) -> i = j
1723 List.map (fun i -> List.find (is_it i) goals) sortedg
1725 (sorted_goals, t, k, tag) :: s
1727 status#set_stack gstatus
1730 let clean_up_tac status =
1732 match status#stack with
1733 | [] -> assert false
1734 | (g, t, k, tag) :: s ->
1735 let is_open = function
1736 | (_,Continuationals.Stack.Open _) -> true
1737 | (_,Continuationals.Stack.Closed _) -> false
1739 let g' = List.filter is_open g in
1740 (g', t, k, tag) :: s
1742 status#set_stack gstatus
1745 let focus_tac focus status =
1747 match status#stack with
1748 | [] -> assert false
1749 | (g, t, k, tag) :: s ->
1750 let in_focus = function
1751 | (_,Continuationals.Stack.Open i)
1752 | (_,Continuationals.Stack.Closed i) -> List.mem i focus
1754 let focus,others = List.partition in_focus g
1756 (* we need to mark it as a BranchTag, otherwise cannot merge later *)
1757 (focus,[],[],`BranchTag) :: (others, t, k, tag) :: s
1759 status#set_stack gstatus
1762 let rec auto_clusters ?(top=false)
1763 flags signature cache depth status : unit =
1764 debug_print ~depth (lazy "entering auto clusters");
1765 (* ignore(Unix.select [] [] [] 0.01); *)
1766 let status = clean_up_tac status in
1767 let goals = head_goals status#stack in
1768 if goals = [] then raise (Proved status)
1769 else if depth = flags.maxdepth then raise (Gaveup IntSet.empty)
1770 else if List.length goals < 2 then
1771 auto_main flags signature cache depth status
1773 debug_print ~depth (lazy ("goals = " ^
1774 String.concat "," (List.map string_of_int goals)));
1775 let classes = HExtlib.clusters (deps status) goals in
1776 let classes = if top then List.rev classes else classes in
1782 ("cluster:" ^ String.concat "," (List.map string_of_int l)))
1786 (fun (status,b) gl ->
1787 let status = focus_tac gl status in
1789 debug_print ~depth (lazy ("focusing on" ^
1790 String.concat "," (List.map string_of_int gl)));
1791 auto_main flags signature cache depth status; assert false
1793 | Proved(status) -> (NTactics.merge_tac status,true)
1794 | Gaveup _ when top -> (NTactics.merge_tac status,b)
1796 (status,false) classes
1797 in if b then raise (Proved status) else raise (Gaveup IntSet.empty)
1801 (* the goals returned upon failure are an unsatisfiable subset
1802 of the initial head goals in the stack *)
1804 auto_main flags signature (cache:cache) depth status: unit =
1805 debug_print ~depth (lazy "entering auto main");
1806 (* ignore(Unix.select [] [] [] 0.01); *)
1807 let status = sort_tac (clean_up_tac status) in
1808 let goals = head_goals status#stack in
1810 | [] -> raise (Proved status)
1812 let ng = List.length goals in
1813 if ng > flags.maxwidth then
1814 (debug_print (lazy "FAIL WIDTH"); raise (Gaveup IntSet.empty))
1815 else let branch = ng>1 in
1816 if depth = flags.maxdepth then raise (Gaveup IntSet.empty)
1819 if branch then NTactics.branch_tac status
1821 let status, cache = intros ~depth status cache in
1822 let g,gctx, gty = current_goal status in
1823 let ctx,ty = close status g in
1824 let closegty = mk_cic_term ctx ty in
1825 let status, gty = apply_subst status gctx gty in
1826 debug_print ~depth (lazy("Attacking goal " ^ (string_of_int g) ^" : "^ppterm status gty));
1827 if is_subsumed depth status closegty cache.under_inspection then
1828 (debug_print (lazy "SUBSUMED");
1829 raise (Gaveup IntSet.add g IntSet.empty))
1832 {flags with last = flags.last && (not branch)} in
1833 let alternatives, cache =
1834 do_something signature do_flags status g depth gty cache in
1836 let under_inspection =
1837 add_to_th closegty cache.under_inspection closegty in
1838 {cache with under_inspection = under_inspection} in
1841 (* the underscore information does not need to be returned
1843 (fun unsat ((_,t),status) ->
1844 let depth',looping_cache =
1845 if t=Ast.Ident("__whd",None) then depth,cache
1846 else depth+1, loop_cache in
1847 debug_print (~depth:depth')
1848 (lazy ("Case: " ^ CicNotationPp.pp_term t));
1850 {flags with maxwidth = flags.maxwidth - ng +1} in
1853 {flags' with last = flags'.last && (not branch)} in
1855 (lazy ("auto last: " ^ (string_of_bool flags'.last)));
1856 try auto_clusters flags' signature loop_cache
1857 depth' status; unsat
1860 debug_print (~depth:depth') (lazy "proved");
1862 let status = NTactics.merge_tac status
1864 (* old cache, here *)
1866 {flags with maxwidth = flags.maxwidth - 1} in
1867 try auto_clusters flags signature cache
1868 depth status; assert false
1871 (lazy ("Unsat1 at depth " ^ (string_of_int depth)
1873 (pp_goals status (IntSet.elements f))));
1874 (* TODO: cache failures *)
1875 IntSet.union f unsat
1876 else raise (Proved status)
1878 debug_print (~depth:depth')
1879 (lazy ("Unsat2 at depth " ^ (string_of_int depth')
1881 (pp_goals status (IntSet.elements f))));
1882 (* TODO: cache local failures *)
1884 IntSet.empty alternatives
1886 raise (Gaveup IntSet.add orig unsat)
1889 let int name l def =
1890 try int_of_string (List.assoc name l)
1891 with Failure _ | Not_found -> def
1894 let auto_tac ~params:(_univ,flags) status =
1895 let oldstatus = status in
1896 let status = (status:> NTacStatus.tac_status) in
1897 let goals = head_goals status#stack in
1898 let status, facts = mk_th_cache status goals in
1899 let unit_eq = index_local_equations status#eq_cache status in
1900 let cache = init_cache ~facts ~unit_eq () in
1901 (* pp_th status facts; *)
1903 NDiscriminationTree.DiscriminationTree.iter status#auto_cache (fun p t ->
1905 NDiscriminationTree.NCicIndexable.string_of_path p ^ " |--> " ^
1906 String.concat "\n " (List.map (
1907 NCicPp.ppterm ~metasenv:[] ~context:[] ~subst:[])
1908 (NDiscriminationTree.TermSet.elements t))
1911 let depth = int "depth" flags 3 in
1912 let size = int "size" flags 10 in
1913 let width = int "width" flags 4 (* (3+List.length goals)*) in
1915 let goals = List.map (fun i -> (i,P)) goals in
1916 let signature = () in
1922 timeout = Unix.gettimeofday() +. 3000.;
1925 let initial_time = Unix.gettimeofday() in
1930 ("TIME ELAPSED:"^string_of_float(Unix.gettimeofday()-.initial_time)));
1932 ("Applicative nodes:"^string_of_int !app_counter));
1933 raise (Error (lazy "auto gave up", None)))
1935 let _ = debug_print (lazy("\n\nRound "^string_of_int x^"\n")) in
1936 let flags = { flags with maxdepth = x }
1938 try auto_clusters (~top:true) flags signature cache 0 status;assert false
1940 | Gaveup _ -> up_to (x+1) y
1942 debug_print (lazy ("proved at depth " ^ string_of_int x));
1945 | (g,t,k,f) :: rest -> (filter_open g,t,k,f):: rest
1948 let s = s#set_stack stack in
1949 oldstatus#set_status s
1951 let s = up_to depth depth in
1953 ("TIME ELAPSED:"^string_of_float(Unix.gettimeofday()-.initial_time)));
1955 ("Applicative nodes:"^string_of_int !app_counter));