src/HOL/Tools/res_atp.ML
author paulson
Fri Aug 10 15:13:18 2007 +0200 (2007-08-10)
changeset 24215 5458fbf18276
parent 23387 7cb8faa5d4d3
child 24286 7619080e49f0
permissions -rw-r--r--
removal of some refs
mengj@19194
     1
(*  Author: Jia Meng, Cambridge University Computer Laboratory, NICTA
paulson@15608
     2
    ID: $Id$
paulson@15608
     3
    Copyright 2004 University of Cambridge
paulson@15347
     4
paulson@15347
     5
ATPs with TPTP format input.
paulson@15347
     6
*)
paulson@15452
     7
wenzelm@16802
     8
signature RES_ATP =
wenzelm@16802
     9
sig
paulson@17306
    10
  val prover: string ref
paulson@17484
    11
  val destdir: string ref
paulson@17849
    12
  val helper_path: string -> string -> string
paulson@17484
    13
  val problem_name: string ref
paulson@17690
    14
  val time_limit: int ref
paulson@21224
    15
  val set_prover: string -> unit
wenzelm@21588
    16
mengj@19194
    17
  datatype mode = Auto | Fol | Hol
paulson@19450
    18
  val linkup_logic_mode : mode ref
mengj@19722
    19
  val write_subgoal_file: bool -> mode -> Proof.context -> thm list -> thm list -> int -> string
wenzelm@20289
    20
  val atp_method: (Proof.context -> thm list -> int -> tactic) ->
wenzelm@20289
    21
    Method.src -> Proof.context -> Proof.method
mengj@19194
    22
  val cond_rm_tmp: string -> unit
paulson@20246
    23
  val include_all: bool ref
mengj@19194
    24
  val run_relevance_filter: bool ref
mengj@19768
    25
  val run_blacklist_filter: bool ref
paulson@19894
    26
  val add_all : unit -> unit
mengj@19227
    27
  val add_claset : unit -> unit
mengj@19227
    28
  val add_simpset : unit -> unit
mengj@19227
    29
  val add_clasimp : unit -> unit
mengj@19227
    30
  val add_atpset : unit -> unit
paulson@19894
    31
  val rm_all : unit -> unit
mengj@19227
    32
  val rm_claset : unit -> unit
mengj@19227
    33
  val rm_simpset : unit -> unit
mengj@19227
    34
  val rm_atpset : unit -> unit
mengj@19227
    35
  val rm_clasimp : unit -> unit
mengj@21311
    36
  val is_fol_thms : thm list -> bool
paulson@22989
    37
  val tvar_classes_of_terms : term list -> string list
paulson@22989
    38
  val tfree_classes_of_terms : term list -> string list
paulson@22989
    39
  val type_consts_of_terms : theory -> term list -> string list
paulson@15347
    40
end;
paulson@15347
    41
wenzelm@22865
    42
structure ResAtp: RES_ATP =
paulson@15347
    43
struct
paulson@15347
    44
wenzelm@22130
    45
fun timestamp s = Output.debug (fn () => ("At " ^ Time.toString (Time.now()) ^ ": " ^ s));
paulson@21070
    46
mengj@19194
    47
(********************************************************************)
mengj@19194
    48
(* some settings for both background automatic ATP calling procedure*)
mengj@19194
    49
(* and also explicit ATP invocation methods                         *)
mengj@19194
    50
(********************************************************************)
mengj@19194
    51
mengj@19194
    52
(*** background linkup ***)
paulson@21224
    53
val time_limit = ref 60;
wenzelm@21588
    54
val prover = ref "";
paulson@21224
    55
wenzelm@21588
    56
fun set_prover atp =
paulson@21224
    57
  case String.map Char.toLower atp of
wenzelm@21588
    58
      "e" =>
paulson@21290
    59
          (ReduceAxiomsN.max_new := 100;
paulson@21224
    60
           ReduceAxiomsN.theory_const := false;
paulson@21224
    61
           prover := "E")
wenzelm@21588
    62
    | "spass" =>
paulson@21224
    63
          (ReduceAxiomsN.max_new := 40;
paulson@21224
    64
           ReduceAxiomsN.theory_const := true;
paulson@21224
    65
           prover := "spass")
wenzelm@21588
    66
    | "vampire" =>
paulson@21224
    67
          (ReduceAxiomsN.max_new := 60;
paulson@21224
    68
           ReduceAxiomsN.theory_const := false;
paulson@21224
    69
           prover := "vampire")
paulson@21224
    70
    | _ => error ("No such prover: " ^ atp);
paulson@21224
    71
paulson@21224
    72
val _ = set_prover "E"; (* use E as the default prover *)
paulson@21224
    73
paulson@17484
    74
val destdir = ref "";   (*Empty means write files to /tmp*)
paulson@17484
    75
val problem_name = ref "prob";
paulson@17484
    76
paulson@17819
    77
(*Return the path to a "helper" like SPASS or tptp2X, first checking that
wenzelm@21588
    78
  it exists.  FIXME: modify to use Path primitives and move to some central place.*)
paulson@17819
    79
fun helper_path evar base =
paulson@17819
    80
  case getenv evar of
paulson@17819
    81
      "" => error  ("Isabelle environment variable " ^ evar ^ " not defined")
wenzelm@21588
    82
    | home =>
paulson@17819
    83
        let val path = home ^ "/" ^ base
wenzelm@21858
    84
        in  if File.exists (File.explode_platform_path path) then path
wenzelm@21588
    85
            else error ("Could not find the file " ^ path)
wenzelm@21588
    86
        end;
paulson@17819
    87
wenzelm@21588
    88
fun probfile_nosuffix _ =
paulson@17484
    89
  if !destdir = "" then File.platform_path (File.tmp_path (Path.basic (!problem_name)))
wenzelm@21858
    90
  else if File.exists (File.explode_platform_path (!destdir))
paulson@17484
    91
  then !destdir ^ "/" ^ !problem_name
paulson@17484
    92
  else error ("No such directory: " ^ !destdir);
quigley@15644
    93
paulson@17717
    94
fun prob_pathname n = probfile_nosuffix n ^ "_" ^ Int.toString n;
paulson@17717
    95
mengj@19194
    96
fun atp_input_file () =
wenzelm@21588
    97
    let val file = !problem_name
mengj@19194
    98
    in
wenzelm@21588
    99
        if !destdir = "" then File.platform_path (File.tmp_path (Path.basic file))
wenzelm@21858
   100
        else if File.exists (File.explode_platform_path (!destdir))
wenzelm@21588
   101
        then !destdir ^ "/" ^ file
wenzelm@21588
   102
        else error ("No such directory: " ^ !destdir)
mengj@19194
   103
    end;
mengj@19194
   104
paulson@20868
   105
val include_all = ref true;
mengj@19194
   106
val include_simpset = ref false;
wenzelm@21588
   107
val include_claset = ref false;
mengj@19194
   108
val include_atpset = ref true;
paulson@20246
   109
paulson@20246
   110
(*Tests show that follow_defs gives VERY poor results with "include_all"*)
paulson@20246
   111
fun add_all() = (include_all:=true; ReduceAxiomsN.follow_defs := false);
paulson@20246
   112
fun rm_all() = include_all:=false;
paulson@20246
   113
paulson@20246
   114
fun add_simpset() = include_simpset:=true;
paulson@20246
   115
fun rm_simpset() = include_simpset:=false;
paulson@20246
   116
paulson@20246
   117
fun add_claset() = include_claset:=true;
paulson@20246
   118
fun rm_claset() = include_claset:=false;
paulson@20246
   119
paulson@20246
   120
fun add_clasimp() = (include_simpset:=true;include_claset:=true);
paulson@20246
   121
fun rm_clasimp() = (include_simpset:=false;include_claset:=false);
paulson@20246
   122
paulson@20246
   123
fun add_atpset() = include_atpset:=true;
paulson@20246
   124
fun rm_atpset() = include_atpset:=false;
mengj@19194
   125
mengj@19194
   126
mengj@19194
   127
(**** relevance filter ****)
paulson@20457
   128
