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