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 print ?(depth=0) s =
16 prerr_endline (String.make depth '\t'^Lazy.force s)
17 let debug_print ?(depth=0) s =
18 if !debug then print ~depth s else ()
20 let debug_do f = if !debug then f () else ()
22 open Continuationals.Stack
24 module Ast = CicNotationPt
25 let app_counter = ref 0
27 (* ======================= utility functions ========================= *)
28 module IntSet = Set.Make(struct type t = int let compare = compare end)
30 let get_sgoalty status g =
31 let _,_,metasenv,subst,_ = status#obj in
33 let _, ctx, ty = NCicUtils.lookup_meta g metasenv in
34 let ty = NCicUntrusted.apply_subst subst ctx ty in
35 let ctx = NCicUntrusted.apply_subst_context
36 ~fix_projections:true subst ctx
38 NTacStatus.mk_cic_term ctx ty
39 with NCicUtils.Meta_not_found _ as exn -> fail ~exn (lazy "get_sgoalty")
43 let gty = get_sgoalty status g in
44 metas_of_term status gty
47 let menv_closure status gl =
48 let rec closure acc = function
50 | x::l when IntSet.mem x acc -> closure acc l
51 | x::l -> closure (IntSet.add x acc) (deps status x @ l)
52 in closure IntSet.empty gl
55 (* we call a "fact" an object whose hypothesis occur in the goal
56 or in types of goal-variables *)
57 let is_a_fact status ty =
58 let status, ty, metas = saturate ~delta:0 status ty in
59 debug_print (lazy ("saturated ty :" ^ (ppterm status ty)));
60 let g_metas = metas_of_term status ty in
61 let clos = menv_closure status g_metas in
62 (* let _,_,metasenv,_,_ = status#obj in *)
66 let _, m = term_of_cic_term status m (ctx_of m) in
68 | NCic.Meta(i,_) -> IntSet.add i acc
71 in IntSet.subset menv clos;;
73 let is_a_fact_obj s uri =
74 let obj = NCicEnvironment.get_checked_obj uri in
76 | (_,_,[],[],NCic.Constant(_,_,Some(t),ty,_)) ->
77 is_a_fact s (mk_cic_term [] ty)
78 (* aggiungere i costruttori *)
81 let is_a_fact_ast status subst metasenv ctx cand =
83 (lazy ("------- checking " ^ CicNotationPp.pp_term cand));
84 let status, t = disambiguate status ctx ("",0,cand) None in
85 let status,t = term_of_cic_term status t ctx in
86 let ty = NCicTypeChecker.typeof subst metasenv ctx t in
87 is_a_fact status (mk_cic_term ctx ty)
89 let current_goal status =
90 let open_goals = head_goals status#stack in
91 assert (List.length open_goals = 1);
92 let open_goal = List.hd open_goals in
93 let gty = get_goalty status open_goal in
94 let ctx = ctx_of gty in
98 (* =============================== paramod =========================== *)
99 let solve fast status eq_cache goal =
101 if fast then NCicParamod.fast_eq_check
102 else NCicParamod.paramod in
103 let n,h,metasenv,subst,o = status#obj in
104 let gname, ctx, gty = List.assoc goal metasenv in
105 let gty = NCicUntrusted.apply_subst subst ctx gty in
106 let build_status (pt, _, metasenv, subst) =
108 debug_print (lazy ("refining: "^(NCicPp.ppterm ctx subst metasenv pt)));
109 let stamp = Unix.gettimeofday () in
110 let metasenv, subst, pt, pty =
111 NCicRefiner.typeof status
112 (* (status#set_coerc_db NCicCoercion.empty_db) *)
113 metasenv subst ctx pt None in
114 debug_print (lazy ("refined: "^(NCicPp.ppterm ctx subst metasenv pt)));
115 debug_print (lazy ("synt: "^(NCicPp.ppterm ctx subst metasenv pty)));
116 let metasenv, subst =
117 NCicUnification.unify status metasenv subst ctx gty pty
118 (* the previous code is much less expensive than directly refining
119 pt with expected type pty
121 prerr_endline ("exp: "^(NCicPp.ppterm ctx subst metasenv gty));
123 (status#set_coerc_db NCicCoercion.empty_db)
124 metasenv subst ctx pt (Some gty) *)
126 debug_print (lazy (Printf.sprintf "Refined in %fs"
127 (Unix.gettimeofday() -. stamp)));
128 let status = status#set_obj (n,h,metasenv,subst,o) in
129 let metasenv = List.filter (fun j,_ -> j <> goal) metasenv in
130 let subst = (goal,(gname,ctx,pt,pty)) :: subst in
131 Some (status#set_obj (n,h,metasenv,subst,o))
133 NCicRefiner.RefineFailure msg
134 | NCicRefiner.Uncertain msg ->
135 debug_print (lazy ("WARNING: refining in fast_eq_check failed" ^
136 snd (Lazy.force msg))); None
137 | NCicRefiner.AssertFailure msg ->
138 debug_print (lazy ("WARNING: refining in fast_eq_check failed" ^
139 Lazy.force msg)); None
142 HExtlib.filter_map build_status
143 (f status metasenv subst ctx eq_cache (NCic.Rel ~-1,gty))
146 let fast_eq_check eq_cache status goal =
147 match solve true status eq_cache goal with
148 | [] -> raise (Error (lazy "no proof found",None))
152 let dist_fast_eq_check eq_cache s =
153 NTactics.distribute_tac (fast_eq_check eq_cache) s
156 let auto_eq_check eq_cache status =
158 let s = dist_fast_eq_check eq_cache status in
164 (* warning: ctx is supposed to be already instantiated w.r.t subst *)
165 let index_local_equations eq_cache status =
166 debug_print (lazy "indexing equations");
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 | NReference.Fix (_,_,h))))
1304 | NCic.Appl (NCic.Const(NReference.Ref(_,(NReference.Def h | NReference.Fix (_,_,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 let status, keys = keys_of_term status t in
1327 debug_print(lazy("indexing: "^ppterm status t ^ ": " ^ string_of_int (List.length keys)));
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 rm_from_th t c ty =
1355 let key_c = ctx_of t in
1356 if not (List.mem_assq key_c c) then assert false
1358 let rec replace = function
1360 | (x, idx) :: tl when x == key_c ->
1361 (x, InvRelDiscriminationTree.remove_index idx ty t) :: tl
1362 | x :: tl -> x :: replace tl
1367 let pp_idx status idx =
1368 InvRelDiscriminationTree.iter idx
1370 debug_print(lazy("K: " ^ NCicInverseRelIndexable.string_of_path k));
1372 (fun t -> debug_print(lazy("\t"^ppterm status t)))
1379 debug_print(lazy( "-----------------------------------------------"));
1380 debug_print(lazy( (NCicPp.ppcontext ~metasenv:[] ~subst:[] ctx)));
1381 debug_print(lazy( "||====> "));
1385 let search_in_th gty th =
1386 let c = ctx_of gty in
1387 let rec aux acc = function
1388 | [] -> (* Ncic_termSet.elements *) acc
1391 let idx = List.assq k th in
1392 let acc = Ncic_termSet.union acc
1393 (InvRelDiscriminationTree.retrieve_unifiables idx gty)
1396 with Not_found -> aux acc tl
1398 aux Ncic_termSet.empty c
1402 do_types : bool; (* solve goals in Type *)
1403 last : bool; (* last goal: take first solution only *)
1411 {facts : th_cache; (* positive results *)
1412 under_inspection : cic_term list * th_cache; (* to prune looping *)
1413 unit_eq : NCicParamod.state
1417 type goal = int * sort (* goal, depth, sort *)
1418 type fail = goal * cic_term
1419 type candidate = int * Ast.term (* unique candidate number, candidate *)
1421 exception Gaveup of IntSet.t (* a sublist of unprovable conjunctive
1422 atoms of the input goals *)
1423 exception Proved of NTacStatus.tac_status
1425 let height_of_ref (NReference.Ref (uri, x)) =
1430 | NReference.CoFix _ ->
1431 let _,height,_,_,_ = NCicEnvironment.get_checked_obj uri in
1433 | NReference.Def h -> h
1434 | NReference.Fix (_,_,h) -> h
1437 let fast_height_of_term t =
1441 NCic.Meta (_,(_,NCic.Ctx l)) -> List.iter aux l
1445 | NCic.Implicit _ -> assert false
1446 | NCic.Const nref as t ->
1448 prerr_endline (NCicPp.ppterm ~metasenv:[] ~subst:[]
1449 ~context:[] t ^ ":" ^ string_of_int (height_of_ref nref));
1451 h := max !h (height_of_ref nref)
1452 | NCic.Prod (_,t1,t2)
1453 | NCic.Lambda (_,t1,t2) -> aux t1; aux t2
1454 | NCic.LetIn (_,s,ty,t) -> aux s; aux ty; aux t
1455 | NCic.Appl l -> List.iter aux l
1456 | NCic.Match (_,outty,t,pl) -> aux outty; aux t; List.iter aux pl
1461 let height_of_goals status =
1462 let open_goals = head_goals status#stack in
1463 assert (List.length open_goals > 0);
1467 let ty = get_goalty status open_goal in
1468 let context = ctx_of ty in
1469 let _, ty = term_of_cic_term status ty (ctx_of ty) in
1470 h := max !h (fast_height_of_term ty);
1473 | _, NCic.Decl ty -> h := max !h (fast_height_of_term ty)
1474 | _, NCic.Def (bo,ty) ->
1475 h := max !h (fast_height_of_term ty);
1476 h := max !h (fast_height_of_term bo);
1480 debug_print (lazy ("altezza sequente: " ^ string_of_int !h));
1484 (* let close_failures _ c = c;; *)
1485 (* let prunable _ _ _ = false;; *)
1486 (* let cache_examine cache gty = `Notfound;; *)
1487 (* let put_in_subst s _ _ _ = s;; *)
1488 (* let add_to_cache_and_del_from_orlist_if_green_cut _ _ c _ _ o f _ = c, o, f, false ;; *)
1489 (* let cache_add_underinspection c _ _ = c;; *)
1491 let init_cache ?(facts=[]) ?(under_inspection=[],[])
1492 ?(unit_eq=NCicParamod.empty_state) _ =
1494 under_inspection = under_inspection;
1498 let only signature _context candidate =
1499 (* TASSI: nel trie ci mettiamo solo il body, non il ty *)
1501 NCicTypeChecker.typeof ~subst:[] ~metasenv:[] [] candidate
1503 let height = fast_height_of_term candidate_ty in
1504 let rc = signature >= height in
1506 debug_print (lazy ("Filtro: " ^ NCicPp.ppterm ~context:[] ~subst:[]
1507 ~metasenv:[] candidate ^ ": " ^ string_of_int height))
1509 debug_print (lazy ("Tengo: " ^ NCicPp.ppterm ~context:[] ~subst:[]
1510 ~metasenv:[] candidate ^ ": " ^ string_of_int height));
1515 let candidate_no = ref 0;;
1517 let openg_no status = List.length (head_goals status#stack)
1519 let sort_new_elems l =
1520 List.sort (fun (_,s1) (_,s2) -> openg_no s1 - openg_no s2) l
1522 let try_candidate ?(smart=0) flags depth status eq_cache t =
1524 debug_print ~depth (lazy ("------------ try " ^ CicNotationPp.pp_term t));
1526 if smart= 0 then NTactics.apply_tac ("",0,t) status
1527 else if smart = 1 then smart_apply_auto ("",0,t) eq_cache status
1528 else (* smart = 2: both *)
1529 try NTactics.apply_tac ("",0,t) status
1531 smart_apply_auto ("",0,t) eq_cache status in
1532 let og_no = openg_no status in
1533 if (* og_no > flags.maxwidth || *)
1534 ((depth + 1) = flags.maxdepth && og_no <> 0) then
1535 (debug_print ~depth (lazy "pruned immediately"); None)
1538 Some ((!candidate_no,t),status))
1539 with Error (msg,exn) -> debug_print ~depth (lazy "failed"); None
1542 let get_candidates ?(smart=true) status cache signature gty =
1543 let universe = status#auto_cache in
1544 let context = ctx_of gty in
1546 let _status, t = term_of_cic_term status t context
1548 let c_ast = function
1549 | NCic.Const r -> Ast.NRef r | _ -> assert false in
1550 let _, raw_gty = term_of_cic_term status gty context in
1551 let cands = NDiscriminationTree.DiscriminationTree.retrieve_unifiables
1553 let local_cands = search_in_th gty cache in
1554 debug_print (lazy ("candidates for" ^ NTacStatus.ppterm status gty));
1555 debug_print (lazy ("local cands = " ^ (string_of_int (List.length (Ncic_termSet.elements local_cands)))));
1556 let together global local =
1558 (List.filter (only signature context)
1559 (NDiscriminationTree.TermSet.elements global)) @
1560 List.map t_ast (Ncic_termSet.elements local) in
1561 let candidates = together cands local_cands in
1562 let smart_candidates =
1565 | NCic.Appl (hd::tl) ->
1567 NCic.Appl (hd:: HExtlib.mk_list(NCic.Meta (0,(0,NCic.Irl 0)))
1568 (List.length tl)) in
1570 NDiscriminationTree.DiscriminationTree.retrieve_unifiables
1571 universe weak_gty in
1573 NDiscriminationTree.TermSet.diff more_cands cands in
1574 let cic_weak_gty = mk_cic_term context weak_gty in
1575 let more_local_cands = search_in_th cic_weak_gty cache in
1576 let smart_local_cands =
1577 Ncic_termSet.diff more_local_cands local_cands in
1578 together smart_cands smart_local_cands
1582 candidates, smart_candidates
1585 let applicative_case depth signature status flags gty (cache:cache) =
1586 app_counter:= !app_counter+1;
1587 let _,_,metasenv,subst,_ = status#obj in
1588 let context = ctx_of gty in
1589 let tcache = cache.facts in
1591 let status, t = term_of_cic_term status gty context in
1592 NCicParamod.is_equation metasenv subst context t
1594 debug_print(lazy (string_of_bool is_eq));
1595 let candidates, smart_candidates =
1596 get_candidates ~smart:(not is_eq) status tcache signature gty in
1598 (lazy ("candidates: " ^ string_of_int (List.length candidates)));
1600 (lazy ("smart candidates: " ^
1601 string_of_int (List.length smart_candidates)));
1604 let smart_candidates = [] in *)
1605 let sm = if is_eq then 0 else 2 in
1606 let maxd = ((depth + 1) = flags.maxdepth) in
1607 let only_one = flags.last && maxd in
1608 debug_print (lazy ("only_one: " ^ (string_of_bool only_one)));
1609 debug_print (lazy ("maxd: " ^ (string_of_bool maxd)));
1613 if (only_one && (elems <> [])) then elems
1615 if (maxd && not(is_a_fact_ast status subst metasenv context cand))
1616 then (debug_print (lazy "pruned: not a fact"); elems)
1618 match try_candidate (~smart:sm)
1619 flags depth status cache.unit_eq cand with
1621 | Some x -> x::elems)
1625 if only_one && elems <> [] then elems
1629 if (only_one && (elems <> [])) then elems
1631 if (maxd && not(is_a_fact_ast status subst metasenv context cand))
1632 then (debug_print (lazy "pruned: not a fact"); elems)
1634 match try_candidate (~smart:1)
1635 flags depth status cache.unit_eq cand with
1637 | Some x -> x::elems)
1646 (* gty is supposed to be meta-closed *)
1647 let is_subsumed depth status gty cache =
1648 if cache=[] then false else (
1649 debug_print ~depth (lazy("Subsuming " ^ (ppterm status gty)));
1650 let n,h,metasenv,subst,obj = status#obj in
1651 let ctx = ctx_of gty in
1652 let _ , target = term_of_cic_term status gty ctx in
1653 let target = NCicSubstitution.lift 1 target in
1654 (* candidates must only be searched w.r.t the given context *)
1657 let idx = List.assq ctx cache in
1658 Ncic_termSet.elements
1659 (InvRelDiscriminationTree.retrieve_generalizations idx gty)
1660 with Not_found -> []
1663 (lazy ("failure candidates: " ^ string_of_int (List.length candidates)));
1667 let _ , source = term_of_cic_term status t ctx in
1669 NCic.Prod("foo",source,target) in
1670 let metasenv,j,_,_ =
1671 NCicMetaSubst.mk_meta
1672 metasenv ctx ~with_type:implication `IsType in
1673 let status = status#set_obj (n,h,metasenv,subst,obj) in
1674 let status = status#set_stack [([1,Open j],[],[],`NoTag)] in
1676 let status = NTactics.intro_tac "foo" status in
1678 NTactics.apply_tac ("",0,Ast.NCic (NCic.Rel 1)) status
1680 if (head_goals status#stack = []) then raise Found
1685 with Found -> debug_print ~depth (lazy "success");true)
1688 let rec guess_name name ctx =
1689 if name = "_" then guess_name "auto" ctx else
1690 if not (List.mem_assoc name ctx) then name else
1691 guess_name (name^"'") ctx
1694 let is_prod status =
1695 let _, ctx, gty = current_goal status in
1696 let _, raw_gty = term_of_cic_term status gty ctx in
1698 | NCic.Prod (name,_,_) -> Some (guess_name name ctx)
1701 let intro ~depth status facts name =
1702 let status = NTactics.intro_tac name status in
1703 let _, ctx, ngty = current_goal status in
1704 let t = mk_cic_term ctx (NCic.Rel 1) in
1705 let status, keys = keys_of_term status t in
1706 let facts = List.fold_left (add_to_th t) facts keys in
1707 debug_print ~depth (lazy ("intro: "^ name));
1708 (* unprovability is not stable w.r.t introduction *)
1712 let rec intros_facts ~depth status facts =
1713 match is_prod status with
1716 intro ~depth status facts name
1717 in intros_facts ~depth status facts
1718 | _ -> status, facts
1721 let rec intros ~depth status (cache:cache) =
1722 match is_prod status with
1725 intros_facts ~depth status cache.facts
1727 (* we reindex the equation from scratch *)
1729 index_local_equations status#eq_cache status in
1730 status, init_cache ~facts ~unit_eq ()
1731 | _ -> status, cache
1734 let reduce ~depth status g =
1735 let n,h,metasenv,subst,o = status#obj in
1736 let attr, ctx, ty = NCicUtils.lookup_meta g metasenv in
1737 let ty = NCicUntrusted.apply_subst subst ctx ty in
1738 let ty' = NCicReduction.whd ~subst ctx ty in
1742 (lazy ("reduced to: "^ NCicPp.ppterm ctx subst metasenv ty'));
1744 (g,(attr,ctx,ty'))::(List.filter (fun (i,_) -> i<>g) metasenv)
1746 let status = status#set_obj (n,h,metasenv,subst,o) in
1747 (* we merge to gain a depth level; the previous goal level should
1749 let status = NTactics.merge_tac status in
1751 [(!candidate_no,Ast.Ident("__whd",None)),status])
1754 let do_something signature flags status g depth gty cache =
1756 let l = reduce ~depth status g in
1757 (* backward aplications *)
1762 ((!candidate_no,Ast.Ident("__paramod",None)),s))
1763 (auto_eq_check cache.unit_eq status)
1766 (* if (l1 <> []) then [] else *)
1767 applicative_case depth signature status flags gty cache
1768 (* fast paramodulation *)
1770 (* states in l1 have have an empty set of subgoals: no point to sort them *)
1772 (lazy ("alternatives = " ^ (string_of_int (List.length (l1@l@l2)))));
1773 l1 @ (sort_new_elems (l@l2)), cache
1776 let pp_goal = function
1777 | (_,Continuationals.Stack.Open i)
1778 | (_,Continuationals.Stack.Closed i) -> string_of_int i
1781 let pp_goals status l =
1785 let gty = get_goalty status i in
1786 NTacStatus.ppterm status gty)
1793 let compare = Pervasives.compare
1797 module MS = HTopoSort.Make(M)
1800 let sort_tac status =
1802 match status#stack with
1803 | [] -> assert false
1804 | (goals, t, k, tag) :: s ->
1805 let g = head_goals status#stack in
1807 (List.rev (MS.topological_sort g (deps status))) in
1808 debug_print (lazy ("old g = " ^
1809 String.concat "," (List.map string_of_int g)));
1810 debug_print (lazy ("sorted goals = " ^
1811 String.concat "," (List.map string_of_int sortedg)));
1812 let is_it i = function
1813 | (_,Continuationals.Stack.Open j )
1814 | (_,Continuationals.Stack.Closed j ) -> i = j
1817 List.map (fun i -> List.find (is_it i) goals) sortedg
1819 (sorted_goals, t, k, tag) :: s
1821 status#set_stack gstatus
1824 let clean_up_tac status =
1826 match status#stack with
1827 | [] -> assert false
1828 | (g, t, k, tag) :: s ->
1829 let is_open = function
1830 | (_,Continuationals.Stack.Open _) -> true
1831 | (_,Continuationals.Stack.Closed _) -> false
1833 let g' = List.filter is_open g in
1834 (g', t, k, tag) :: s
1836 status#set_stack gstatus
1839 let focus_tac focus status =
1841 match status#stack with
1842 | [] -> assert false
1843 | (g, t, k, tag) :: s ->
1844 let in_focus = function
1845 | (_,Continuationals.Stack.Open i)
1846 | (_,Continuationals.Stack.Closed i) -> List.mem i focus
1848 let focus,others = List.partition in_focus g
1850 (* we need to mark it as a BranchTag, otherwise cannot merge later *)
1851 (focus,[],[],`BranchTag) :: (others, t, k, tag) :: s
1853 status#set_stack gstatus
1856 let deep_focus_tac level focus status =
1857 let in_focus = function
1858 | (_,Continuationals.Stack.Open i)
1859 | (_,Continuationals.Stack.Closed i) -> List.mem i focus
1861 let rec slice level gs =
1862 if level = 0 then [],[],gs else
1864 | [] -> assert false
1865 | (g, t, k, tag) :: s ->
1866 let f,o,gs = slice (level-1) s in
1867 let f1,o1 = List.partition in_focus g
1869 (* we need to mark it as a BranchTag, otherwise cannot merge later *)
1870 (f1,[],[],`BranchTag)::f, (o1, t, k, tag)::o, gs
1873 let f,o,s = slice level status#stack in f@o@s
1875 status#set_stack gstatus
1878 let open_goals level status =
1879 let rec aux level gs =
1880 if level = 0 then []
1882 | [] -> assert false
1883 | _ :: s -> head_goals gs @ aux (level-1) s
1885 aux level status#stack
1888 let rec auto_clusters ?(top=false)
1889 flags signature cache depth status : unit =
1890 debug_print ~depth (lazy ("entering auto clusters at depth " ^
1891 (string_of_int depth)));
1892 (* ignore(Unix.select [] [] [] 0.01); *)
1893 let status = clean_up_tac status in
1894 let goals = head_goals status#stack in
1896 if depth = 0 then raise (Proved status)
1898 let status = NTactics.merge_tac status in
1899 auto_clusters flags signature (cache:cache) (depth-1) status
1900 else if List.length goals < 2 then
1901 auto_main flags signature cache depth status
1903 let all_goals = open_goals (depth+1) status in
1904 debug_print ~depth (lazy ("goals = " ^
1905 String.concat "," (List.map string_of_int all_goals)));
1906 let classes = HExtlib.clusters (deps status) all_goals in
1907 let classes = if top then List.rev classes else classes in
1913 ("cluster:" ^ String.concat "," (List.map string_of_int l)))
1917 (fun (status,b) gl ->
1918 let lold = List.length status#stack in
1919 debug_print ~depth (lazy ("stack length = " ^
1920 (string_of_int lold)));
1921 let fstatus = deep_focus_tac (depth+1) gl status in
1923 debug_print ~depth (lazy ("focusing on" ^
1924 String.concat "," (List.map string_of_int gl)));
1925 auto_main flags signature cache depth fstatus; assert false
1928 let status = NTactics.merge_tac status in
1929 let lnew = List.length status#stack in
1930 assert (lold = lnew);
1932 | Gaveup _ when top -> (status,b)
1934 (status,false) classes
1936 let rec final_merge n s =
1937 if n = 0 then s else final_merge (n-1) (NTactics.merge_tac s)
1938 in let status = final_merge depth status
1939 in if b then raise (Proved status) else raise (Gaveup IntSet.empty)
1943 (* BRAND NEW VERSION *)
1944 auto_main flags signature (cache:cache) depth status: unit =
1945 debug_print ~depth (lazy "entering auto main");
1946 debug_print ~depth (lazy ("stack length = " ^
1947 (string_of_int (List.length status#stack))));
1948 (* ignore(Unix.select [] [] [] 0.01); *)
1949 let status = sort_tac (clean_up_tac status) in
1950 let goals = head_goals status#stack in
1952 | [] when depth = 0 -> raise (Proved status)
1954 let status = NTactics.merge_tac status in
1956 let l,tree = cache.under_inspection in
1958 | [] -> assert false
1959 | a::tl -> let tree = rm_from_th a tree a in
1960 {cache with under_inspection = tl,tree}
1962 auto_clusters flags signature (cache:cache) (depth-1) status
1964 let ng = List.length goals in
1965 if ng > flags.maxwidth then
1966 (print (lazy "FAIL WIDTH"); raise (Gaveup IntSet.empty))
1967 else if depth = flags.maxdepth then raise (Gaveup IntSet.empty)
1969 let status = NTactics.branch_tac ~force:true status in
1970 let status, cache = intros ~depth status cache in
1971 let g,gctx, gty = current_goal status in
1972 let ctx,ty = close status g in
1973 let closegty = mk_cic_term ctx ty in
1974 let status, gty = apply_subst status gctx gty in
1975 debug_print ~depth (lazy("Attacking goal " ^ (string_of_int g) ^" : "^ppterm status gty));
1976 if is_subsumed depth status closegty (snd cache.under_inspection) then
1977 (debug_print ~depth (lazy "SUBSUMED");
1978 raise (Gaveup IntSet.add g IntSet.empty))
1981 {flags with last = flags.last && ng=1} in
1982 let alternatives, cache =
1983 do_something signature do_flags status g depth gty cache in
1985 let l,tree = cache.under_inspection in
1986 let l,tree = closegty::l, add_to_th closegty tree closegty in
1987 {cache with under_inspection = l,tree} in
1989 (fun ((_,t),status) ->
1991 (lazy("(re)considering goal " ^
1992 (string_of_int g) ^" : "^ppterm status gty));
1993 debug_print (~depth:depth)
1994 (lazy ("Case: " ^ CicNotationPp.pp_term t));
1996 if t=Ast.Ident("__whd",None) then depth, cache
1997 else depth+1,loop_cache in
1999 auto_clusters flags signature (cache:cache) depth status
2001 debug_print ~depth (lazy "Failed");())
2003 raise (Gaveup IntSet.empty)
2006 let int name l def =
2007 try int_of_string (List.assoc name l)
2008 with Failure _ | Not_found -> def
2011 let auto_tac ~params:(_univ,flags) status =
2012 let oldstatus = status in
2013 let status = (status:> NTacStatus.tac_status) in
2014 let goals = head_goals status#stack in
2015 let status, facts = mk_th_cache status goals in
2016 let unit_eq = index_local_equations status#eq_cache status in
2017 let cache = init_cache ~facts ~unit_eq () in
2018 (* pp_th status facts; *)
2020 NDiscriminationTree.DiscriminationTree.iter status#auto_cache (fun p t ->
2022 NDiscriminationTree.NCicIndexable.string_of_path p ^ " |--> " ^
2023 String.concat "\n " (List.map (
2024 NCicPp.ppterm ~metasenv:[] ~context:[] ~subst:[])
2025 (NDiscriminationTree.TermSet.elements t))
2028 let depth = int "depth" flags 3 in
2029 let size = int "size" flags 10 in
2030 let width = int "width" flags 4 (* (3+List.length goals)*) in
2032 (* let goals = List.map (fun i -> (i,P)) goals in *)
2033 let signature = height_of_goals status in
2039 timeout = Unix.gettimeofday() +. 3000.;
2042 let initial_time = Unix.gettimeofday() in
2047 ("TIME ELAPSED:"^string_of_float(Unix.gettimeofday()-.initial_time)));
2049 ("Applicative nodes:"^string_of_int !app_counter));
2050 raise (Error (lazy "auto gave up", None)))
2052 let _ = debug_print (lazy("\n\nRound "^string_of_int x^"\n")) in
2053 let flags = { flags with maxdepth = x }
2055 try auto_clusters (~top:true) flags signature cache 0 status;assert false
2057 try auto_main flags signature cache 0 status;assert false
2060 | Gaveup _ -> up_to (x+1) y
2062 debug_print (lazy ("proved at depth " ^ string_of_int x));
2065 | (g,t,k,f) :: rest -> (filter_open g,t,k,f):: rest
2068 let s = s#set_stack stack in
2069 oldstatus#set_status s
2071 let s = up_to depth depth in
2073 ("TIME ELAPSED:"^string_of_float(Unix.gettimeofday()-.initial_time)));
2075 ("Applicative nodes:"^string_of_int !app_counter));