val run_relevance_filter = ReduceAxiomsN.run_relevance_filter;
mengj@19768
   129
val run_blacklist_filter = ref true;
mengj@19194
   130
mengj@19194
   131
(******************************************************************)
mengj@19194
   132
(* detect whether a given problem (clauses) is FOL/HOL/HOLC/HOLCS *)
mengj@19194
   133
(******************************************************************)
mengj@19194
   134
mengj@19194
   135
datatype logic = FOL | HOL | HOLC | HOLCS;
mengj@19194
   136
mengj@19194
   137
fun string_of_logic FOL = "FOL"
mengj@19194
   138
  | string_of_logic HOL = "HOL"
mengj@19194
   139
  | string_of_logic HOLC = "HOLC"
mengj@19194
   140
  | string_of_logic HOLCS = "HOLCS";
mengj@19194
   141
mengj@19194
   142
fun is_fol_logic FOL = true
mengj@19194
   143
  | is_fol_logic  _ = false
mengj@19194
   144
mengj@19194
   145
(*HOLCS will not occur here*)
mengj@19194
   146
fun upgrade_lg HOLC _ = HOLC
mengj@19194
   147
  | upgrade_lg HOL HOLC = HOLC
mengj@19194
   148
  | upgrade_lg HOL _ = HOL
wenzelm@21588
   149
  | upgrade_lg FOL lg = lg;
mengj@19194
   150
mengj@19194
   151
(* check types *)
mengj@19451
   152
fun has_bool_hfn (Type("bool",_)) = true
mengj@19451
   153
  | has_bool_hfn (Type("fun",_)) = true
mengj@19451
   154
  | has_bool_hfn (Type(_, Ts)) = exists has_bool_hfn Ts
mengj@19451
   155
  | has_bool_hfn _ = false;
mengj@19194
   156
mengj@19451
   157
fun is_hol_fn tp =
mengj@19194
   158
    let val (targs,tr) = strip_type tp
mengj@19194
   159
    in
wenzelm@21588
   160
        exists (has_bool_hfn) (tr::targs)
mengj@19194
   161
    end;
mengj@19194
   162
mengj@19451
   163
fun is_hol_pred tp =
mengj@19451
   164
    let val (targs,tr) = strip_type tp
mengj@19451
   165
    in
wenzelm@21588
   166
        exists (has_bool_hfn) targs
mengj@19451
   167
    end;
mengj@19194
   168
mengj@19194
   169
exception FN_LG of term;
mengj@19194
   170
wenzelm@21588
   171
fun fn_lg (t as Const(f,tp)) (lg,seen) =
wenzelm@21588
   172
    if is_hol_fn tp then (upgrade_lg HOL lg, insert (op =) t seen) else (lg, insert (op =) t seen)
wenzelm@21588
   173
  | fn_lg (t as Free(f,tp)) (lg,seen) =
wenzelm@21588
   174
    if is_hol_fn tp then (upgrade_lg HOL lg, insert (op =) t seen) else (lg, insert (op =) t seen)
mengj@19194
   175
  | fn_lg (t as Var(f,tp)) (lg,seen) =
haftmann@20854
   176
    if is_hol_fn tp then (upgrade_lg HOL lg,insert (op =) t seen) else (lg,insert (op =) t seen)
haftmann@20854
   177
  | fn_lg (t as Abs(_,_,_)) (lg,seen) = (upgrade_lg HOLC lg,insert (op =) t seen)
wenzelm@21588
   178
  | fn_lg f _ = raise FN_LG(f);
mengj@19194
   179
mengj@19194
   180
mengj@19194
   181
fun term_lg [] (lg,seen) = (lg,seen)
mengj@19194
   182
  | term_lg (tm::tms) (FOL,seen) =
paulson@20457
   183
      let val (f,args) = strip_comb tm
wenzelm@21588
   184
          val (lg',seen') = if f mem seen then (FOL,seen)
wenzelm@21588
   185
                            else fn_lg f (FOL,seen)
paulson@20457
   186
      in
wenzelm@21588
   187
        if is_fol_logic lg' then ()
wenzelm@22130
   188
        else Output.debug (fn () => ("Found a HOL term: " ^ Display.raw_string_of_term f));
paulson@20457
   189
        term_lg (args@tms) (lg',seen')
paulson@20457
   190
      end
mengj@19194
   191
  | term_lg _ (lg,seen) = (lg,seen)
mengj@19194
   192
mengj@19194
   193
exception PRED_LG of term;
mengj@19194
   194
wenzelm@21588
   195
fun pred_lg (t as Const(P,tp)) (lg,seen)=
wenzelm@21588
   196
      if is_hol_pred tp then (upgrade_lg HOL lg, insert (op =) t seen)
wenzelm@21588
   197
      else (lg,insert (op =) t seen)
mengj@19194
   198
  | pred_lg (t as Free(P,tp)) (lg,seen) =
wenzelm@21588
   199
      if is_hol_pred tp then (upgrade_lg HOL lg, insert (op =) t seen)
paulson@21470
   200
      else (lg,insert (op =) t seen)
haftmann@20854
   201
  | pred_lg (t as Var(_,_)) (lg,seen) = (upgrade_lg HOL lg, insert (op =) t seen)
mengj@19194
   202
  | pred_lg P _ = raise PRED_LG(P);
mengj@19194
   203
mengj@19194
   204
mengj@19194
   205
fun lit_lg (Const("Not",_) $ P) (lg,seen) = lit_lg P (lg,seen)
mengj@19194
   206
  | lit_lg P (lg,seen) =
paulson@20457
   207
      let val (pred,args) = strip_comb P
wenzelm@21588
   208
          val (lg',seen') = if pred mem seen then (lg,seen)
wenzelm@21588
   209
                            else pred_lg pred (lg,seen)
paulson@20457
   210
      in
wenzelm@21588
   211
        if is_fol_logic lg' then ()
wenzelm@22130
   212
        else Output.debug (fn () => ("Found a HOL predicate: " ^ Display.raw_string_of_term pred));
wenzelm@21588
   213
        term_lg args (lg',seen')
paulson@20457
   214
      end;
mengj@19194
   215
mengj@19194
   216
fun lits_lg [] (lg,seen) = (lg,seen)
mengj@19194
   217
  | lits_lg (lit::lits) (FOL,seen) =
