src/HOL/Tools/res_atp.ML
author paulson
Fri Jul 28 18:36:24 2006 +0200 (2006-07-28)
changeset 20246 fdfe7399e057
parent 20224 9c40a144ee0e
child 20289 ba7a7c56bed5
permissions -rw-r--r--
"all theorems" mode forces definition-expansion off.
signature tidying
     1 (*  Author: Jia Meng, Cambridge University Computer Laboratory, NICTA
     2     ID: $Id$
     3     Copyright 2004 University of Cambridge
     4 
     5 ATPs with TPTP format input.
     6 *)
     7 
     8 signature RES_ATP =
     9 sig
    10   val prover: string ref
    11   val custom_spass: string list ref
    12   val destdir: string ref
    13   val helper_path: string -> string -> string
    14   val problem_name: string ref
    15   val time_limit: int ref
    16    
    17   datatype mode = Auto | Fol | Hol
    18   val linkup_logic_mode : mode ref
    19   val write_subgoal_file: bool -> mode -> Proof.context -> thm list -> thm list -> int -> string
    20   val vampire_time: int ref
    21   val eprover_time: int ref
    22   val spass_time: int ref
    23   val run_vampire: int -> unit
    24   val run_eprover: int -> unit
    25   val run_spass: int -> unit
    26   val vampireLimit: unit -> int
    27   val eproverLimit: unit -> int
    28   val spassLimit: unit -> int
    29   val atp_method: (ProofContext.context -> thm list -> int -> Tactical.tactic) ->
    30 		  Method.src -> ProofContext.context -> Method.method
    31   val cond_rm_tmp: string -> unit
    32   val keep_atp_input: bool ref
    33   val fol_keep_types: bool ref
    34   val hol_full_types: unit -> unit
    35   val hol_partial_types: unit -> unit
    36   val hol_const_types_only: unit -> unit
    37   val hol_no_types: unit -> unit
    38   val hol_typ_level: unit -> ResHolClause.type_level
    39   val include_all: bool ref
    40   val run_relevance_filter: bool ref
    41   val run_blacklist_filter: bool ref
    42   val add_all : unit -> unit
    43   val add_claset : unit -> unit
    44   val add_simpset : unit -> unit
    45   val add_clasimp : unit -> unit
    46   val add_atpset : unit -> unit
    47   val rm_all : unit -> unit
    48   val rm_claset : unit -> unit
    49   val rm_simpset : unit -> unit
    50   val rm_atpset : unit -> unit
    51   val rm_clasimp : unit -> unit
    52 end;
    53 
    54 structure ResAtp : RES_ATP =
    55 struct
    56 
    57 (********************************************************************)
    58 (* some settings for both background automatic ATP calling procedure*)
    59 (* and also explicit ATP invocation methods                         *)
    60 (********************************************************************)
    61 
    62 (*** background linkup ***)
    63 val call_atp = ref false; 
    64 val hook_count = ref 0;
    65 val time_limit = ref 30;
    66 val prover = ref "E";   (* use E as the default prover *)
    67 val custom_spass =   (*specialized options for SPASS*)
    68       ref ["-Auto=0","-FullRed=0","-IORe","-IOFc","-RTaut","-RFSub","-RBSub"];
    69 val destdir = ref "";   (*Empty means write files to /tmp*)
    70 val problem_name = ref "prob";
    71 
    72 (*Return the path to a "helper" like SPASS or tptp2X, first checking that
    73   it exists.  FIXME: modify to use Path primitives and move to some central place.*)  
    74 fun helper_path evar base =
    75   case getenv evar of
    76       "" => error  ("Isabelle environment variable " ^ evar ^ " not defined")
    77     | home => 
    78         let val path = home ^ "/" ^ base
    79         in  if File.exists (File.unpack_platform_path path) then path 
    80 	    else error ("Could not find the file " ^ path)
    81 	end;  
    82 
    83 fun probfile_nosuffix _ = 
    84   if !destdir = "" then File.platform_path (File.tmp_path (Path.basic (!problem_name)))
    85   else if File.exists (File.unpack_platform_path (!destdir))
    86   then !destdir ^ "/" ^ !problem_name
    87   else error ("No such directory: " ^ !destdir);
    88 
    89 fun prob_pathname n = probfile_nosuffix n ^ "_" ^ Int.toString n;
    90 
    91 
    92 (*** ATP methods ***)
    93 val vampire_time = ref 60;
    94 val eprover_time = ref 60;
    95 val spass_time = ref 60;
    96 
    97 fun run_vampire time =  
    98     if (time >0) then vampire_time:= time
    99     else vampire_time:=60;
   100 
   101 fun run_eprover time = 
   102     if (time > 0) then eprover_time:= time
   103     else eprover_time:=60;
   104 
   105 fun run_spass time = 
   106     if (time > 0) then spass_time:=time
   107     else spass_time:=60;
   108 
   109 
   110 fun vampireLimit () = !vampire_time;
   111 fun eproverLimit () = !eprover_time;
   112 fun spassLimit () = !spass_time;
   113 
   114 val keep_atp_input = ref false;
   115 val fol_keep_types = ResClause.keep_types;
   116 val hol_full_types = ResHolClause.full_types;
   117 val hol_partial_types = ResHolClause.partial_types;
   118 val hol_const_types_only = ResHolClause.const_types_only;
   119 val hol_no_types = ResHolClause.no_types;
   120 fun hol_typ_level () = ResHolClause.find_typ_level ();
   121 fun is_typed_hol () = 
   122     let val tp_level = hol_typ_level()
   123     in
   124 	not (tp_level = ResHolClause.T_NONE)
   125     end;
   126 val include_combS = ResHolClause.include_combS;
   127 val include_min_comb = ResHolClause.include_min_comb;
   128 
   129 fun atp_input_file () =
   130     let val file = !problem_name 
   131     in
   132 	if !destdir = "" then File.platform_path (File.tmp_path (Path.basic file))
   133 	else if File.exists (File.unpack_platform_path (!destdir))
   134 	then !destdir ^ "/" ^ file
   135 	else error ("No such directory: " ^ !destdir)
   136     end;
   137 
   138 val include_all = ref false;
   139 val include_simpset = ref false;
   140 val include_claset = ref false; 
   141 val include_atpset = ref true;
   142 
   143 (*Tests show that follow_defs gives VERY poor results with "include_all"*)
   144 fun add_all() = (include_all:=true; ReduceAxiomsN.follow_defs := false);
   145 fun rm_all() = include_all:=false;
   146 
   147 fun add_simpset() = include_simpset:=true;
   148 fun rm_simpset() = include_simpset:=false;
   149 
   150 fun add_claset() = include_claset:=true;
   151 fun rm_claset() = include_claset:=false;
   152 
   153 fun add_clasimp() = (include_simpset:=true;include_claset:=true);
   154 fun rm_clasimp() = (include_simpset:=false;include_claset:=false);
   155 
   156 fun add_atpset() = include_atpset:=true;
   157 fun rm_atpset() = include_atpset:=false;
   158 
   159 
   160 (**** relevance filter ****)
   161 val run_relevance_filter = ref true;
   162 val run_blacklist_filter = ref true;
   163 
   164 (******************************************************************)
   165 (* detect whether a given problem (clauses) is FOL/HOL/HOLC/HOLCS *)
   166 (******************************************************************)
   167 
   168 datatype logic = FOL | HOL | HOLC | HOLCS;
   169 
   170 fun string_of_logic FOL = "FOL"
   171   | string_of_logic HOL = "HOL"
   172   | string_of_logic HOLC = "HOLC"
   173   | string_of_logic HOLCS = "HOLCS";
   174 
   175 
   176 fun is_fol_logic FOL = true
   177   | is_fol_logic  _ = false
   178 
   179 
   180 (*HOLCS will not occur here*)
   181 fun upgrade_lg HOLC _ = HOLC
   182   | upgrade_lg HOL HOLC = HOLC
   183   | upgrade_lg HOL _ = HOL
   184   | upgrade_lg FOL lg = lg; 
   185 
   186 (* check types *)
   187 fun has_bool_hfn (Type("bool",_)) = true
   188   | has_bool_hfn (Type("fun",_)) = true
   189   | has_bool_hfn (Type(_, Ts)) = exists has_bool_hfn Ts
   190   | has_bool_hfn _ = false;
   191 
   192 fun is_hol_fn tp =
   193     let val (targs,tr) = strip_type tp
   194     in
   195 	exists (has_bool_hfn) (tr::targs)
   196     end;
   197 
   198 fun is_hol_pred tp =
   199     let val (targs,tr) = strip_type tp
   200     in
   201 	exists (has_bool_hfn) targs
   202     end;
   203 
   204 exception FN_LG of term;
   205 
   206 fun fn_lg (t as Const(f,tp)) (lg,seen) = 
   207     if is_hol_fn tp then (upgrade_lg HOL lg, t ins seen) else (lg, t ins seen) 
   208   | fn_lg (t as Free(f,tp)) (lg,seen) = 
   209     if is_hol_fn tp then (upgrade_lg HOL lg, t ins seen) else (lg, t ins seen) 
   210   | fn_lg (t as Var(f,tp)) (lg,seen) =
   211     if is_hol_fn tp then (upgrade_lg HOL lg,t ins seen) else (lg,t ins seen)
   212   | fn_lg (t as Abs(_,_,_)) (lg,seen) = (upgrade_lg HOLC lg,t ins seen)
   213   | fn_lg f _ = raise FN_LG(f); 
   214 
   215 
   216 fun term_lg [] (lg,seen) = (lg,seen)
   217   | term_lg (tm::tms) (FOL,seen) =
   218     let val (f,args) = strip_comb tm
   219 	val (lg',seen') = if f mem seen then (FOL,seen) 
   220 			  else fn_lg f (FOL,seen)
   221 	val _ =
   222           if is_fol_logic lg' then ()
   223           else Output.debug ("Found a HOL term: " ^ Display.raw_string_of_term f)
   224 	 in
   225 	     term_lg (args@tms) (lg',seen')
   226     end
   227   | term_lg _ (lg,seen) = (lg,seen)
   228 
   229 exception PRED_LG of term;
   230 
   231 fun pred_lg (t as Const(P,tp)) (lg,seen)= 
   232     if is_hol_pred tp then (upgrade_lg HOL lg, t ins seen) else (lg,t ins seen) 
   233   | pred_lg (t as Free(P,tp)) (lg,seen) =
   234     if is_hol_pred tp then (upgrade_lg HOL lg, t ins seen) else (lg,t ins seen)
   235   | pred_lg (t as Var(_,_)) (lg,seen) = (upgrade_lg HOL lg, t ins seen)
   236   | pred_lg P _ = raise PRED_LG(P);
   237 
   238 
   239 fun lit_lg (Const("Not",_) $ P) (lg,seen) = lit_lg P (lg,seen)
   240   | lit_lg P (lg,seen) =
   241     let val (pred,args) = strip_comb P
   242 	val (lg',seen') = if pred mem seen then (lg,seen) 
   243 			  else pred_lg pred (lg,seen)
   244 	val _ =
   245           if is_fol_logic lg' then ()
   246           else Output.debug ("Found a HOL predicate: " ^ Display.raw_string_of_term pred)
   247     in
   248 	term_lg args (lg',seen')
   249     end;
   250 
   251 fun lits_lg [] (lg,seen) = (lg,seen)
   252   | lits_lg (lit::lits) (FOL,seen) =
   253     let val (lg,seen') = lit_lg lit (FOL,seen)
   254 	val _ =
   255           if is_fol_logic lg then ()
   256           else Output.debug ("Found a HOL literal: " ^ Display.raw_string_of_term lit)
   257     in
   258 	lits_lg lits (lg,seen')
   259     end
   260   | lits_lg lits (lg,seen) = (lg,seen);
   261 
   262 
   263 fun dest_disj_aux (Const ("op |", _) $ t $ t') disjs = 
   264     dest_disj_aux t (dest_disj_aux t' disjs)
   265   | dest_disj_aux t disjs = t::disjs;
   266 
   267 fun dest_disj t = dest_disj_aux t [];
   268 
   269 fun logic_of_clause tm (lg,seen) =
   270     let val tm' = HOLogic.dest_Trueprop tm
   271 	val disjs = dest_disj tm'
   272     in
   273 	lits_lg disjs (lg,seen)
   274     end;
   275 
   276 fun logic_of_clauses [] (lg,seen) = (lg,seen)
   277   | logic_of_clauses (cls::clss) (FOL,seen) =
   278     let val (lg,seen') = logic_of_clause cls (FOL,seen)
   279 	val _ =
   280           if is_fol_logic lg then ()
   281           else Output.debug ("Found a HOL clause: " ^ Display.raw_string_of_term cls)
   282     in
   283 	logic_of_clauses clss (lg,seen')
   284     end
   285   | logic_of_clauses (cls::clss) (lg,seen) = (lg,seen);
   286 
   287 fun problem_logic_goals_aux [] (lg,seen) = lg
   288   | problem_logic_goals_aux (subgoal::subgoals) (lg,seen) = 
   289     problem_logic_goals_aux subgoals (logic_of_clauses subgoal (lg,seen));
   290     
   291 fun problem_logic_goals subgoals = problem_logic_goals_aux subgoals (FOL,[]);
   292 
   293 (***************************************************************)
   294 (* Retrieving and filtering lemmas                             *)
   295 (***************************************************************)
   296 
   297 (*** white list and black list of lemmas ***)
   298 
   299 (*The rule subsetI is frequently omitted by the relevance filter.*)
   300 val whitelist = ref [subsetI]; 
   301 
   302 (*In general, these produce clauses that are prolific (match too many equality or
   303   membership literals) and relate to seldom-used facts. Some duplicate other rules.
   304   FIXME: this blacklist needs to be maintained using theory data and added to using
   305   an attribute.*)
   306 val blacklist = ref
   307   ["Datatype.prod.size",
   308    "Divides.dvd_0_left_iff",
   309    "Finite_Set.card_0_eq",
   310    "Finite_Set.card_infinite",
   311    "Finite_Set.Max_ge",
   312    "Finite_Set.Max_in",
   313    "Finite_Set.Max_le_iff",
   314    "Finite_Set.Max_less_iff",
   315    "Finite_Set.max.f_below_strict_below.below_f_conv", (*duplicates in Orderings.*)
   316    "Finite_Set.max.f_below_strict_below.strict_below_f_conv", (*duplicates in Orderings.*)
   317    "Finite_Set.Min_ge_iff",
   318    "Finite_Set.Min_gr_iff",
   319    "Finite_Set.Min_in",
   320    "Finite_Set.Min_le",
   321    "Finite_Set.min_max.below_inf_sup_Inf_Sup.inf_Sup_absorb", 
   322    "Finite_Set.min_max.below_inf_sup_Inf_Sup.sup_Inf_absorb", 
   323    "Finite_Set.min.f_below_strict_below.below_f_conv",        (*duplicates in Orderings.*)
   324    "Finite_Set.min.f_below_strict_below.strict_below_f_conv", (*duplicates in Orderings.*)
   325    "IntDef.Integ.Abs_Integ_inject",
   326    "IntDef.Integ.Abs_Integ_inverse",
   327    "IntDiv.zdvd_0_left",
   328    "List.append_eq_append_conv",
   329    "List.hd_Cons_tl",   (*Says everything is [] or Cons. Probably prolific.*)
   330    "List.in_listsD",
   331    "List.in_listsI",
   332    "List.lists.Cons",
   333    "List.listsE",
   334    "Nat.less_one", (*not directional? obscure*)
   335    "Nat.not_gr0",
   336    "Nat.one_eq_mult_iff", (*duplicate by symmetry*)
   337    "NatArith.of_nat_0_eq_iff",
   338    "NatArith.of_nat_eq_0_iff",
   339    "NatArith.of_nat_le_0_iff",
   340    "NatSimprocs.divide_le_0_iff_number_of",  (*too many clauses*)
   341    "NatSimprocs.divide_less_0_iff_number_of",
   342    "NatSimprocs.equation_minus_iff_1",  (*not directional*)
   343    "NatSimprocs.equation_minus_iff_number_of", (*not directional*)
   344    "NatSimprocs.le_minus_iff_1", (*not directional*)
   345    "NatSimprocs.le_minus_iff_number_of",  (*not directional*)
   346    "NatSimprocs.less_minus_iff_1", (*not directional*)
   347    "NatSimprocs.less_minus_iff_number_of", (*not directional*)
   348    "NatSimprocs.minus_equation_iff_number_of", (*not directional*)
   349    "NatSimprocs.minus_le_iff_1", (*not directional*)
   350    "NatSimprocs.minus_le_iff_number_of", (*not directional*)
   351    "NatSimprocs.minus_less_iff_1", (*not directional*)
   352    "NatSimprocs.mult_le_cancel_left_number_of", (*excessive case analysis*)
   353    "NatSimprocs.mult_le_cancel_right_number_of", (*excessive case analysis*)
   354    "NatSimprocs.mult_less_cancel_left_number_of", (*excessive case analysis*)
   355    "NatSimprocs.mult_less_cancel_right_number_of", (*excessive case analysis*)
   356    "NatSimprocs.zero_le_divide_iff_number_of", (*excessive case analysis*)
   357    "NatSimprocs.zero_less_divide_iff_number_of",
   358    "OrderedGroup.abs_0_eq", (*duplicate by symmetry*)
   359    "OrderedGroup.diff_eq_0_iff_eq", (*prolific?*)
   360    "OrderedGroup.join_0_eq_0",
   361    "OrderedGroup.meet_0_eq_0",
   362    "OrderedGroup.pprt_eq_0",   (*obscure*)
   363    "OrderedGroup.pprt_eq_id",   (*obscure*)
   364    "OrderedGroup.pprt_mono",   (*obscure*)
   365    "Parity.even_nat_power",   (*obscure, somewhat prolilfic*)
   366    "Parity.power_eq_0_iff_number_of",
   367    "Parity.power_le_zero_eq_number_of",   (*obscure and prolific*)
   368    "Parity.power_less_zero_eq_number_of",
   369    "Parity.zero_le_power_eq_number_of",   (*obscure and prolific*)
   370    "Parity.zero_less_power_eq_number_of",   (*obscure and prolific*)
   371    "Power.zero_less_power_abs_iff",
   372    "Relation.diagI",
   373    "Relation.ImageI",
   374    "Ring_and_Field.divide_cancel_left", (*fields are seldom used & often prolific*)
   375    "Ring_and_Field.divide_cancel_right",
   376    "Ring_and_Field.divide_divide_eq_left",
   377    "Ring_and_Field.divide_divide_eq_right",
   378    "Ring_and_Field.divide_eq_0_iff",
   379    "Ring_and_Field.divide_eq_1_iff",
   380    "Ring_and_Field.divide_eq_eq_1",
   381    "Ring_and_Field.divide_le_0_1_iff",
   382    "Ring_and_Field.divide_le_eq_1_neg",  (*obscure and prolific*)
   383    "Ring_and_Field.divide_le_eq_1_pos",  (*obscure and prolific*)
   384    "Ring_and_Field.divide_less_0_1_iff",
   385    "Ring_and_Field.divide_less_eq_1_neg",  (*obscure and prolific*)
   386    "Ring_and_Field.divide_less_eq_1_pos",  (*obscure and prolific*)
   387    "Ring_and_Field.eq_divide_eq_1", (*duplicate by symmetry*)
   388    "Ring_and_Field.field_mult_cancel_left",
   389    "Ring_and_Field.field_mult_cancel_right",
   390    "Ring_and_Field.inverse_le_iff_le_neg",
   391    "Ring_and_Field.inverse_le_iff_le",
   392    "Ring_and_Field.inverse_less_iff_less_neg",
   393    "Ring_and_Field.inverse_less_iff_less",
   394    "Ring_and_Field.le_divide_eq_1_neg", (*obscure and prolific*)
   395    "Ring_and_Field.le_divide_eq_1_pos", (*obscure and prolific*)
   396    "Ring_and_Field.less_divide_eq_1_neg", (*obscure and prolific*)
   397    "Ring_and_Field.less_divide_eq_1_pos", (*obscure and prolific*)
   398    "Ring_and_Field.one_eq_divide_iff",  (*duplicate by symmetry*)
   399    "Set.Diff_eq_empty_iff", (*redundant with paramodulation*)
   400    "Set.Diff_insert0",
   401    "Set.disjoint_insert_1",
   402    "Set.disjoint_insert_2",
   403    "Set.empty_Union_conv", (*redundant with paramodulation*)
   404    "Set.insert_disjoint_1",
   405    "Set.insert_disjoint_2",
   406    "Set.Int_UNIV", (*redundant with paramodulation*)
   407    "Set.Inter_iff",              (*We already have InterI, InterE*)
   408    "Set.Inter_UNIV_conv_1",
   409    "Set.Inter_UNIV_conv_2",
   410    "Set.psubsetE",    (*too prolific and obscure*)
   411    "Set.psubsetI",
   412    "Set.singleton_insert_inj_eq'",
   413    "Set.singleton_insert_inj_eq",
   414    "Set.singletonD",  (*these two duplicate some "insert" lemmas*)
   415    "Set.singletonI",
   416    "Set.Un_empty", (*redundant with paramodulation*)
   417    "Set.Union_empty_conv", (*redundant with paramodulation*)
   418    "Set.Union_iff",              (*We already have UnionI, UnionE*)
   419    "SetInterval.atLeastAtMost_iff", (*obscure and prolific*)
   420    "SetInterval.atLeastLessThan_iff", (*obscure and prolific*)
   421    "SetInterval.greaterThanAtMost_iff", (*obscure and prolific*)
   422    "SetInterval.greaterThanLessThan_iff", (*obscure and prolific*)
   423    "SetInterval.ivl_subset"];  (*excessive case analysis*)
   424 
   425 
   426 (*These might be prolific but are probably OK, and min and max are basic.
   427    "Orderings.max_less_iff_conj", 
   428    "Orderings.min_less_iff_conj",
   429    "Orderings.min_max.below_inf.below_inf_conv",
   430    "Orderings.min_max.below_sup.above_sup_conv",
   431 Very prolific and somewhat obscure:
   432    "Set.InterD",
   433    "Set.UnionI",
   434 *)
   435 
   436 (*** retrieve lemmas from clasimpset and atpset, may filter them ***)
   437 
   438 (*The "name" of a theorem is its statement, if nothing else is available.*)
   439 val plain_string_of_thm =
   440     setmp show_question_marks false 
   441       (setmp print_mode [] 
   442 	(Pretty.setmp_margin 999 string_of_thm));
   443 	
   444 (*Returns the first substring enclosed in quotation marks, typically omitting 
   445   the [.] of meta-level assumptions.*)
   446 val firstquoted = hd o (String.tokens (fn c => c = #"\""))
   447 	
   448 fun fake_thm_name th = 
   449     Context.theory_name (theory_of_thm th) ^ "." ^ firstquoted (plain_string_of_thm th);
   450 
   451 fun put_name_pair ("",th) = (fake_thm_name th, th)
   452   | put_name_pair (a,th)  = (a,th);
   453 
   454 (*Hashing to detect duplicate and variant clauses, e.g. from the [iff] attribute*)
   455 
   456 exception HASH_CLAUSE and HASH_STRING;
   457 
   458 (*Catches (for deletion) theorems automatically generated from other theorems*)
   459 fun insert_suffixed_names ht x = 
   460      (Polyhash.insert ht (x^"_iff1", ()); 
   461       Polyhash.insert ht (x^"_iff2", ()); 
   462       Polyhash.insert ht (x^"_dest", ())); 
   463 
   464 fun make_banned_test xs = 
   465   let val ht = Polyhash.mkTable (Polyhash.hash_string, op =)
   466                                 (6000, HASH_STRING)
   467       fun banned s = isSome (Polyhash.peek ht s)
   468   in  app (fn x => Polyhash.insert ht (x,())) (!blacklist);
   469       app (insert_suffixed_names ht) (!blacklist @ xs); 
   470       banned
   471   end;
   472 
   473 (** a hash function from Term.term to int, and also a hash table **)
   474 val xor_words = List.foldl Word.xorb 0w0;
   475 
   476 fun hashw_term ((Const(c,_)), w) = Polyhash.hashw_string (c,w)
   477   | hashw_term ((Free(_,_)), w) = w
   478   | hashw_term ((Var(_,_)), w) = w
   479   | hashw_term ((Bound _), w) = w
   480   | hashw_term ((Abs(_,_,t)), w) = hashw_term (t, w)
   481   | hashw_term ((P$Q), w) = hashw_term (Q, (hashw_term (P, w)));
   482 
   483 fun hashw_pred (P,w) = 
   484     let val (p,args) = strip_comb P
   485     in
   486 	List.foldl hashw_term w (p::args)
   487     end;
   488 
   489 fun hash_literal (Const("Not",_)$P) = Word.notb(hashw_pred(P,0w0))
   490   | hash_literal P = hashw_pred(P,0w0);
   491 
   492 
   493 fun get_literals (Const("Trueprop",_)$P) lits = get_literals P lits
   494   | get_literals (Const("op |",_)$P$Q) lits = get_literals Q (get_literals P lits)
   495   | get_literals lit lits = (lit::lits);
   496 
   497 
   498 fun hash_term term = Word.toIntX (xor_words (map hash_literal (get_literals term [])));
   499 
   500 fun hash_thm  thm = hash_term (prop_of thm);
   501 
   502 fun equal_thm (thm1,thm2) = Term.aconv(prop_of thm1, prop_of thm2);
   503 (*Create a hash table for clauses, of the given size*)
   504 fun mk_clause_table n =
   505       Polyhash.mkTable (hash_thm, equal_thm)
   506                        (n, HASH_CLAUSE);
   507 
   508 (*Use a hash table to eliminate duplicates from xs*)
   509 fun make_unique ht xs = 
   510       (app (ignore o Polyhash.peekInsert ht) xs;  Polyhash.listItems ht);
   511 
   512 fun mem_thm th [] = false
   513   | mem_thm th ((th',_)::thms_names) = equal_thm (th,th') orelse mem_thm th thms_names;
   514 
   515 fun insert_thms [] thms_names = thms_names
   516   | insert_thms ((thm,name)::thms_names) thms_names' =
   517       if mem_thm thm thms_names' then insert_thms thms_names thms_names' 
   518       else insert_thms thms_names ((thm,name)::thms_names');
   519 
   520 fun display_thms [] = ()
   521   | display_thms ((name,thm)::nthms) = 
   522       let val nthm = name ^ ": " ^ (string_of_thm thm)
   523       in Output.debug nthm; display_thms nthms  end;
   524  
   525 
   526 fun all_facts_of ctxt =
   527   FactIndex.find (ProofContext.fact_index_of ctxt) ([], [])
   528   |> maps #2 |> map (`Thm.name_of_thm);
   529 
   530 (* get lemmas from claset, simpset, atpset and extra supplied rules *)
   531 fun get_clasimp_atp_lemmas ctxt user_thms = 
   532   let val included_thms =
   533 	if !include_all 
   534 	then (tap (fn ths => Output.debug ("Including all " ^ Int.toString (length ths) ^
   535 	                                   " theorems")) 
   536 	          (all_facts_of ctxt @ PureThy.all_thms_of (ProofContext.theory_of ctxt)))
   537 	else 
   538 	let val claset_thms =
   539 		if !include_claset then ResAxioms.claset_rules_of_ctxt ctxt
   540 		else []
   541 	    val simpset_thms = 
   542 		if !include_simpset then ResAxioms.simpset_rules_of_ctxt ctxt
   543 		else []
   544 	    val atpset_thms =
   545 		if !include_atpset then ResAxioms.atpset_rules_of_ctxt ctxt
   546 		else []
   547 	    val _ = if !Output.show_debug_msgs 
   548 		    then (Output.debug "ATP theorems: "; display_thms atpset_thms) 
   549 		    else ()		 
   550 	in  claset_thms @ simpset_thms @ atpset_thms  end
   551       val user_rules = map (put_name_pair o ResAxioms.pairname)
   552 			   (if null user_thms then !whitelist else user_thms)
   553   in
   554       (map put_name_pair included_thms, user_rules)
   555   end;
   556 
   557 (* remove lemmas that are banned from the backlist *)
   558 fun blacklist_filter thms = 
   559   if !run_blacklist_filter then 
   560       let val banned = make_banned_test (map #1 thms)
   561 	  fun ok (a,_) = not (banned a)
   562       in  filter ok thms  end
   563   else thms;
   564 
   565 (* filter axiom clauses, but keep supplied clauses and clauses in whitelist *)
   566 fun get_relevant_clauses ctxt cls_thms white_cls goals =
   567  let val cls_thms_list = make_unique (mk_clause_table 2200) (List.concat (white_cls@cls_thms))
   568      val relevant_cls_thms_list = 
   569 	 if !run_relevance_filter 
   570 	 then ReduceAxiomsN.relevance_filter (ProofContext.theory_of ctxt) cls_thms_list goals 
   571 	 else cls_thms_list
   572  in
   573      insert_thms (List.concat white_cls) relevant_cls_thms_list 
   574  end;
   575 
   576 (***************************************************************)
   577 (* ATP invocation methods setup                                *)
   578 (***************************************************************)
   579 
   580 
   581 (**** prover-specific format: TPTP ****)
   582 
   583 
   584 fun cnf_hyps_thms ctxt = 
   585     let val ths = Assumption.prems_of ctxt
   586     in fold (fold (insert Thm.eq_thm) o ResAxioms.skolem_thm) ths [] end;
   587 
   588 
   589 (**** write to files ****)
   590 
   591 datatype mode = Auto | Fol | Hol;
   592 
   593 val linkup_logic_mode = ref Auto;
   594 
   595 fun tptp_writer logic goals filename (axioms,classrels,arities) user_lemmas =
   596     if is_fol_logic logic 
   597     then ResClause.tptp_write_file goals filename (axioms, classrels, arities)
   598     else ResHolClause.tptp_write_file goals filename (axioms, classrels, arities) user_lemmas;
   599 
   600 fun dfg_writer logic goals filename (axioms,classrels,arities) user_lemmas =
   601     if is_fol_logic logic 
   602     then ResClause.dfg_write_file goals filename (axioms, classrels, arities)
   603     else ResHolClause.dfg_write_file goals filename (axioms, classrels, arities) user_lemmas;
   604 
   605 (*Called by the oracle-based methods declared in res_atp_methods.ML*)
   606 fun write_subgoal_file dfg mode ctxt conjectures user_thms n =
   607     let val conj_cls = make_clauses conjectures 
   608 	val hyp_cls = cnf_hyps_thms ctxt
   609 	val goal_cls = conj_cls@hyp_cls
   610 	val (included_thms,user_rules) = get_clasimp_atp_lemmas ctxt user_thms
   611 	val user_lemmas_names = map #1 user_rules
   612 	val rm_black_cls = blacklist_filter included_thms 
   613 	val cla_simp_atp_clauses = ResAxioms.cnf_rules_pairs rm_black_cls
   614 	val user_cls = ResAxioms.cnf_rules_pairs user_rules
   615 	val axclauses = get_relevant_clauses ctxt cla_simp_atp_clauses
   616 	                            user_cls (map prop_of goal_cls)
   617 	val thy = ProofContext.theory_of ctxt
   618 	val prob_logic = case mode of 
   619                             Auto => problem_logic_goals [map prop_of goal_cls]
   620 			  | Fol => FOL
   621 			  | Hol => HOL
   622 	val keep_types = if is_fol_logic prob_logic then !fol_keep_types else is_typed_hol ()
   623 	val classrel_clauses = if keep_types then ResClause.classrel_clauses_thy thy else []
   624 	val arity_clauses = if keep_types then ResClause.arity_clause_thy thy else []
   625         val writer = if dfg then dfg_writer else tptp_writer 
   626 	val file = atp_input_file()
   627     in
   628 	(writer prob_logic goal_cls file (axclauses,classrel_clauses,arity_clauses) user_lemmas_names;
   629 	 Output.debug ("Writing to " ^ file);
   630 	 file)
   631     end;
   632 
   633 
   634 (**** remove tmp files ****)
   635 fun cond_rm_tmp file = 
   636     if !keep_atp_input then Output.debug "ATP input kept..." 
   637     else if !destdir <> "" then Output.debug ("ATP input kept in directory " ^ (!destdir))
   638     else (Output.debug "deleting ATP inputs..."; OS.FileSys.remove file);
   639 
   640 
   641 (****** setup ATPs as Isabelle methods ******)
   642 fun atp_meth' tac ths ctxt = 
   643     Method.SIMPLE_METHOD' HEADGOAL
   644     (tac ctxt ths);
   645 
   646 fun atp_meth tac ths ctxt = 
   647     let val thy = ProofContext.theory_of ctxt
   648 	val _ = ResClause.init thy
   649 	val _ = ResHolClause.init thy
   650     in
   651 	atp_meth' tac ths ctxt
   652     end;
   653 
   654 fun atp_method tac = Method.thms_ctxt_args (atp_meth tac);
   655 
   656 (***************************************************************)
   657 (* automatic ATP invocation                                    *)
   658 (***************************************************************)
   659 
   660 (* call prover with settings and problem file for the current subgoal *)
   661 fun watcher_call_provers sign sg_terms (childin, childout, pid) =
   662   let
   663     fun make_atp_list [] n = []
   664       | make_atp_list (sg_term::xs) n =
   665           let
   666             val probfile = prob_pathname n
   667             val time = Int.toString (!time_limit)
   668           in
   669             Output.debug ("problem file in watcher_call_provers is " ^ probfile);
   670             (*options are separated by Watcher.setting_sep, currently #"%"*)
   671             if !prover = "spass"
   672             then
   673               let val spass = helper_path "SPASS_HOME" "SPASS"
   674                   val sopts =
   675    "-Auto%-SOS=1%-PGiven=0%-PProblem=0%-Splits=0%-FullRed=0%-DocProof%-TimeLimit=" ^ time
   676               in 
   677                   ("spass", spass, sopts, probfile) :: make_atp_list xs (n+1)
   678               end
   679             else if !prover = "vampire"
   680 	    then 
   681               let val vampire = helper_path "VAMPIRE_HOME" "vampire"
   682                   val casc = if !time_limit > 70 then "--mode casc%" else ""
   683                   val vopts = casc ^ "-m 100000%-t " ^ time
   684               in
   685                   ("vampire", vampire, vopts, probfile) :: make_atp_list xs (n+1)
   686               end
   687       	     else if !prover = "E"
   688       	     then
   689 	       let val Eprover = helper_path "E_HOME" "eproof"
   690 	       in
   691 		  ("E", Eprover, 
   692 		     "--tptp-in%-l5%-xAuto%-tAuto%--silent%--cpu-limit=" ^ time, probfile) ::
   693 		   make_atp_list xs (n+1)
   694 	       end
   695 	     else error ("Invalid prover name: " ^ !prover)
   696           end
   697 
   698     val atp_list = make_atp_list sg_terms 1
   699   in
   700     Watcher.callResProvers(childout,atp_list);
   701     Output.debug "Sent commands to watcher!"
   702   end
   703   
   704 fun trace_array fname =
   705   let val path = File.tmp_path (Path.basic fname)
   706   in  Array.app (File.append path o (fn s => s ^ "\n"))  end;
   707 
   708 (*We write out problem files for each subgoal. Argument probfile generates filenames,
   709   and allows the suppression of the suffix "_1" in problem-generation mode.
   710   FIXME: does not cope with &&, and it isn't easy because one could have multiple
   711   subgoals, each involving &&.*)
   712 fun write_problem_files probfile (ctxt,th)  =
   713   let val goals = Thm.prems_of th
   714       val _ = Output.debug ("number of subgoals = " ^ Int.toString (length goals))
   715       val (included_thms,white_thms) = get_clasimp_atp_lemmas ctxt []
   716       val rm_blacklist_cls = blacklist_filter included_thms
   717       val cla_simp_atp_clauses = ResAxioms.cnf_rules_pairs rm_blacklist_cls
   718       val axclauses = get_relevant_clauses ctxt cla_simp_atp_clauses (ResAxioms.cnf_rules_pairs white_thms) goals 
   719       val _ = Output.debug ("total clauses from thms = " ^ Int.toString (length axclauses))
   720       val thy = ProofContext.theory_of ctxt
   721       fun get_neg_subgoals n =
   722 	  if n=0 then []
   723 	  else
   724 	      let val st = Seq.hd (EVERY' [rtac ccontr, ObjectLogic.atomize_tac, 
   725 	                                   skolemize_tac] n th)
   726 		  val negs = Option.valOf (metahyps_thms n st)
   727 		  val negs_clauses = make_clauses negs
   728 	      in
   729 		  negs_clauses :: get_neg_subgoals (n-1)
   730 	      end
   731       val neg_subgoals = get_neg_subgoals (length goals) 
   732       val goals_logic = case !linkup_logic_mode of
   733                             Auto => problem_logic_goals (map (map prop_of) neg_subgoals)
   734 			  | Fol => FOL
   735 			  | Hol => HOL
   736       val keep_types = if is_fol_logic goals_logic then !ResClause.keep_types else is_typed_hol ()
   737       val classrel_clauses = if keep_types then ResClause.classrel_clauses_thy thy else []
   738       val _ = Output.debug ("classrel clauses = " ^ Int.toString (length classrel_clauses))
   739       val arity_clauses = if keep_types then ResClause.arity_clause_thy thy else []
   740       val _ = Output.debug ("arity clauses = " ^ Int.toString (length arity_clauses))
   741       val writer = if !prover = "spass" then dfg_writer else tptp_writer 
   742       fun write_all [] _ = []
   743 	| write_all (sub::subgoals) k =
   744 	   (writer goals_logic sub (probfile k) (axclauses,classrel_clauses,arity_clauses) [],
   745 	    probfile k) :: write_all subgoals (k-1)
   746       val (clnames::_, filenames) = ListPair.unzip (write_all neg_subgoals (length goals))
   747       val thm_names = Array.fromList clnames
   748       val _ = if !Output.show_debug_msgs 
   749               then trace_array "thm_names" thm_names else ()
   750   in
   751       (filenames, thm_names)
   752   end;
   753 
   754 val last_watcher_pid = ref (NONE : (TextIO.instream * TextIO.outstream * 
   755                                     Posix.Process.pid * string list) option);
   756 
   757 fun kill_last_watcher () =
   758     (case !last_watcher_pid of 
   759          NONE => ()
   760        | SOME (_, _, pid, files) => 
   761 	  (Output.debug ("Killing old watcher, pid = " ^ string_of_pid pid);
   762 	   Watcher.killWatcher pid;  
   763 	   ignore (map (try OS.FileSys.remove) files)))
   764      handle OS.SysErr _ => Output.debug "Attempt to kill watcher failed";
   765 
   766 (*writes out the current clasimpset to a tptp file;
   767   turns off xsymbol at start of function, restoring it at end    *)
   768 val isar_atp = setmp print_mode [] 
   769  (fn (ctxt, th) =>
   770   if Thm.no_prems th then ()
   771   else
   772     let
   773       val _ = kill_last_watcher()
   774       val (files,thm_names) = write_problem_files prob_pathname (ctxt,th)
   775       val (childin, childout, pid) = Watcher.createWatcher (th, thm_names)
   776     in
   777       last_watcher_pid := SOME (childin, childout, pid, files);
   778       Output.debug ("problem files: " ^ space_implode ", " files); 
   779       Output.debug ("pid: " ^ string_of_pid pid);
   780       watcher_call_provers (sign_of_thm th) (Thm.prems_of th) (childin, childout, pid)
   781     end);
   782 
   783 val isar_atp_writeonly = setmp print_mode [] 
   784       (fn (ctxt,th) =>
   785        if Thm.no_prems th then ()
   786        else 
   787          let val probfile = if Thm.nprems_of th = 1 then probfile_nosuffix 
   788           	            else prob_pathname
   789          in ignore (write_problem_files probfile (ctxt,th)) end);
   790 
   791 
   792 (** the Isar toplevel hook **)
   793 
   794 fun invoke_atp_ml (ctxt, goal) =
   795   let val thy = ProofContext.theory_of ctxt;
   796   in
   797     Output.debug ("subgoals in isar_atp:\n" ^ 
   798 		  Pretty.string_of (ProofContext.pretty_term ctxt
   799 		    (Logic.mk_conjunction_list (Thm.prems_of goal))));
   800     Output.debug ("current theory: " ^ Context.theory_name thy);
   801     hook_count := !hook_count +1;
   802     Output.debug ("in hook for time: " ^ Int.toString (!hook_count));
   803     ResClause.init thy;
   804     ResHolClause.init thy;
   805     if !destdir = "" andalso !time_limit > 0 then isar_atp (ctxt, goal)
   806     else isar_atp_writeonly (ctxt, goal)
   807   end;
   808 
   809 val invoke_atp = Toplevel.no_timing o Toplevel.unknown_proof o Toplevel.keep
   810  (fn state =>
   811   let val (ctxt, (_, goal)) = Proof.get_goal (Toplevel.proof_of state)
   812   in  invoke_atp_ml (ctxt, goal)  end);
   813 
   814 val call_atpP =
   815   OuterSyntax.command 
   816     "ProofGeneral.call_atp" 
   817     "call automatic theorem provers" 
   818     OuterKeyword.diag
   819     (Scan.succeed invoke_atp);
   820 
   821 val _ = OuterSyntax.add_parsers [call_atpP];
   822 
   823 end;