paulson@20457
   218
      let val (lg,seen') = lit_lg lit (FOL,seen)
paulson@20457
   219
      in
wenzelm@21588
   220
        if is_fol_logic lg then ()
wenzelm@22130
   221
        else Output.debug (fn () => ("Found a HOL literal: " ^ Display.raw_string_of_term lit));
wenzelm@21588
   222
        lits_lg lits (lg,seen')
paulson@20457
   223
      end
mengj@19194
   224
  | lits_lg lits (lg,seen) = (lg,seen);
mengj@19194
   225
paulson@21470
   226
fun dest_disj_aux (Const("Trueprop",_) $ t) disjs = dest_disj_aux t disjs
paulson@21470
   227
  | dest_disj_aux (Const ("op |", _) $ t $ t') disjs = dest_disj_aux t (dest_disj_aux t' disjs)
mengj@19227
   228
  | dest_disj_aux t disjs = t::disjs;
mengj@19227
   229
mengj@19227
   230
fun dest_disj t = dest_disj_aux t [];
mengj@19227
   231
paulson@21470
   232
fun logic_of_clause tm = lits_lg (dest_disj tm);
mengj@19194
   233
mengj@19194
   234
fun logic_of_clauses [] (lg,seen) = (lg,seen)
mengj@19194
   235
  | logic_of_clauses (cls::clss) (FOL,seen) =
mengj@19227
   236
    let val (lg,seen') = logic_of_clause cls (FOL,seen)
wenzelm@21588
   237
        val _ =
wenzelm@19641
   238
          if is_fol_logic lg then ()
wenzelm@22130
   239
          else Output.debug (fn () => ("Found a HOL clause: " ^ Display.raw_string_of_term cls))
mengj@19227
   240
    in
wenzelm@21588
   241
        logic_of_clauses clss (lg,seen')
mengj@19227
   242
    end
mengj@19194
   243
  | logic_of_clauses (cls::clss) (lg,seen) = (lg,seen);
mengj@19194
   244
mengj@19194
   245
fun problem_logic_goals_aux [] (lg,seen) = lg
wenzelm@21588
   246
  | problem_logic_goals_aux (subgoal::subgoals) (lg,seen) =
mengj@19194
   247
    problem_logic_goals_aux subgoals (logic_of_clauses subgoal (lg,seen));
wenzelm@21588
   248
mengj@19194
   249
fun problem_logic_goals subgoals = problem_logic_goals_aux subgoals (FOL,[]);
mengj@19194
   250
mengj@21311
   251
fun is_fol_thms ths = ((fst(logic_of_clauses (map prop_of ths) (FOL,[]))) = FOL);
mengj@21311
   252
mengj@19768
   253
(***************************************************************)
mengj@19768
   254
(* Retrieving and filtering lemmas                             *)
mengj@19768
   255
(***************************************************************)
mengj@19768
   256
mengj@19768
   257
(*** white list and black list of lemmas ***)
mengj@19768
   258
paulson@24215
   259
(*The rule subsetI is frequently omitted by the relevance filter. This could be theory data
paulson@24215
   260
  or identified with ATPset (which however is too big currently)*)
paulson@24215
   261
val whitelist = [subsetI];
wenzelm@21588
   262
paulson@22382
   263
(*Names of theorems and theorem lists to be blacklisted.
paulson@20444
   264
paulson@20444
   265
  These theorems typically produce clauses that are prolific (match too many equality or
mengj@19768
   266
  membership literals) and relate to seldom-used facts. Some duplicate other rules.
mengj@19768
   267
  FIXME: this blacklist needs to be maintained using theory data and added to using
mengj@19768
   268
  an attribute.*)
paulson@24215
   269
val blacklist = 
paulson@20526
   270
  ["Datatype.prod.size",
mengj@19768
   271
   "Divides.dvd_0_left_iff",
mengj@19768
   272
   "Finite_Set.card_0_eq",
mengj@19768
   273
   "Finite_Set.card_infinite",
mengj@19768
   274
   "Finite_Set.Max_ge",
mengj@19768
   275
   "Finite_Set.Max_in",
mengj@19768
   276
   "Finite_Set.Max_le_iff",
mengj@19768
   277
   "Finite_Set.Max_less_iff",
mengj@19768
   278
   "Finite_Set.max.f_below_strict_below.below_f_conv", (*duplicates in Orderings.*)
mengj@19768
   279
   "Finite_Set.max.f_below_strict_below.strict_below_f_conv", (*duplicates in Orderings.*)
mengj@19768
   280
   "Finite_Set.Min_ge_iff",
mengj@19768
   281
   "Finite_Set.Min_gr_iff",
mengj@19768
   282
   "Finite_Set.Min_in",
mengj@19768
   283
   "Finite_Set.Min_le",
mengj@19768
   284
   "Finite_Set.min.f_below_strict_below.below_f_conv",        (*duplicates in Orderings.*)
mengj@19768
   285
   "Finite_Set.min.f_below_strict_below.strict_below_f_conv", (*duplicates in Orderings.*)
paulson@20526
   286
   "Fun.vimage_image_eq",   (*involves an existential quantifier*)
paulson@20526
   287
   "HOL.split_if_asm",     (*splitting theorem*)
paulson@20457
   288
   "HOL.split_if",         (*splitting theorem*)
paulson@22193
   289
   "HOL.All_def",          (*far worse than useless!!*)
paulson@20526
   290
   "IntDef.abs_split",
mengj@19768
   291
   "IntDef.Integ.Abs_Integ_inject",
mengj@19768
   292
   "IntDef.Integ.Abs_Integ_inverse",
mengj@19768
   293
   "IntDiv.zdvd_0_left",
mengj@19768
   294
   "List.append_eq_append_conv",
mengj@19768
   295
   "List.hd_Cons_tl",   (*Says everything is [] or Cons. Probably prolific.*)
mengj@19768
   296
   "List.in_listsD",
mengj@19768
   297
   "List.in_listsI",
mengj@19768
   298
   "List.lists.Cons",
mengj@19768
   299
   "List.listsE",
mengj@19768
   300
   "Nat.less_one", (*not directional? obscure*)
mengj@19768
   301
   "Nat.not_gr0",
mengj@19768
   302
   "Nat.one_eq_mult_iff", (*duplicate by symmetry*)
wenzelm@21243
   303
   "Nat.of_nat_0_eq_iff",
wenzelm@21243
   304
   "Nat.of_nat_eq_0_iff",
wenzelm@21243
   305
   "Nat.of_nat_le_0_iff",
mengj@19768
   306
   "NatSimprocs.divide_le_0_iff_number_of",  (*too many clauses*)
mengj@19768
   307
   "NatSimprocs.divide_less_0_iff_number_of",
mengj@19768
   308
   "NatSimprocs.equation_minus_iff_1",  (*not directional*)
mengj@19768
   309
   "NatSimprocs.equation_minus_iff_number_of", (*not directional*)
mengj@19768
   310
   "NatSimprocs.le_minus_iff_1", (*not directional*)
mengj@19768
   311
   "NatSimprocs.le_minus_iff_number_of",  (*not directional*)
mengj@19768
   312
   "NatSimprocs.less_minus_iff_1", (*not directional*)
mengj@19768
   313
   "NatSimprocs.less_minus_iff_number_of", (*not directional*)
mengj@19768
   314
   "NatSimprocs.minus_equation_iff_number_of", (*not directional*)
mengj@19768
   315
   "NatSimprocs.minus_le_iff_1", (*not directional*)
mengj@19768
   316
   "NatSimprocs.minus_le_iff_number_of", (*not directional*)
mengj@19768
   317
   "NatSimprocs.minus_less_iff_1", (*not directional*)
mengj@19768
   318
   "NatSimprocs.mult_le_cancel_left_number_of", (*excessive case analysis*)
mengj@19768
   319
   "NatSimprocs.mult_le_cancel_right_number_of", (*excessive case analysis*)
mengj@19768
   320
   "NatSimprocs.mult_less_cancel_left_number_of", (*excessive case analysis*)
mengj@19768
   321
   "NatSimprocs.mult_less_cancel_right_number_of", (*excessive case analysis*)
mengj@19768
   322
   "NatSimprocs.zero_le_divide_iff_number_of", (*excessive case analysis*)
mengj@19768
   323
   "NatSimprocs.zero_less_divide_iff_number_of",
mengj@19768
   324
   "OrderedGroup.abs_0_eq", (*duplicate by symmetry*)
mengj@19768
   325
   "OrderedGroup.diff_eq_0_iff_eq", (*prolific?*)
haftmann@22422
   326
   "OrderedGroup.sup_0_eq_0",
haftmann@22422
   327
   "OrderedGroup.inf_0_eq_0",
mengj@19768
   328
   "OrderedGroup.pprt_eq_0",   (*obscure*)
mengj@19768
   329
   "OrderedGroup.pprt_eq_id",   (*obscure*)
mengj@19768
   330
   "OrderedGroup.pprt_mono",   (*obscure*)
paulson@20526
   331
   "Orderings.split_max",      (*splitting theorem*)
paulson@20457
   332
   "Orderings.split_min",      (*splitting theorem*)
mengj@19768
   333
   "Power.zero_less_power_abs_iff",
paulson@20526
   334
   "Product_Type.split_eta_SetCompr",   (*involves an existential quantifier*)
paulson@20457
   335
   "Product_Type.split_paired_Ball_Sigma",     (*splitting theorem*)
paulson@20457
   336
   "Product_Type.split_paired_Bex_Sigma",      (*splitting theorem*)
paulson@20526
   337
   "Product_Type.split_split_asm",             (*splitting theorem*)
paulson@20457
   338
   "Product_Type.split_split",                 (*splitting theorem*)
paulson@20526
   339
   "Product_Type.unit_abs_eta_conv",
paulson@20526
   340
   "Product_Type.unit_induct",
mengj@19768
   341
   "Relation.diagI",
paulson@20526
   342
   "Relation.Domain_def",   (*involves an existential quantifier*)
paulson@20526
   343
   "Relation.Image_def",   (*involves an existential quantifier*)
mengj@19768
   344
   "Relation.ImageI",
mengj@19768
   345
   "Ring_and_Field.divide_cancel_left", (*fields are seldom used & often prolific*)
mengj@19768
   346
   "Ring_and_Field.divide_cancel_right",
mengj@19768
   347
   "Ring_and_Field.divide_divide_eq_left",
mengj@19768
   348
   "Ring_and_Field.divide_divide_eq_right",
mengj@19768
   349
   "Ring_and_Field.divide_eq_0_iff",
mengj@19768
   350
   "Ring_and_Field.divide_eq_1_iff",
mengj@19768
   351
   "Ring_and_Field.divide_eq_eq_1",
mengj@19768
   352
   "Ring_and_Field.divide_le_0_1_iff",
mengj@19768
   353
   "Ring_and_Field.divide_le_eq_1_neg",  (*obscure and prolific*)
mengj@19768
   354
   "Ring_and_Field.divide_le_eq_1_pos",  (*obscure and prolific*)
mengj@19768
   355
   "Ring_and_Field.divide_less_0_1_iff",
mengj@19768
   356
   "Ring_and_Field.divide_less_eq_1_neg",  (*obscure and prolific*)
mengj@19768
   357
   "Ring_and_Field.divide_less_eq_1_pos",  (*obscure and prolific*)
mengj@19768
   358
   "Ring_and_Field.eq_divide_eq_1", (*duplicate by symmetry*)
mengj@19768
   359
   "Ring_and_Field.field_mult_cancel_left",
mengj@19768
   360
   "Ring_and_Field.field_mult_cancel_right",
mengj@19768
   361
   "Ring_and_Field.inverse_le_iff_le_neg",
mengj@19768
   362
   "Ring_and_Field.inverse_le_iff_le",
mengj@19768
   363
   "Ring_and_Field.inverse_less_iff_less_neg",
mengj@19768
   364
   "Ring_and_Field.inverse_less_iff_less",
mengj@19768
   365
   "Ring_and_Field.le_divide_eq_1_neg", (*obscure and prolific*)
mengj@19768
   366
   "Ring_and_Field.le_divide_eq_1_pos", (*obscure and prolific*)
mengj@19768
   367
   "Ring_and_Field.less_divide_eq_1_neg", (*obscure and prolific*)
mengj@19768
   368
   "Ring_and_Field.less_divide_eq_1_pos", (*obscure and prolific*)
mengj@19768
   369
   "Ring_and_Field.one_eq_divide_iff",  (*duplicate by symmetry*)
paulson@22382
   370
   "Set.ball_simps", "Set.bex_simps",  (*quantifier rewriting: useless*)
paulson@20526
   371
   "Set.Collect_bex_eq",   (*involves an existential quantifier*)
paulson@20526
   372
   "Set.Collect_ex_eq",   (*involves an existential quantifier*)
mengj@19768
   373
   "Set.Diff_eq_empty_iff", (*redundant with paramodulation*)
mengj@19768
   374
   "Set.Diff_insert0",
paulson@20526
   375
   "Set.empty_Union_conv",   (*redundant with paramodulation*)
paulson@20526
   376
   "Set.full_SetCompr_eq",   (*involves an existential quantifier*)
paulson@22193
   377
   "Set.image_Collect",      (*involves Collect and a boolean variable...*)
paulson@20526
   378
   "Set.image_def",          (*involves an existential quantifier*)
paulson@22382
   379
   "Set.disjoint_insert", "Set.insert_disjoint",
paulson@20526
   380
   "Set.Int_UNIV",  (*redundant with paramodulation*)
paulson@22382
   381
   "Set.Inter_UNIV_conv",
paulson@20526
   382
   "Set.Inter_iff", (*We already have InterI, InterE*)
mengj@19768
   383
   "Set.psubsetE",    (*too prolific and obscure*)
mengj@19768
   384
   "Set.psubsetI",
mengj@19768
   385
   "Set.singleton_insert_inj_eq'",
mengj@19768
   386
   "Set.singleton_insert_inj_eq",
mengj@19768
   387
   "Set.singletonD",  (*these two duplicate some "insert" lemmas*)
mengj@19768
   388
   "Set.singletonI",
mengj@19768
   389
   "Set.Un_empty", (*redundant with paramodulation*)
paulson@20526
   390
   "Set.UNION_def",   (*involves an existential quantifier*)
mengj@19768
   391
   "Set.Union_empty_conv", (*redundant with paramodulation*)
mengj@19768
   392
   "Set.Union_iff",              (*We already have UnionI, UnionE*)
mengj@19768
   393
   "SetInterval.atLeastAtMost_iff", (*obscure and prolific*)
mengj@19768
   394
   "SetInterval.atLeastLessThan_iff", (*obscure and prolific*)
mengj@19768
   395
   "SetInterval.greaterThanAtMost_iff", (*obscure and prolific*)
mengj@19768
   396
   "SetInterval.greaterThanLessThan_iff", (*obscure and prolific*)
mengj@19768
   397
   "SetInterval.ivl_subset"];  (*excessive case analysis*)
mengj@19768
   398
mengj@19768
   399
(*These might be prolific but are probably OK, and min and max are basic.
wenzelm@21588
   400
   "Orderings.max_less_iff_conj",
mengj@19768
   401
   "Orderings.min_less_iff_conj",
mengj@19768
   402
   "Orderings.min_max.below_inf.below_inf_conv",
mengj@19768
   403
   "Orderings.min_max.below_sup.above_sup_conv",
mengj@19768
   404
Very prolific and somewhat obscure:
mengj@19768
   405
   "Set.InterD",
mengj@19768
   406
   "Set.UnionI",
mengj@19768
   407
*)
mengj@19768
   408
mengj@19768
   409
(*** retrieve lemmas from clasimpset and atpset, may filter them ***)
mengj@19768
   410
mengj@19768
   411
(*Hashing to detect duplicate and variant clauses, e.g. from the [iff] attribute*)
mengj@19768
   412
paulson@22382
   413
fun setinsert (x,s) = Symtab.update (x,()) s;
mengj@19768
   414
paulson@20757
   415
(*Reject theorems with names like "List.filter.filter_list_def" or
paulson@21690
   416
  "Accessible_Part.acc.defs", as these are definitions arising from packages.*)
paulson@20757
   417
fun is_package_def a =
wenzelm@21858
   418
  let val names = NameSpace.explode a
paulson@21690
   419
  in
paulson@21690
   420
     length names > 2 andalso
paulson@21690
   421
     not (hd names = "local") andalso
paulson@21690
   422
     String.isSuffix "_def" a  orelse  String.isSuffix "_defs" a
paulson@21690
   423
  end;
paulson@20757
   424
mengj@19768
   425
(** a hash function from Term.term to int, and also a hash table **)
mengj@19768
   426
val xor_words = List.foldl Word.xorb 0w0;
mengj@19768
   427
mengj@19768
   428
fun hashw_term ((Const(c,_)), w) = Polyhash.hashw_string (c,w)
paulson@20661
   429
  | hashw_term ((Free(a,_)), w) = Polyhash.hashw_string (a,w)
mengj@19768
   430
  | hashw_term ((Var(_,_)), w) = w
paulson@20661
   431
  | hashw_term ((Bound i), w) = Polyhash.hashw_int(i,w)
mengj@19768
   432
  | hashw_term ((Abs(_,_,t)), w) = hashw_term (t, w)
mengj@19768
   433
  | hashw_term ((P$Q), w) = hashw_term (Q, (hashw_term (P, w)));
mengj@19768
   434
paulson@21070
   435
fun hash_literal (Const("Not",_)$P) = Word.notb(hashw_term(P,0w0))
paulson@21070
   436
  | hash_literal P = hashw_term(P,0w0);
mengj@19768
   437
paulson@21470
   438
fun hash_term t = Word.toIntX (xor_words (map hash_literal (dest_disj t)));
mengj@19768
   439
mengj@19768
   440
fun equal_thm (thm1,thm2) = Term.aconv(prop_of thm1, prop_of thm2);
paulson@20457
   441
paulson@22382
   442
exception HASH_CLAUSE;
paulson@22382
   443
mengj@19768
   444
(*Create a hash table for clauses, of the given size*)
mengj@19768
   445
fun mk_clause_table n =
paulson@20457
   446
      Polyhash.mkTable (hash_term o prop_of, equal_thm)
mengj@19768
   447
                       (n, HASH_CLAUSE);
mengj@19768
   448
paulson@20457
   449
(*Use a hash table to eliminate duplicates from xs. Argument is a list of
paulson@20868
   450
  (thm * (string * int)) tuples. The theorems are hashed into the table. *)
wenzelm@21588
   451
fun make_unique xs =
paulson@20868
   452
  let val ht = mk_clause_table 7000
paulson@20457
   453
  in
wenzelm@22130
   454
      Output.debug (fn () => ("make_unique gets " ^ Int.toString (length xs) ^ " clauses"));
wenzelm@21588
   455
      app (ignore o Polyhash.peekInsert ht) xs;
paulson@20868
   456
      Polyhash.listItems ht
paulson@20457
   457
  end;
mengj@19768
   458
paulson@20868
   459
(*Remove existing axiom clauses from the conjecture clauses, as this can dramatically
paulson@20868
   460
  boost an ATP's performance (for some reason)*)
wenzelm@21588
   461
fun subtract_cls c_clauses ax_clauses =
paulson@20868
   462
  let val ht = mk_clause_table 2200
paulson@20868
   463
      fun known x = isSome (Polyhash.peek ht x)
paulson@20868
   464
  in
wenzelm@21588
   465
      app (ignore o Polyhash.peekInsert ht) ax_clauses;
wenzelm@21588
   466
      filter (not o known) c_clauses
paulson@20868
   467
  end;
mengj@19768
   468
wenzelm@21588
   469
(*Filter axiom clauses, but keep supplied clauses and clauses in whitelist.
paulson@20868
   470
  Duplicates are removed later.*)
paulson@20457
   471
fun get_relevant_clauses thy cls_thms white_cls goals =
paulson@20868
   472
  white_cls @ (ReduceAxiomsN.relevance_filter thy cls_thms goals);
paulson@20457
   473
paulson@21224
   474
fun all_valid_thms ctxt =
paulson@22382
   475
  let
paulson@24215
   476
    val banned_tab = foldl setinsert Symtab.empty blacklist
paulson@22382
   477
    fun blacklisted s = !run_blacklist_filter andalso
paulson@22382
   478
                        (isSome (Symtab.lookup banned_tab s) orelse is_package_def s)
paulson@22382
   479
paulson@22382
   480
    fun extern_valid space (name, ths) =
paulson@22382
   481
      let
paulson@22382
   482
        val is_valid = ProofContext.valid_thms ctxt;
paulson@22382
   483
        val xname = NameSpace.extern space name;
paulson@22382
   484
      in
paulson@22382
   485
        if blacklisted name then I
paulson@22382
   486
        else if is_valid (xname, ths) then cons (xname, ths)
paulson@22382
   487
        else if is_valid (name, ths) then cons (name, ths)
paulson@22382
   488
        else I
paulson@22382
   489
      end;
paulson@22382
   490
    val thy = ProofContext.theory_of ctxt;
paulson@22382
   491
    val all_thys = thy :: Theory.ancestors_of thy;
paulson@22382
   492
paulson@22382
   493
    fun dest_valid (space, tab) = Symtab.fold (extern_valid space) tab [];
paulson@22382
   494
  in
paulson@22382
   495
    maps (dest_valid o PureThy.theorems_of) all_thys @
paulson@22382
   496
    fold (extern_valid (#1 (ProofContext.theorems_of ctxt)))
paulson@22382
   497
      (FactIndex.find (ProofContext.fact_index_of ctxt) ([], [])) []
paulson@22382
   498
  end;
paulson@21224
   499
wenzelm@21588
   500
fun multi_name a (th, (n,pairs)) =
paulson@21224
   501
  (n+1, (a ^ "(" ^ Int.toString n ^ ")", th) :: pairs)
paulson@21224
   502
paulson@22382
   503
fun add_single_names ((a, []), pairs) = pairs
paulson@22382
   504
  | add_single_names ((a, [th]), pairs) = (a,th)::pairs
paulson@22382
   505
  | add_single_names ((a, ths), pairs) = #2 (foldl (multi_name a) (1,pairs) ths);
paulson@21431
   506
paulson@21470
   507
val multi_base_blacklist =
paulson@21470
   508
  ["defs","select_defs","update_defs","induct","inducts","split","splits","split_asm"];
paulson@21470
   509
paulson@22382
   510
(*Ignore blacklisted basenames*)
wenzelm@21588
   511
fun add_multi_names ((a, ths), pairs) =
paulson@22382
   512
  if (Sign.base_name a) mem_string multi_base_blacklist  then pairs
paulson@22382
   513
  else add_single_names ((a, ths), pairs);
paulson@21224
   514
paulson@21290
   515
fun is_multi (a, ths) = length ths > 1 orelse String.isSuffix ".axioms" a;
paulson@21290
   516
paulson@21290
   517
(*The single theorems go BEFORE the multiple ones*)
wenzelm@21588
   518
fun name_thm_pairs ctxt =
paulson@21290
   519
  let val (mults,singles) = List.partition is_multi (all_valid_thms ctxt)
paulson@22382
   520
  in  foldl add_single_names  (foldl add_multi_names [] mults) singles end;
paulson@21224
   521
paulson@21224
   522
fun check_named ("",th) = (warning ("No name for theorem " ^ string_of_thm th); false)
paulson@21224
   523
  | check_named (_,th) = true;
paulson@19894
   524
paulson@22193
   525
fun display_thm (name,th) = Output.debug (fn () => name ^ ": " ^ string_of_thm th);
paulson@22193
   526
mengj@19768
   527
(* get lemmas from claset, simpset, atpset and extra supplied rules *)
wenzelm@21588
   528
fun get_clasimp_atp_lemmas ctxt user_thms =
paulson@19894
   529
  let val included_thms =
wenzelm@21588
   530
        if !include_all
wenzelm@21588
   531
        then (tap (fn ths => Output.debug
wenzelm@22130
   532
                     (fn () => ("Including all " ^ Int.toString (length ths) ^ " theorems")))
wenzelm@21588
   533
                  (name_thm_pairs ctxt))
wenzelm@21588
   534
        else
wenzelm@21588
   535
        let val claset_thms =
wenzelm@21588
   536
                if !include_claset then ResAxioms.claset_rules_of ctxt
wenzelm@21588
   537
                else []
wenzelm@21588
   538
            val simpset_thms =
wenzelm@21588
   539
                if !include_simpset then ResAxioms.simpset_rules_of ctxt
wenzelm@21588
   540
                else []
wenzelm@21588
   541
            val atpset_thms =
wenzelm@21588
   542
                if !include_atpset then ResAxioms.atpset_rules_of ctxt
wenzelm@21588
   543
                else []
paulson@22193
   544
            val _ = (Output.debug (fn () => "ATP theorems: ");  app display_thm atpset_thms)
wenzelm@21588
   545
        in  claset_thms @ simpset_thms @ atpset_thms  end
wenzelm@21588
   546
      val user_rules = filter check_named
paulson@22382
   547
                         (map ResAxioms.pairname
paulson@24215
   548
                           (if null user_thms then whitelist else user_thms))
paulson@19894
   549
  in
paulson@21224
   550
      (filter check_named included_thms, user_rules)
paulson@19894
   551
  end;
mengj@19768
   552
paulson@21290
   553
(***************************************************************)
paulson@21290
   554
(* Type Classes Present in the Axiom or Conjecture Clauses     *)
paulson@21290
   555
(***************************************************************)
paulson@21290
   556
paulson@21290
   557
fun add_classes (sorts, cset) = foldl setinsert cset (List.concat sorts);
paulson@21290
   558
paulson@21290
   559
(*Remove this trivial type class*)
paulson@21290
   560
fun delete_type cset = Symtab.delete_safe "HOL.type" cset;
paulson@21290
   561
paulson@21290
   562
fun tvar_classes_of_terms ts =
paulson@21290
   563
  let val sorts_list = map (map #2 o term_tvars) ts
paulson@21290
   564
  in  Symtab.keys (delete_type (foldl add_classes Symtab.empty sorts_list))  end;
paulson@21290
   565
paulson@21290
   566
fun tfree_classes_of_terms ts =
paulson@21290
   567
  let val sorts_list = map (map #2 o term_tfrees) ts
paulson@21290
   568
  in  Symtab.keys (delete_type (foldl add_classes Symtab.empty sorts_list))  end;
paulson@20526
   569
paulson@21373
   570
(*fold type constructors*)
paulson@21373
   571
fun fold_type_consts f (Type (a, Ts)) x = fold (fold_type_consts f) Ts (f (a,x))
paulson@21373
   572
  | fold_type_consts f T x = x;
paulson@21373
   573
paulson@21373
   574
val add_type_consts_in_type = fold_type_consts setinsert;
paulson@21373
   575
paulson@21397
   576
(*Type constructors used to instantiate overloaded constants are the only ones needed.*)
paulson@21397
   577
fun add_type_consts_in_term thy =
paulson@21397
   578
  let val const_typargs = Sign.const_typargs thy
paulson@21397
   579
      fun add_tcs (Const cT) x = fold add_type_consts_in_type (const_typargs cT) x
paulson@21397
   580
        | add_tcs (Abs (_, T, u)) x = add_tcs u x
paulson@21397
   581
        | add_tcs (t $ u) x = add_tcs t (add_tcs u x)
paulson@21397
   582
        | add_tcs _ x = x
paulson@21397
   583
  in  add_tcs  end
paulson@21373
   584
paulson@21397
   585
fun type_consts_of_terms thy ts =
paulson@21397
   586
  Symtab.keys (fold (add_type_consts_in_term thy) ts Symtab.empty);
paulson@21373
   587
paulson@21373
   588
mengj@19194
   589
(***************************************************************)
mengj@19194
   590
(* ATP invocation methods setup                                *)
mengj@19194
   591
(***************************************************************)
mengj@19194
   592
wenzelm@21588
   593
fun cnf_hyps_thms ctxt =
wenzelm@20224
   594
    let val ths = Assumption.prems_of ctxt
wenzelm@19617
   595
    in fold (fold (insert Thm.eq_thm) o ResAxioms.skolem_thm) ths [] end;
mengj@19194
   596
paulson@20526
   597
(*Translation mode can be auto-detected, or forced to be first-order or higher-order*)
mengj@19194
   598
datatype mode = Auto | Fol | Hol;
mengj@19194
   599
paulson@19450
   600
val linkup_logic_mode = ref Auto;
paulson@19205
   601
paulson@20526
   602
(*Ensures that no higher-order theorems "leak out"*)
paulson@22382
   603
fun restrict_to_logic thy logic cls =
paulson@22382
   604
  if is_fol_logic logic then filter (Meson.is_fol_term thy o prop_of o fst) cls
wenzelm@21588
   605
                        else cls;
paulson@20526
   606
paulson@21470
   607
(**** Predicates to detect unwanted clauses (prolific or likely to cause unsoundness) ****)
paulson@21470
   608
paulson@21470
   609
(** Too general means, positive equality literal with a variable X as one operand,
paulson@21470
   610
  when X does not occur properly in the other operand. This rules out clearly
paulson@21470
   611
  inconsistent clauses such as V=a|V=b, though it by no means guarantees soundness. **)
wenzelm@21588
   612
paulson@21470
   613
fun occurs ix =
paulson@21470
   614
    let fun occ(Var (jx,_)) = (ix=jx)
paulson@21470
   615
          | occ(t1$t2)      = occ t1 orelse occ t2
paulson@21470
   616
          | occ(Abs(_,_,t)) = occ t
paulson@21470
   617
          | occ _           = false
paulson@21470
   618
    in occ end;
paulson@21470
   619
paulson@21470
   620
fun is_recordtype T = not (null (RecordPackage.dest_recTs T));
paulson@21470
   621
paulson@21470
   622
(*Unwanted equalities include
paulson@21470
   623
  (1) those between a variable that does not properly occur in the second operand,
paulson@21470
   624
  (2) those between a variable and a record, since these seem to be prolific "cases" thms
wenzelm@21588
   625
*)
paulson@21470
   626
fun too_general_eqterms (Var (ix,T), t) = not (occurs ix t) orelse is_recordtype T
paulson@21470
   627
  | too_general_eqterms _ = false;
paulson@21470
   628
paulson@21470
   629
fun too_general_equality (Const ("op =", _) $ x $ y) =
paulson@21470
   630
      too_general_eqterms (x,y) orelse too_general_eqterms(y,x)
paulson@21470
   631
  | too_general_equality _ = false;
paulson@21470
   632
paulson@21470
   633
(* tautologous? *)
paulson@21470
   634
fun is_taut (Const ("Trueprop", _) $ Const ("True", _)) = true
paulson@21470
   635
  | is_taut _ = false;
paulson@21470
   636
paulson@21431
   637
(*True if the term contains a variable whose (atomic) type is in the given list.*)
wenzelm@21588
   638
fun has_typed_var tycons =
paulson@21431
   639
  let fun var_tycon (Var (_, Type(a,_))) = a mem_string tycons
paulson@21431
   640
        | var_tycon _ = false
paulson@21431
   641
  in  exists var_tycon o term_vars  end;
paulson@21431
   642
paulson@22217
   643
(*Clauses are forbidden to contain variables of these types. The typical reason is that
paulson@22217
   644
  they lead to unsoundness. Note that "unit" satisfies numerous equations like ?X=().
paulson@22217
   645
  The resulting clause will have no type constraint, yielding false proofs. Even "bool"
paulson@22217
   646
  leads to many unsound proofs, though (obviously) only for higher-order problems.*)
paulson@24215
   647
val unwanted_types = ["Product_Type.unit","bool"];
paulson@22217
   648
paulson@21470
   649
fun unwanted t =
paulson@24215
   650
    is_taut t orelse has_typed_var unwanted_types t orelse
paulson@21470
   651
    forall too_general_equality (dest_disj t);
paulson@21470
   652
paulson@21431
   653
(*Clauses containing variables of type "unit" or "bool" are unlikely to be useful and
paulson@21431
   654
  likely to lead to unsound proofs.*)
paulson@22217
   655
fun remove_unwanted_clauses cls = filter (not o unwanted o prop_of o fst) cls;
paulson@21431
   656
paulson@23387
   657
fun tptp_writer logic = ResHolClause.tptp_write_file (logic=FOL);
paulson@19445
   658
paulson@23387
   659
fun dfg_writer logic = ResHolClause.dfg_write_file (logic=FOL);
mengj@19194
   660
paulson@20022
   661
(*Called by the oracle-based methods declared in res_atp_methods.ML*)
mengj@19722
   662
fun write_subgoal_file dfg mode ctxt conjectures user_thms n =
wenzelm@21588
   663
    let val conj_cls = make_clauses conjectures
paulson@22731
   664
                         |> ResAxioms.assume_abstract_list "subgoal" |> Meson.finish_cnf
wenzelm@21588
   665
        val hyp_cls = cnf_hyps_thms ctxt
wenzelm@21588
   666
        val goal_cls = conj_cls@hyp_cls
wenzelm@21588
   667
        val goal_tms = map prop_of goal_cls
paulson@22382
   668
        val thy = ProofContext.theory_of ctxt
wenzelm@21588
   669
        val logic = case mode of
paulson@21431
   670
                            Auto => problem_logic_goals [goal_tms]
wenzelm@21588
   671
                          | Fol => FOL
wenzelm@21588
   672
                          | Hol => HOL
wenzelm@21588
   673
        val (included_thms,user_rules) = get_clasimp_atp_lemmas ctxt user_thms
wenzelm@22865
   674
        val cla_simp_atp_clauses = included_thms
wenzelm@21588
   675
                                     |> ResAxioms.cnf_rules_pairs |> make_unique
paulson@22382
   676
                                     |> restrict_to_logic thy logic
paulson@21470
   677
                                     |> remove_unwanted_clauses
wenzelm@21588
   678
        val user_cls = ResAxioms.cnf_rules_pairs user_rules
wenzelm@21588
   679
        val axclauses = make_unique (get_relevant_clauses thy cla_simp_atp_clauses user_cls goal_tms)
paulson@21431
   680
        val subs = tfree_classes_of_terms goal_tms
paulson@21373
   681
        and axtms = map (prop_of o #1) axclauses
paulson@21373
   682
        val supers = tvar_classes_of_terms axtms
paulson@21431
   683
        and tycons = type_consts_of_terms thy (goal_tms@axtms)
paulson@21290
   684
        (*TFrees in conjecture clauses; TVars in axiom clauses*)
paulson@22645
   685
        val (supers',arity_clauses) = ResClause.make_arity_clauses thy tycons supers
paulson@22645
   686
        val classrel_clauses = ResClause.make_classrel_clauses thy subs supers'
wenzelm@21588
   687
        val writer = if dfg then dfg_writer else tptp_writer
wenzelm@21588
   688
        and file = atp_input_file()
wenzelm@21588
   689
        and user_lemmas_names = map #1 user_rules
mengj@19194
   690
    in
wenzelm@21588
   691
        writer logic goal_cls file (axclauses,classrel_clauses,arity_clauses) user_lemmas_names;
wenzelm@22130
   692
        Output.debug (fn () => "Writing to " ^ file);
wenzelm@21588
   693
        file
mengj@19194
   694
    end;
mengj@19194
   695
mengj@19194
   696
mengj@19194
   697
(**** remove tmp files ****)
wenzelm@21588
   698
fun cond_rm_tmp file =
wenzelm@22130
   699
    if !Output.debugging orelse !destdir <> ""
wenzelm@22130
   700
    then Output.debug (fn () => "ATP input kept...")
paulson@20870
   701
    else OS.FileSys.remove file;
mengj@19194
   702
mengj@19194
   703
mengj@19194
   704
(****** setup ATPs as Isabelle methods ******)
mengj@19194
   705
wenzelm@21588
   706
fun atp_meth tac ths ctxt =
mengj@19194
   707
    let val thy = ProofContext.theory_of ctxt
wenzelm@21588
   708
        val _ = ResClause.init thy
wenzelm@21588
   709
        val _ = ResHolClause.init thy
wenzelm@21588
   710
    in Method.SIMPLE_METHOD' (tac ctxt ths) end;
mengj@19194
   711
mengj@19194
   712
fun atp_method tac = Method.thms_ctxt_args (atp_meth tac);
mengj@19194
   713
mengj@19194
   714
(***************************************************************)
mengj@19194
   715
(* automatic ATP invocation                                    *)
mengj@19194
   716
(***************************************************************)
mengj@19194
   717
paulson@17306
   718
(* call prover with settings and problem file for the current subgoal *)
paulson@17764
   719
fun watcher_call_provers sign sg_terms (childin, childout, pid) =
wenzelm@16802
   720
  let
paulson@17422
   721
    fun make_atp_list [] n = []
paulson@17717
   722
      | make_atp_list (sg_term::xs) n =
wenzelm@16802
   723
          let
paulson@17717
   724
            val probfile = prob_pathname n
paulson@17690
   725
            val time = Int.toString (!time_limit)
wenzelm@16802
   726
          in
wenzelm@22130
   727
            Output.debug (fn () => "problem file in watcher_call_provers is " ^ probfile);
paulson@17764
   728
            (*options are separated by Watcher.setting_sep, currently #"%"*)
paulson@17306
   729
            if !prover = "spass"
wenzelm@16802
   730
            then
paulson@19445
   731
              let val spass = helper_path "SPASS_HOME" "SPASS"
paulson@19445
   732
                  val sopts =
paulson@19445
   733
   "-Auto%-SOS=1%-PGiven=0%-PProblem=0%-Splits=0%-FullRed=0%-DocProof%-TimeLimit=" ^ time
wenzelm@21588
   734
              in
paulson@19445
   735
                  ("spass", spass, sopts, probfile) :: make_atp_list xs (n+1)
wenzelm@16802
   736
              end
paulson@17306
   737
            else if !prover = "vampire"
wenzelm@21588
   738
            then
paulson@17819
   739
              let val vampire = helper_path "VAMPIRE_HOME" "vampire"
paulson@21132
   740
                  val vopts = "--mode casc%-t " ^ time  (*what about -m 100000?*)
wenzelm@16802
   741
              in
paulson@19445
   742
                  ("vampire", vampire, vopts, probfile) :: make_atp_list xs (n+1)
wenzelm@16802
   743
              end
wenzelm@21588
   744
             else if !prover = "E"
wenzelm@21588
   745
             then
wenzelm@21588
   746
               let val Eprover = helper_path "E_HOME" "eproof"
wenzelm@21588
   747
               in
wenzelm@21588
   748
                  ("E", Eprover,
paulson@21900
   749
                     "--tstp-in%--tstp-out%-l5%-xAutoDev%-tAutoDev%--silent%--cpu-limit=" ^ time, probfile) ::
wenzelm@21588
   750
                   make_atp_list xs (n+1)
wenzelm@21588
   751
               end
wenzelm@21588
   752
             else error ("Invalid prover name: " ^ !prover)
wenzelm@16802
   753
          end
paulson@15452
   754
paulson@17422
   755
    val atp_list = make_atp_list sg_terms 1
wenzelm@16802
   756
  in
wenzelm@16802
   757
    Watcher.callResProvers(childout,atp_list);
wenzelm@22130
   758
    Output.debug (fn () => "Sent commands to watcher!")
wenzelm@16802
   759
  end
wenzelm@21588
   760
paulson@22193
   761
(*For debugging the generated set of theorem names*)
paulson@21888
   762
fun trace_vector fname =
paulson@22193
   763
  let val path = File.explode_platform_path (fname ^ "_thm_names")
paulson@21888
   764
  in  Vector.app (File.append path o (fn s => s ^ "\n"))  end;
quigley@16357
   765
paulson@20022
   766
(*We write out problem files for each subgoal. Argument probfile generates filenames,
paulson@18986
   767
  and allows the suppression of the suffix "_1" in problem-generation mode.
paulson@18986
   768
  FIXME: does not cope with &&, and it isn't easy because one could have multiple
paulson@18986
   769
  subgoals, each involving &&.*)
paulson@20022
   770
fun write_problem_files probfile (ctxt,th)  =
paulson@18753
   771
  let val goals = Thm.prems_of th
wenzelm@22130
   772
      val _ = Output.debug (fn () => "number of subgoals = " ^ Int.toString (length goals))
paulson@17717
   773
      val thy = ProofContext.theory_of ctxt
paulson@20457
   774
      fun get_neg_subgoals [] _ = []
wenzelm@22865
   775
        | get_neg_subgoals (gl::gls) n = #1 (ResAxioms.neg_conjecture_clauses th n) ::
paulson@21999
   776
                                         get_neg_subgoals gls (n+1)
paulson@20526
   777
      val goal_cls = get_neg_subgoals goals 1
paulson@20457
   778
      val logic = case !linkup_logic_mode of
paulson@23387
   779
                Auto => problem_logic_goals (map (map prop_of) goal_cls)
wenzelm@21588
   780
              | Fol => FOL
wenzelm@21588
   781
              | Hol => HOL
paulson@20526
   782
      val (included_thms,white_thms) = get_clasimp_atp_lemmas ctxt []
paulson@22382
   783
      val included_cls = included_thms |> ResAxioms.cnf_rules_pairs |> make_unique
paulson@22382
   784
                                       |> restrict_to_logic thy logic
paulson@21470
   785
                                       |> remove_unwanted_clauses
wenzelm@22130
   786
      val _ = Output.debug (fn () => "included clauses = " ^ Int.toString(length included_cls))
paulson@20526
   787
      val white_cls = ResAxioms.cnf_rules_pairs white_thms
paulson@20526
   788
      (*clauses relevant to goal gl*)
mengj@21563
   789
      val axcls_list = map (fn ngcls => get_relevant_clauses thy included_cls white_cls (map prop_of ngcls)) goal_cls
wenzelm@22130
   790
      val _ = app (fn axcls => Output.debug (fn () => "filtered clauses = " ^ Int.toString(length axcls)))
paulson@21070
   791
                  axcls_list
wenzelm@21588
   792
      val writer = if !prover = "spass" then dfg_writer else tptp_writer
paulson@20526
   793
      fun write_all [] [] _ = []
wenzelm@21588
   794
        | write_all (ccls::ccls_list) (axcls::axcls_list) k =
paulson@20868
   795
            let val fname = probfile k
paulson@22217
   796
                val _ = Output.debug (fn () => "About to write file " ^ fname)
paulson@20868
   797
                val axcls = make_unique axcls
paulson@22217
   798
                val _ = Output.debug (fn () => "Conjecture Clauses (before duplicate removal)")
paulson@22217
   799
                val _ = app (fn th => Output.debug (fn _ => string_of_thm th)) ccls
paulson@20868
   800
                val ccls = subtract_cls ccls axcls
paulson@22217
   801
                val _ = Output.debug (fn () => "Conjecture Clauses (AFTER duplicate removal)")
paulson@22217
   802
                val _ = app (fn th => Output.debug (fn _ => string_of_thm th)) ccls
paulson@21431
   803
                val ccltms = map prop_of ccls
paulson@21373
   804
                and axtms = map (prop_of o #1) axcls
paulson@21431
   805
                val subs = tfree_classes_of_terms ccltms
paulson@21431
   806
                and supers = tvar_classes_of_terms axtms
paulson@21431
   807
                and tycons = type_consts_of_terms thy (ccltms@axtms)
paulson@21290
   808
                (*TFrees in conjecture clauses; TVars in axiom clauses*)
paulson@22645
   809
                val (supers',arity_clauses) = ResClause.make_arity_clauses thy tycons supers
paulson@22645
   810
                val _ = Output.debug (fn () => "arity clauses = " ^ Int.toString (length arity_clauses))
paulson@22645
   811
                val classrel_clauses = ResClause.make_classrel_clauses thy subs supers'
wenzelm@22130
   812
                val _ = Output.debug (fn () => "classrel clauses = " ^ Int.toString (length classrel_clauses))
paulson@20868
   813
                val clnames = writer logic ccls fname (axcls,classrel_clauses,arity_clauses) []
paulson@21888
   814
                val thm_names = Vector.fromList clnames
paulson@22193
   815
                val _ = if !Output.debugging then trace_vector fname thm_names else ()
paulson@20870
   816
            in  (thm_names,fname) :: write_all ccls_list axcls_list (k+1)  end
paulson@20870
   817
      val (thm_names_list, filenames) = ListPair.unzip (write_all goal_cls axcls_list 1)
mengj@19194
   818
  in
paulson@20870
   819
      (filenames, thm_names_list)
mengj@19194
   820
  end;
quigley@15644
   821
wenzelm@21588
   822
val last_watcher_pid = ref (NONE : (TextIO.instream * TextIO.outstream *
paulson@17775
   823
                                    Posix.Process.pid * string list) option);
paulson@17775
   824
paulson@17775
   825
fun kill_last_watcher () =
wenzelm@21588
   826
    (case !last_watcher_pid of
paulson@17775
   827
         NONE => ()
wenzelm@21588
   828
       | SOME (_, _, pid, files) =>
wenzelm@22130
   829
          (Output.debug (fn () => "Killing old watcher, pid = " ^ string_of_pid pid);
wenzelm@21588
   830
           Watcher.killWatcher pid;
wenzelm@21588
   831
           ignore (map (try cond_rm_tmp) files)))
wenzelm@22130
   832
     handle OS.SysErr _ => Output.debug (fn () => "Attempt to kill watcher failed");
paulson@17525
   833
paulson@21980
   834
(*writes out the current problems and calls ATPs*)
paulson@21980
   835
fun isar_atp (ctxt, th) =
paulson@17717
   836
  if Thm.no_prems th then ()
wenzelm@16802
   837
  else
wenzelm@16802
   838
    let
paulson@17775
   839
      val _ = kill_last_watcher()
paulson@20870
   840
      val (files,thm_names_list) = write_problem_files prob_pathname (ctxt,th)
paulson@22012
   841
      val (childin, childout, pid) = Watcher.createWatcher (ctxt, th, thm_names_list)
paulson@15608
   842
    in
paulson@17772
   843
      last_watcher_pid := SOME (childin, childout, pid, files);
wenzelm@22130
   844
      Output.debug (fn () => "problem files: " ^ space_implode ", " files);
wenzelm@22130
   845
      Output.debug (fn () => "pid: " ^ string_of_pid pid);
wenzelm@22578
   846
      watcher_call_provers (Thm.theory_of_thm th) (Thm.prems_of th) (childin, childout, pid)
paulson@20954
   847
    end;
paulson@20954
   848
paulson@20954
   849
(*For ML scripts, and primarily, for debugging*)
wenzelm@21588
   850
fun callatp () =
paulson@20954
   851
  let val th = topthm()
paulson@20954
   852
      val ctxt = ProofContext.init (theory_of_thm th)
paulson@21980
   853
  in  isar_atp (ctxt, th)  end;
paulson@15608
   854
wenzelm@21588
   855
val isar_atp_writeonly = setmp print_mode []
paulson@17717
   856
      (fn (ctxt,th) =>
paulson@17717
   857
       if Thm.no_prems th then ()
wenzelm@21588
   858
       else
wenzelm@21588
   859
         let val probfile = if Thm.nprems_of th = 1 then probfile_nosuffix
wenzelm@21588
   860
                            else prob_pathname
paulson@20022
   861
         in ignore (write_problem_files probfile (ctxt,th)) end);
paulson@15452
   862
quigley@16357
   863
wenzelm@22865
   864
(** the Isar toplevel command **)
wenzelm@16802
   865
wenzelm@22865
   866
fun sledgehammer state =
wenzelm@22865
   867
  let
wenzelm@22865
   868
    val (ctxt, (_, goal)) = Proof.get_goal (Toplevel.proof_of state);
wenzelm@22865
   869
    val thy = ProofContext.theory_of ctxt;
wenzelm@16802
   870
  in
wenzelm@22130
   871
    Output.debug (fn () => "subgoals in isar_atp:\n" ^
wenzelm@21588
   872
                  Pretty.string_of (ProofContext.pretty_term ctxt
wenzelm@21588
   873
                    (Logic.mk_conjunction_list (Thm.prems_of goal))));
wenzelm@22130
   874
    Output.debug (fn () => "current theory: " ^ Context.theory_name thy);
paulson@16925
   875
    ResClause.init thy;
mengj@19194
   876
    ResHolClause.init thy;
paulson@21132
   877
    if !time_limit > 0 then isar_atp (ctxt, goal)
wenzelm@22865
   878
    else (warning ("Writing problem file only: " ^ !problem_name);
paulson@22193
   879
          isar_atp_writeonly (ctxt, goal))
paulson@19205
   880
  end;
paulson@19205
   881
wenzelm@22865
   882
val _ = OuterSyntax.add_parsers
wenzelm@22865
   883
  [OuterSyntax.command "sledgehammer" "call automatic theorem provers" OuterKeyword.diag
wenzelm@22865
   884
    (Scan.succeed (Toplevel.no_timing o Toplevel.unknown_proof o Toplevel.keep sledgehammer))];
paulson@17091
   885
paulson@15347
   886
end;