src/HOL/Tools/res_atp.ML
author paulson
Fri Oct 05 09:59:03 2007 +0200 (2007-10-05)
changeset 24854 0ebcd575d3c6
parent 24827 646bdc51eb7d
child 24867 e5b55d7be9bb
permissions -rw-r--r--
filtering out some package theorems
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@24425
    10
  val prover: ResReconstruct.atp 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
mengj@19194
    20
  val cond_rm_tmp: string -> unit
paulson@20246
    21
  val include_all: bool ref
mengj@19194
    22
  val run_relevance_filter: bool ref
mengj@19768
    23
  val run_blacklist_filter: bool ref
paulson@24287
    24
  val theory_const : bool ref
paulson@24287
    25
  val pass_mark    : real ref
paulson@24287
    26
  val convergence  : real ref
paulson@24287
    27
  val max_new      : int ref
paulson@24287
    28
  val follow_defs  : bool ref
paulson@19894
    29
  val add_all : unit -> unit
mengj@19227
    30
  val add_claset : unit -> unit
mengj@19227
    31
  val add_simpset : unit -> unit
mengj@19227
    32
  val add_clasimp : unit -> unit
mengj@19227
    33
  val add_atpset : unit -> unit
paulson@19894
    34
  val rm_all : unit -> unit
mengj@19227
    35
  val rm_claset : unit -> unit
mengj@19227
    36
  val rm_simpset : unit -> unit
mengj@19227
    37
  val rm_atpset : unit -> unit
mengj@19227
    38
  val rm_clasimp : unit -> unit
mengj@21311
    39
  val is_fol_thms : thm list -> bool
paulson@22989
    40
  val tvar_classes_of_terms : term list -> string list
paulson@22989
    41
  val tfree_classes_of_terms : term list -> string list
paulson@22989
    42
  val type_consts_of_terms : theory -> term list -> string list
paulson@15347
    43
end;
paulson@15347
    44
wenzelm@22865
    45
structure ResAtp: RES_ATP =
paulson@15347
    46
struct
paulson@15347
    47
paulson@24425
    48
structure Recon = ResReconstruct;
paulson@24425
    49
wenzelm@22130
    50
fun timestamp s = Output.debug (fn () => ("At " ^ Time.toString (Time.now()) ^ ": " ^ s));
paulson@21070
    51
mengj@19194
    52
(********************************************************************)
mengj@19194
    53
(* some settings for both background automatic ATP calling procedure*)
mengj@19194
    54
(* and also explicit ATP invocation methods                         *)
mengj@19194
    55
(********************************************************************)
mengj@19194
    56
mengj@19194
    57
(*** background linkup ***)
paulson@24287
    58
val run_blacklist_filter = ref true;
paulson@21224
    59
val time_limit = ref 60;
paulson@24425
    60
val prover = ref Recon.E;
paulson@21224
    61
paulson@24287
    62
(*** relevance filter parameters ***)
paulson@24287
    63
val run_relevance_filter = ref true;
paulson@24287
    64
val theory_const = ref true;
paulson@24287
    65
val pass_mark = ref 0.5;
paulson@24287
    66
val convergence = ref 3.2;    (*Higher numbers allow longer inference chains*)
paulson@24287
    67
val max_new = ref 60;         (*Limits how many clauses can be picked up per stage*)
paulson@24287
    68
val follow_defs = ref false;  (*Follow definitions. Makes problems bigger.*)
paulson@24287
    69
wenzelm@21588
    70
fun set_prover atp =
paulson@21224
    71
  case String.map Char.toLower atp of
wenzelm@21588
    72
      "e" =>
paulson@24287
    73
          (max_new := 100;
paulson@24287
    74
           theory_const := false;
paulson@24425
    75
           prover := Recon.E)
wenzelm@21588
    76
    | "spass" =>
paulson@24287
    77
          (max_new := 40;
paulson@24287
    78
           theory_const := true;
paulson@24425
    79
           prover := Recon.SPASS)
wenzelm@21588
    80
    | "vampire" =>
paulson@24287
    81
          (max_new := 60;
paulson@24287
    82
           theory_const := false;
paulson@24425
    83
           prover := Recon.Vampire)
paulson@21224
    84
    | _ => error ("No such prover: " ^ atp);
paulson@21224
    85
paulson@21224
    86
val _ = set_prover "E"; (* use E as the default prover *)
paulson@21224
    87
paulson@17484
    88
val destdir = ref "";   (*Empty means write files to /tmp*)
paulson@17484
    89
val problem_name = ref "prob";
paulson@17484
    90
paulson@17819
    91
(*Return the path to a "helper" like SPASS or tptp2X, first checking that
wenzelm@21588
    92
  it exists.  FIXME: modify to use Path primitives and move to some central place.*)
paulson@17819
    93
fun helper_path evar base =
paulson@17819
    94
  case getenv evar of
paulson@17819
    95
      "" => error  ("Isabelle environment variable " ^ evar ^ " not defined")
wenzelm@21588
    96
    | home =>
paulson@17819
    97
        let val path = home ^ "/" ^ base
wenzelm@21858
    98
        in  if File.exists (File.explode_platform_path path) then path
wenzelm@21588
    99
            else error ("Could not find the file " ^ path)
wenzelm@21588
   100
        end;
paulson@17819
   101
wenzelm@21588
   102
fun probfile_nosuffix _ =
paulson@17484
   103
  if !destdir = "" then File.platform_path (File.tmp_path (Path.basic (!problem_name)))
wenzelm@21858
   104
  else if File.exists (File.explode_platform_path (!destdir))
paulson@17484
   105
  then !destdir ^ "/" ^ !problem_name
paulson@17484
   106
  else error ("No such directory: " ^ !destdir);
quigley@15644
   107
paulson@17717
   108
fun prob_pathname n = probfile_nosuffix n ^ "_" ^ Int.toString n;
paulson@17717
   109
mengj@19194
   110
fun atp_input_file () =
wenzelm@21588
   111
    let val file = !problem_name
mengj@19194
   112
    in
wenzelm@21588
   113
        if !destdir = "" then File.platform_path (File.tmp_path (Path.basic file))
wenzelm@21858
   114
        else if File.exists (File.explode_platform_path (!destdir))
wenzelm@21588
   115
        then !destdir ^ "/" ^ file
wenzelm@21588
   116
        else error ("No such directory: " ^ !destdir)
mengj@19194
   117
    end;
mengj@19194
   118
paulson@20868
   119
val include_all = ref true;
mengj@19194
   120
val include_simpset = ref false;
wenzelm@21588
   121
val include_claset = ref false;
mengj@19194
   122
val include_atpset = ref true;
paulson@20246
   123
paulson@20246
   124
(*Tests show that follow_defs gives VERY poor results with "include_all"*)
paulson@24287
   125
fun add_all() = (include_all:=true; follow_defs := false);
paulson@20246
   126
fun rm_all() = include_all:=false;
paulson@20246
   127
paulson@20246
   128
fun add_simpset() = include_simpset:=true;
paulson@20246
   129
fun rm_simpset() = include_simpset:=false;
paulson@20246
   130
paulson@20246
   131
fun add_claset() = include_claset:=true;
paulson@20246
   132
fun rm_claset() = include_claset:=false;
paulson@20246
   133
paulson@20246
   134
fun add_clasimp() = (include_simpset:=true;include_claset:=true);
paulson@20246
   135
fun rm_clasimp() = (include_simpset:=false;include_claset:=false);
paulson@20246
   136
paulson@20246
   137
fun add_atpset() = include_atpset:=true;
paulson@20246
   138
fun rm_atpset() = include_atpset:=false;
mengj@19194
   139
mengj@19194
   140
mengj@19194
   141
(******************************************************************)
mengj@19194
   142
(* detect whether a given problem (clauses) is FOL/HOL/HOLC/HOLCS *)
mengj@19194
   143
(******************************************************************)
mengj@19194
   144
mengj@19194
   145
datatype logic = FOL | HOL | HOLC | HOLCS;
mengj@19194
   146
mengj@19194
   147
fun string_of_logic FOL = "FOL"
mengj@19194
   148
  | string_of_logic HOL = "HOL"
mengj@19194
   149
  | string_of_logic HOLC = "HOLC"
mengj@19194
   150
  | string_of_logic HOLCS = "HOLCS";
mengj@19194
   151
mengj@19194
   152
fun is_fol_logic FOL = true
mengj@19194
   153
  | is_fol_logic  _ = false
mengj@19194
   154
mengj@19194
   155
(*HOLCS will not occur here*)
mengj@19194
   156
fun upgrade_lg HOLC _ = HOLC
mengj@19194
   157
  | upgrade_lg HOL HOLC = HOLC
mengj@19194
   158
  | upgrade_lg HOL _ = HOL
wenzelm@21588
   159
  | upgrade_lg FOL lg = lg;
mengj@19194
   160
mengj@19194
   161
(* check types *)
mengj@19451
   162
fun has_bool_hfn (Type("bool",_)) = true
mengj@19451
   163
  | has_bool_hfn (Type("fun",_)) = true
mengj@19451
   164
  | has_bool_hfn (Type(_, Ts)) = exists has_bool_hfn Ts
mengj@19451
   165
  | has_bool_hfn _ = false;
mengj@19194
   166
mengj@19451
   167
fun is_hol_fn tp =
mengj@19194
   168
    let val (targs,tr) = strip_type tp
mengj@19194
   169
    in
wenzelm@21588
   170
        exists (has_bool_hfn) (tr::targs)
mengj@19194
   171
    end;
mengj@19194
   172
mengj@19451
   173
fun is_hol_pred tp =
mengj@19451
   174
    let val (targs,tr) = strip_type tp
mengj@19451
   175
    in
wenzelm@21588
   176
        exists (has_bool_hfn) targs
mengj@19451
   177
    end;
mengj@19194
   178
mengj@19194
   179
exception FN_LG of term;
mengj@19194
   180
wenzelm@21588
   181
fun fn_lg (t as Const(f,tp)) (lg,seen) =
wenzelm@21588
   182
    if is_hol_fn tp then (upgrade_lg HOL lg, insert (op =) t seen) else (lg, insert (op =) t seen)
wenzelm@21588
   183
  | fn_lg (t as Free(f,tp)) (lg,seen) =
wenzelm@21588
   184
    if is_hol_fn tp then (upgrade_lg HOL lg, insert (op =) t seen) else (lg, insert (op =) t seen)
mengj@19194
   185
  | fn_lg (t as Var(f,tp)) (lg,seen) =
haftmann@20854
   186
    if is_hol_fn tp then (upgrade_lg HOL lg,insert (op =) t seen) else (lg,insert (op =) t seen)
haftmann@20854
   187
  | fn_lg (t as Abs(_,_,_)) (lg,seen) = (upgrade_lg HOLC lg,insert (op =) t seen)
wenzelm@21588
   188
  | fn_lg f _ = raise FN_LG(f);
mengj@19194
   189
mengj@19194
   190
mengj@19194
   191
fun term_lg [] (lg,seen) = (lg,seen)
mengj@19194
   192
  | term_lg (tm::tms) (FOL,seen) =
paulson@20457
   193
      let val (f,args) = strip_comb tm
wenzelm@21588
   194
          val (lg',seen') = if f mem seen then (FOL,seen)
wenzelm@21588
   195
                            else fn_lg f (FOL,seen)
paulson@20457
   196
      in
wenzelm@21588
   197
        if is_fol_logic lg' then ()
wenzelm@22130
   198
        else Output.debug (fn () => ("Found a HOL term: " ^ Display.raw_string_of_term f));
paulson@20457
   199
        term_lg (args@tms) (lg',seen')
paulson@20457
   200
      end
mengj@19194
   201
  | term_lg _ (lg,seen) = (lg,seen)
mengj@19194
   202
mengj@19194
   203
exception PRED_LG of term;
mengj@19194
   204
wenzelm@21588
   205
fun pred_lg (t as Const(P,tp)) (lg,seen)=
wenzelm@21588
   206
      if is_hol_pred tp then (upgrade_lg HOL lg, insert (op =) t seen)
wenzelm@21588
   207
      else (lg,insert (op =) t seen)
mengj@19194
   208
  | pred_lg (t as Free(P,tp)) (lg,seen) =
wenzelm@21588
   209
      if is_hol_pred tp then (upgrade_lg HOL lg, insert (op =) t seen)
paulson@21470
   210
      else (lg,insert (op =) t seen)
haftmann@20854
   211
  | pred_lg (t as Var(_,_)) (lg,seen) = (upgrade_lg HOL lg, insert (op =) t seen)
mengj@19194
   212
  | pred_lg P _ = raise PRED_LG(P);
mengj@19194
   213
mengj@19194
   214
mengj@19194
   215
fun lit_lg (Const("Not",_) $ P) (lg,seen) = lit_lg P (lg,seen)
mengj@19194
   216
  | lit_lg P (lg,seen) =
paulson@20457
   217
      let val (pred,args) = strip_comb P
wenzelm@21588
   218
          val (lg',seen') = if pred mem seen then (lg,seen)
wenzelm@21588
   219
                            else pred_lg pred (lg,seen)
paulson@20457
   220
      in
wenzelm@21588
   221
        if is_fol_logic lg' then ()
wenzelm@22130
   222
        else Output.debug (fn () => ("Found a HOL predicate: " ^ Display.raw_string_of_term pred));
wenzelm@21588
   223
        term_lg args (lg',seen')
paulson@20457
   224
      end;
mengj@19194
   225
mengj@19194
   226
fun lits_lg [] (lg,seen) = (lg,seen)
mengj@19194
   227
  | lits_lg (lit::lits) (FOL,seen) =
paulson@20457
   228
      let val (lg,seen') = lit_lg lit (FOL,seen)
paulson@20457
   229
      in
wenzelm@21588
   230
        if is_fol_logic lg then ()
wenzelm@22130
   231
        else Output.debug (fn () => ("Found a HOL literal: " ^ Display.raw_string_of_term lit));
wenzelm@21588
   232
        lits_lg lits (lg,seen')
paulson@20457
   233
      end
mengj@19194
   234
  | lits_lg lits (lg,seen) = (lg,seen);
mengj@19194
   235
paulson@21470
   236
fun dest_disj_aux (Const("Trueprop",_) $ t) disjs = dest_disj_aux t disjs
paulson@21470
   237
  | dest_disj_aux (Const ("op |", _) $ t $ t') disjs = dest_disj_aux t (dest_disj_aux t' disjs)
mengj@19227
   238
  | dest_disj_aux t disjs = t::disjs;
mengj@19227
   239
mengj@19227
   240
fun dest_disj t = dest_disj_aux t [];
mengj@19227
   241
paulson@21470
   242
fun logic_of_clause tm = lits_lg (dest_disj tm);
mengj@19194
   243
mengj@19194
   244
fun logic_of_clauses [] (lg,seen) = (lg,seen)
mengj@19194
   245
  | logic_of_clauses (cls::clss) (FOL,seen) =
mengj@19227
   246
    let val (lg,seen') = logic_of_clause cls (FOL,seen)
wenzelm@21588
   247
        val _ =
wenzelm@19641
   248
          if is_fol_logic lg then ()
wenzelm@22130
   249
          else Output.debug (fn () => ("Found a HOL clause: " ^ Display.raw_string_of_term cls))
mengj@19227
   250
    in
wenzelm@21588
   251
        logic_of_clauses clss (lg,seen')
mengj@19227
   252
    end
mengj@19194
   253
  | logic_of_clauses (cls::clss) (lg,seen) = (lg,seen);
mengj@19194
   254
mengj@19194
   255
fun problem_logic_goals_aux [] (lg,seen) = lg
wenzelm@21588
   256
  | problem_logic_goals_aux (subgoal::subgoals) (lg,seen) =
mengj@19194
   257
    problem_logic_goals_aux subgoals (logic_of_clauses subgoal (lg,seen));
wenzelm@21588
   258
mengj@19194
   259
fun problem_logic_goals subgoals = problem_logic_goals_aux subgoals (FOL,[]);
mengj@19194
   260
mengj@21311
   261
fun is_fol_thms ths = ((fst(logic_of_clauses (map prop_of ths) (FOL,[]))) = FOL);
mengj@21311
   262
mengj@19768
   263
(***************************************************************)
paulson@24287
   264
(* Relevance Filtering                                         *)
paulson@24287
   265
(***************************************************************)
paulson@24287
   266
paulson@24287
   267
(*A surprising number of theorems contain only a few significant constants.
paulson@24287
   268
  These include all induction rules, and other general theorems. Filtering
paulson@24287
   269
  theorems in clause form reveals these complexities in the form of Skolem 
paulson@24287
   270
  functions. If we were instead to filter theorems in their natural form,
paulson@24287
   271
  some other method of measuring theorem complexity would become necessary.*)
paulson@24287
   272
paulson@24287
   273
fun log_weight2 (x:real) = 1.0 + 2.0/Math.ln (x+1.0);
paulson@24287
   274
paulson@24287
   275
(*The default seems best in practice. A constant function of one ignores
paulson@24287
   276
  the constant frequencies.*)
paulson@24287
   277
val weight_fn = ref log_weight2;
paulson@24287
   278
paulson@24287
   279
paulson@24287
   280
(*Including equality in this list might be expected to stop rules like subset_antisym from
paulson@24287
   281
  being chosen, but for some reason filtering works better with them listed. The
paulson@24287
   282
  logical signs All, Ex, &, and --> are omitted because any remaining occurrrences
paulson@24287
   283
  must be within comprehensions.*)
paulson@24287
   284
val standard_consts = ["Trueprop","==>","all","==","op |","Not","op ="];
paulson@24287
   285
paulson@24287
   286
paulson@24287
   287
(*** constants with types ***)
paulson@24287
   288
paulson@24287
   289
(*An abstraction of Isabelle types*)
paulson@24287
   290
datatype const_typ =  CTVar | CType of string * const_typ list
paulson@24287
   291
paulson@24287
   292
(*Is the second type an instance of the first one?*)
paulson@24287
   293
fun match_type (CType(con1,args1)) (CType(con2,args2)) = 
paulson@24287
   294
      con1=con2 andalso match_types args1 args2
paulson@24287
   295
  | match_type CTVar _ = true
paulson@24287
   296
  | match_type _ CTVar = false
paulson@24287
   297
and match_types [] [] = true
paulson@24287
   298
  | match_types (a1::as1) (a2::as2) = match_type a1 a2 andalso match_types as1 as2;
paulson@24287
   299
paulson@24287
   300
(*Is there a unifiable constant?*)
paulson@24287
   301
fun uni_mem gctab (c,c_typ) =
paulson@24287
   302
  case Symtab.lookup gctab c of
paulson@24287
   303
      NONE => false
paulson@24287
   304
    | SOME ctyps_list => exists (match_types c_typ) ctyps_list;
paulson@24287
   305
  
paulson@24287
   306
(*Maps a "real" type to a const_typ*)
paulson@24287
   307
fun const_typ_of (Type (c,typs)) = CType (c, map const_typ_of typs) 
paulson@24287
   308
  | const_typ_of (TFree _) = CTVar
paulson@24287
   309
  | const_typ_of (TVar _) = CTVar
paulson@24287
   310
paulson@24287
   311
(*Pairs a constant with the list of its type instantiations (using const_typ)*)
paulson@24287
   312
fun const_with_typ thy (c,typ) = 
paulson@24287
   313
    let val tvars = Sign.const_typargs thy (c,typ)
paulson@24287
   314
    in (c, map const_typ_of tvars) end
paulson@24287
   315
    handle TYPE _ => (c,[]);   (*Variable (locale constant): monomorphic*)   
paulson@24287
   316
paulson@24287
   317
(*Add a const/type pair to the table, but a [] entry means a standard connective,
paulson@24287
   318
  which we ignore.*)
paulson@24287
   319
fun add_const_typ_table ((c,ctyps), tab) =
paulson@24287
   320
  Symtab.map_default (c, [ctyps]) (fn [] => [] | ctyps_list => insert (op =) ctyps ctyps_list) 
paulson@24287
   321
    tab;
paulson@24287
   322
paulson@24287
   323
(*Free variables are included, as well as constants, to handle locales*)
paulson@24287
   324
fun add_term_consts_typs_rm thy (Const(c, typ), tab) =
paulson@24287
   325
      add_const_typ_table (const_with_typ thy (c,typ), tab) 
paulson@24287
   326
  | add_term_consts_typs_rm thy (Free(c, typ), tab) =
paulson@24287
   327
      add_const_typ_table (const_with_typ thy (c,typ), tab) 
paulson@24287
   328
  | add_term_consts_typs_rm thy (t $ u, tab) =
paulson@24287
   329
      add_term_consts_typs_rm thy (t, add_term_consts_typs_rm thy (u, tab))
paulson@24287
   330
  | add_term_consts_typs_rm thy (Abs(_,_,t), tab) = add_term_consts_typs_rm thy (t, tab)
paulson@24287
   331
  | add_term_consts_typs_rm thy (_, tab) = tab;
paulson@24287
   332
paulson@24287
   333
(*The empty list here indicates that the constant is being ignored*)
paulson@24287
   334
fun add_standard_const (s,tab) = Symtab.update (s,[]) tab;
paulson@24287
   335
paulson@24287
   336
val null_const_tab : const_typ list list Symtab.table = 
paulson@24287
   337
    foldl add_standard_const Symtab.empty standard_consts;
paulson@24287
   338
paulson@24287
   339
fun get_goal_consts_typs thy = foldl (add_term_consts_typs_rm thy) null_const_tab;
paulson@24287
   340
paulson@24287
   341
(*Inserts a dummy "constant" referring to the theory name, so that relevance
paulson@24287
   342
  takes the given theory into account.*)
paulson@24287
   343
fun const_prop_of th =
paulson@24287
   344
 if !theory_const then
paulson@24287
   345
  let val name = Context.theory_name (theory_of_thm th)
paulson@24287
   346
      val t = Const (name ^ ". 1", HOLogic.boolT)
paulson@24287
   347
  in  t $ prop_of th  end
paulson@24287
   348
 else prop_of th;
paulson@24287
   349
paulson@24287
   350
(**** Constant / Type Frequencies ****)
paulson@24287
   351
paulson@24287
   352
(*A two-dimensional symbol table counts frequencies of constants. It's keyed first by
paulson@24287
   353
  constant name and second by its list of type instantiations. For the latter, we need
paulson@24287
   354
  a linear ordering on type const_typ list.*)
paulson@24287
   355
  
paulson@24287
   356
local
paulson@24287
   357
paulson@24287
   358
fun cons_nr CTVar = 0
paulson@24287
   359
  | cons_nr (CType _) = 1;
paulson@24287
   360
paulson@24287
   361
in
paulson@24287
   362
paulson@24287
   363
fun const_typ_ord TU =
paulson@24287
   364
  case TU of
paulson@24287
   365
    (CType (a, Ts), CType (b, Us)) =>
paulson@24287
   366
      (case fast_string_ord(a,b) of EQUAL => dict_ord const_typ_ord (Ts,Us) | ord => ord)
paulson@24287
   367
  | (T, U) => int_ord (cons_nr T, cons_nr U);
paulson@24287
   368
paulson@24287
   369
end;
paulson@24287
   370
paulson@24287
   371
structure CTtab = TableFun(type key = const_typ list val ord = dict_ord const_typ_ord);
paulson@24287
   372
paulson@24287
   373
fun count_axiom_consts thy ((thm,_), tab) = 
paulson@24287
   374
  let fun count_const (a, T, tab) =
paulson@24287
   375
	let val (c, cts) = const_with_typ thy (a,T)
paulson@24287
   376
	in  (*Two-dimensional table update. Constant maps to types maps to count.*)
paulson@24287
   377
	    Symtab.map_default (c, CTtab.empty) 
paulson@24287
   378
	                       (CTtab.map_default (cts,0) (fn n => n+1)) tab
paulson@24287
   379
	end
paulson@24287
   380
      fun count_term_consts (Const(a,T), tab) = count_const(a,T,tab)
paulson@24287
   381
	| count_term_consts (Free(a,T), tab) = count_const(a,T,tab)
paulson@24287
   382
	| count_term_consts (t $ u, tab) =
paulson@24287
   383
	    count_term_consts (t, count_term_consts (u, tab))
paulson@24287
   384
	| count_term_consts (Abs(_,_,t), tab) = count_term_consts (t, tab)
paulson@24287
   385
	| count_term_consts (_, tab) = tab
paulson@24287
   386
  in  count_term_consts (const_prop_of thm, tab)  end;
paulson@24287
   387
paulson@24287
   388
paulson@24287
   389
(**** Actual Filtering Code ****)
paulson@24287
   390
paulson@24287
   391
(*The frequency of a constant is the sum of those of all instances of its type.*)
paulson@24287
   392
fun const_frequency ctab (c, cts) =
paulson@24287
   393
  let val pairs = CTtab.dest (the (Symtab.lookup ctab c))
paulson@24287
   394
      fun add ((cts',m), n) = if match_types cts cts' then m+n else n
paulson@24287
   395
  in  List.foldl add 0 pairs  end;
paulson@24287
   396
paulson@24287
   397
(*Add in a constant's weight, as determined by its frequency.*)
paulson@24287
   398
fun add_ct_weight ctab ((c,T), w) =
paulson@24287
   399
  w + !weight_fn (real (const_frequency ctab (c,T)));
paulson@24287
   400
paulson@24287
   401
(*Relevant constants are weighted according to frequency, 
paulson@24287
   402
  but irrelevant constants are simply counted. Otherwise, Skolem functions,
paulson@24287
   403
  which are rare, would harm a clause's chances of being picked.*)
paulson@24287
   404
fun clause_weight ctab gctyps consts_typs =
paulson@24287
   405
    let val rel = filter (uni_mem gctyps) consts_typs
paulson@24287
   406
        val rel_weight = List.foldl (add_ct_weight ctab) 0.0 rel
paulson@24287
   407
    in
paulson@24287
   408
	rel_weight / (rel_weight + real (length consts_typs - length rel))
paulson@24287
   409
    end;
paulson@24287
   410
    
paulson@24287
   411
(*Multiplies out to a list of pairs: 'a * 'b list -> ('a * 'b) list -> ('a * 'b) list*)
paulson@24287
   412
fun add_expand_pairs (x,ys) xys = foldl (fn (y,acc) => (x,y)::acc) xys ys;
paulson@24287
   413
paulson@24287
   414
fun consts_typs_of_term thy t = 
paulson@24287
   415
  let val tab = add_term_consts_typs_rm thy (t, null_const_tab)
paulson@24287
   416
  in  Symtab.fold add_expand_pairs tab []  end;
paulson@24287
   417
paulson@24287
   418
fun pair_consts_typs_axiom thy (thm,name) =
paulson@24287
   419
    ((thm,name), (consts_typs_of_term thy (const_prop_of thm)));
paulson@24287
   420
paulson@24287
   421
exception ConstFree;
paulson@24287
   422
fun dest_ConstFree (Const aT) = aT
paulson@24287
   423
  | dest_ConstFree (Free aT) = aT
paulson@24287
   424
  | dest_ConstFree _ = raise ConstFree;
paulson@24287
   425
paulson@24287
   426
(*Look for definitions of the form f ?x1 ... ?xn = t, but not reversed.*)
paulson@24287
   427
fun defines thy (thm,(name,n)) gctypes =
paulson@24287
   428
    let val tm = prop_of thm
paulson@24287
   429
	fun defs lhs rhs =
paulson@24287
   430
            let val (rator,args) = strip_comb lhs
paulson@24287
   431
		val ct = const_with_typ thy (dest_ConstFree rator)
paulson@24287
   432
            in  forall is_Var args andalso uni_mem gctypes ct andalso
paulson@24287
   433
                Term.add_vars rhs [] subset Term.add_vars lhs []
paulson@24287
   434
            end
paulson@24287
   435
	    handle ConstFree => false
paulson@24287
   436
    in    
paulson@24287
   437
	case tm of Const ("Trueprop",_) $ (Const("op =",_) $ lhs $ rhs) => 
paulson@24287
   438
		   defs lhs rhs andalso
paulson@24287
   439
		   (Output.debug (fn () => "Definition found: " ^ name ^ "_" ^ Int.toString n); true)
paulson@24287
   440
		 | _ => false
paulson@24287
   441
    end;
paulson@24287
   442
paulson@24287
   443
type annotd_cls = (thm * (string * int)) * ((string * const_typ list) list);
paulson@24287
   444
       
paulson@24287
   445
(*For a reverse sort, putting the largest values first.*)
paulson@24287
   446
fun compare_pairs ((_,w1),(_,w2)) = Real.compare (w2,w1);
paulson@24287
   447
paulson@24287
   448
(*Limit the number of new clauses, to prevent runaway acceptance.*)
paulson@24287
   449
fun take_best (newpairs : (annotd_cls*real) list) =
paulson@24287
   450
  let val nnew = length newpairs
paulson@24287
   451
  in
paulson@24287
   452
    if nnew <= !max_new then (map #1 newpairs, [])
paulson@24287
   453
    else 
paulson@24287
   454
      let val cls = sort compare_pairs newpairs
paulson@24287
   455
          val accepted = List.take (cls, !max_new)
paulson@24287
   456
      in
paulson@24287
   457
        Output.debug (fn () => ("Number of candidates, " ^ Int.toString nnew ^ 
paulson@24287
   458
		       ", exceeds the limit of " ^ Int.toString (!max_new)));
paulson@24287
   459
        Output.debug (fn () => ("Effective pass mark: " ^ Real.toString (#2 (List.last accepted))));
paulson@24287
   460
        Output.debug (fn () => "Actually passed: " ^
paulson@24287
   461
          space_implode ", " (map (fn (((_,(name,_)),_),_) => name) accepted));
paulson@24287
   462
paulson@24287
   463
	(map #1 accepted, map #1 (List.drop (cls, !max_new)))
paulson@24287
   464
      end
paulson@24287
   465
  end;
paulson@24287
   466
paulson@24287
   467
fun relevant_clauses thy ctab p rel_consts =
paulson@24287
   468
  let fun relevant ([],_) [] = [] : (thm * (string * int)) list  (*Nothing added this iteration*)
paulson@24287
   469
	| relevant (newpairs,rejects) [] =
paulson@24287
   470
	    let val (newrels,more_rejects) = take_best newpairs
paulson@24287
   471
		val new_consts = List.concat (map #2 newrels)
paulson@24287
   472
		val rel_consts' = foldl add_const_typ_table rel_consts new_consts
paulson@24287
   473
		val newp = p + (1.0-p) / !convergence
paulson@24287
   474
	    in
paulson@24287
   475
              Output.debug (fn () => ("relevant this iteration: " ^ Int.toString (length newrels)));
paulson@24287
   476
	       (map #1 newrels) @ 
paulson@24287
   477
	       (relevant_clauses thy ctab newp rel_consts' (more_rejects@rejects))
paulson@24287
   478
	    end
paulson@24287
   479
	| relevant (newrels,rejects) ((ax as (clsthm as (_,(name,n)),consts_typs)) :: axs) =
paulson@24287
   480
	    let val weight = clause_weight ctab rel_consts consts_typs
paulson@24287
   481
	    in
paulson@24287
   482
	      if p <= weight orelse (!follow_defs andalso defines thy clsthm rel_consts)
paulson@24287
   483
	      then (Output.debug (fn () => (name ^ " clause " ^ Int.toString n ^ 
paulson@24287
   484
	                                    " passes: " ^ Real.toString weight));
paulson@24287
   485
	            relevant ((ax,weight)::newrels, rejects) axs)
paulson@24287
   486
	      else relevant (newrels, ax::rejects) axs
paulson@24287
   487
	    end
paulson@24287
   488
    in  Output.debug (fn () => ("relevant_clauses, current pass mark = " ^ Real.toString p));
paulson@24287
   489
        relevant ([],[]) 
paulson@24287
   490
    end;
paulson@24287
   491
	
paulson@24287
   492
fun relevance_filter thy axioms goals = 
paulson@24287
   493
 if !run_relevance_filter andalso !pass_mark >= 0.1
paulson@24287
   494
 then
paulson@24287
   495
  let val _ = Output.debug (fn () => "Start of relevance filtering");
paulson@24287
   496
      val const_tab = List.foldl (count_axiom_consts thy) Symtab.empty axioms
paulson@24287
   497
      val goal_const_tab = get_goal_consts_typs thy goals
paulson@24287
   498
      val _ = Output.debug (fn () => ("Initial constants: " ^
paulson@24287
   499
                                 space_implode ", " (Symtab.keys goal_const_tab)));
paulson@24287
   500
      val rels = relevant_clauses thy const_tab (!pass_mark) 
paulson@24287
   501
                   goal_const_tab  (map (pair_consts_typs_axiom thy) axioms)
paulson@24287
   502
  in
paulson@24287
   503
      Output.debug (fn () => ("Total relevant: " ^ Int.toString (length rels)));
paulson@24287
   504
      rels
paulson@24287
   505
  end
paulson@24287
   506
 else axioms;
paulson@24287
   507
paulson@24287
   508
(***************************************************************)
mengj@19768
   509
(* Retrieving and filtering lemmas                             *)
mengj@19768
   510
(***************************************************************)
mengj@19768
   511
mengj@19768
   512
(*** white list and black list of lemmas ***)
mengj@19768
   513
paulson@24215
   514
(*The rule subsetI is frequently omitted by the relevance filter. This could be theory data
paulson@24215
   515
  or identified with ATPset (which however is too big currently)*)
paulson@24215
   516
val whitelist = [subsetI];
wenzelm@21588
   517
mengj@19768
   518
(*** retrieve lemmas from clasimpset and atpset, may filter them ***)
mengj@19768
   519
mengj@19768
   520
(*Hashing to detect duplicate and variant clauses, e.g. from the [iff] attribute*)
mengj@19768
   521
paulson@22382
   522
fun setinsert (x,s) = Symtab.update (x,()) s;
mengj@19768
   523
paulson@20757
   524
(*Reject theorems with names like "List.filter.filter_list_def" or
paulson@21690
   525
  "Accessible_Part.acc.defs", as these are definitions arising from packages.*)
paulson@20757
   526
fun is_package_def a =
wenzelm@21858
   527
  let val names = NameSpace.explode a
paulson@21690
   528
  in
paulson@21690
   529
     length names > 2 andalso
paulson@21690
   530
     not (hd names = "local") andalso
paulson@21690
   531
     String.isSuffix "_def" a  orelse  String.isSuffix "_defs" a
paulson@21690
   532
  end;
paulson@20757
   533
mengj@19768
   534
(** a hash function from Term.term to int, and also a hash table **)
mengj@19768
   535
val xor_words = List.foldl Word.xorb 0w0;
mengj@19768
   536
mengj@19768
   537
fun hashw_term ((Const(c,_)), w) = Polyhash.hashw_string (c,w)
paulson@20661
   538
  | hashw_term ((Free(a,_)), w) = Polyhash.hashw_string (a,w)
mengj@19768
   539
  | hashw_term ((Var(_,_)), w) = w
paulson@20661
   540
  | hashw_term ((Bound i), w) = Polyhash.hashw_int(i,w)
mengj@19768
   541
  | hashw_term ((Abs(_,_,t)), w) = hashw_term (t, w)
mengj@19768
   542
  | hashw_term ((P$Q), w) = hashw_term (Q, (hashw_term (P, w)));
mengj@19768
   543
paulson@21070
   544
fun hash_literal (Const("Not",_)$P) = Word.notb(hashw_term(P,0w0))
paulson@21070
   545
  | hash_literal P = hashw_term(P,0w0);
mengj@19768
   546
paulson@21470
   547
fun hash_term t = Word.toIntX (xor_words (map hash_literal (dest_disj t)));
mengj@19768
   548
mengj@19768
   549
fun equal_thm (thm1,thm2) = Term.aconv(prop_of thm1, prop_of thm2);
paulson@20457
   550
paulson@22382
   551
exception HASH_CLAUSE;
paulson@22382
   552
mengj@19768
   553
(*Create a hash table for clauses, of the given size*)
mengj@19768
   554
fun mk_clause_table n =
paulson@20457
   555
      Polyhash.mkTable (hash_term o prop_of, equal_thm)
mengj@19768
   556
                       (n, HASH_CLAUSE);
mengj@19768
   557
paulson@20457
   558
(*Use a hash table to eliminate duplicates from xs. Argument is a list of
paulson@20868
   559
  (thm * (string * int)) tuples. The theorems are hashed into the table. *)
wenzelm@21588
   560
fun make_unique xs =
paulson@20868
   561
  let val ht = mk_clause_table 7000
paulson@20457
   562
  in
wenzelm@22130
   563
      Output.debug (fn () => ("make_unique gets " ^ Int.toString (length xs) ^ " clauses"));
wenzelm@21588
   564
      app (ignore o Polyhash.peekInsert ht) xs;
paulson@20868
   565
      Polyhash.listItems ht
paulson@20457
   566
  end;
mengj@19768
   567
paulson@20868
   568
(*Remove existing axiom clauses from the conjecture clauses, as this can dramatically
paulson@20868
   569
  boost an ATP's performance (for some reason)*)
wenzelm@21588
   570
fun subtract_cls c_clauses ax_clauses =
paulson@20868
   571
  let val ht = mk_clause_table 2200
paulson@20868
   572
      fun known x = isSome (Polyhash.peek ht x)
paulson@20868
   573
  in
wenzelm@21588
   574
      app (ignore o Polyhash.peekInsert ht) ax_clauses;
wenzelm@21588
   575
      filter (not o known) c_clauses
paulson@20868
   576
  end;
mengj@19768
   577
paulson@21224
   578
fun all_valid_thms ctxt =
paulson@22382
   579
  let
paulson@24286
   580
    fun blacklisted s = !run_blacklist_filter andalso is_package_def s
paulson@22382
   581
paulson@22382
   582
    fun extern_valid space (name, ths) =
paulson@22382
   583
      let
paulson@22382
   584
        val is_valid = ProofContext.valid_thms ctxt;
paulson@22382
   585
        val xname = NameSpace.extern space name;
paulson@22382
   586
      in
paulson@22382
   587
        if blacklisted name then I
paulson@22382
   588
        else if is_valid (xname, ths) then cons (xname, ths)
paulson@22382
   589
        else if is_valid (name, ths) then cons (name, ths)
paulson@22382
   590
        else I
paulson@22382
   591
      end;
paulson@22382
   592
    val thy = ProofContext.theory_of ctxt;
paulson@22382
   593
    val all_thys = thy :: Theory.ancestors_of thy;
paulson@22382
   594
paulson@22382
   595
    fun dest_valid (space, tab) = Symtab.fold (extern_valid space) tab [];
paulson@22382
   596
  in
paulson@22382
   597
    maps (dest_valid o PureThy.theorems_of) all_thys @
paulson@22382
   598
    fold (extern_valid (#1 (ProofContext.theorems_of ctxt)))
paulson@22382
   599
      (FactIndex.find (ProofContext.fact_index_of ctxt) ([], [])) []
paulson@22382
   600
  end;
paulson@21224
   601
wenzelm@21588
   602
fun multi_name a (th, (n,pairs)) =
paulson@21224
   603
  (n+1, (a ^ "(" ^ Int.toString n ^ ")", th) :: pairs)
paulson@21224
   604
paulson@22382
   605
fun add_single_names ((a, []), pairs) = pairs
paulson@22382
   606
  | add_single_names ((a, [th]), pairs) = (a,th)::pairs
paulson@22382
   607
  | add_single_names ((a, ths), pairs) = #2 (foldl (multi_name a) (1,pairs) ths);
paulson@21431
   608
paulson@22382
   609
(*Ignore blacklisted basenames*)
wenzelm@21588
   610
fun add_multi_names ((a, ths), pairs) =
paulson@24854
   611
  if (Sign.base_name a) mem_string ResAxioms.multi_base_blacklist  then pairs
paulson@22382
   612
  else add_single_names ((a, ths), pairs);
paulson@21224
   613
paulson@21290
   614
fun is_multi (a, ths) = length ths > 1 orelse String.isSuffix ".axioms" a;
paulson@21290
   615
paulson@24286
   616
(*The single theorems go BEFORE the multiple ones. Blacklist is applied to all.*)
wenzelm@21588
   617
fun name_thm_pairs ctxt =
paulson@21290
   618
  let val (mults,singles) = List.partition is_multi (all_valid_thms ctxt)
paulson@24286
   619
      val ht = mk_clause_table 900   (*ht for blacklisted theorems*)
paulson@24286
   620
      fun blacklisted x = !run_blacklist_filter andalso isSome (Polyhash.peek ht x)
paulson@24286
   621
  in
paulson@24286
   622
      app (fn th => ignore (Polyhash.peekInsert ht (th,()))) (ResBlacklist.get ctxt);
paulson@24286
   623
      filter (not o blacklisted o #2)
paulson@24286
   624
        (foldl add_single_names (foldl add_multi_names [] mults) singles)
paulson@24286
   625
  end;
paulson@21224
   626
paulson@21224
   627
fun check_named ("",th) = (warning ("No name for theorem " ^ string_of_thm th); false)
paulson@21224
   628
  | check_named (_,th) = true;
paulson@19894
   629
paulson@22193
   630
fun display_thm (name,th) = Output.debug (fn () => name ^ ": " ^ string_of_thm th);
paulson@22193
   631
mengj@19768
   632
(* get lemmas from claset, simpset, atpset and extra supplied rules *)
wenzelm@21588
   633
fun get_clasimp_atp_lemmas ctxt user_thms =
paulson@19894
   634
  let val included_thms =
wenzelm@21588
   635
        if !include_all
wenzelm@21588
   636
        then (tap (fn ths => Output.debug
wenzelm@22130
   637
                     (fn () => ("Including all " ^ Int.toString (length ths) ^ " theorems")))
wenzelm@21588
   638
                  (name_thm_pairs ctxt))
wenzelm@21588
   639
        else
wenzelm@21588
   640
        let val claset_thms =
wenzelm@21588
   641
                if !include_claset then ResAxioms.claset_rules_of ctxt
wenzelm@21588
   642
                else []
wenzelm@21588
   643
            val simpset_thms =
wenzelm@21588
   644
                if !include_simpset then ResAxioms.simpset_rules_of ctxt
wenzelm@21588
   645
                else []
wenzelm@21588
   646
            val atpset_thms =
wenzelm@21588
   647
                if !include_atpset then ResAxioms.atpset_rules_of ctxt
wenzelm@21588
   648
                else []
paulson@22193
   649
            val _ = (Output.debug (fn () => "ATP theorems: ");  app display_thm atpset_thms)
wenzelm@21588
   650
        in  claset_thms @ simpset_thms @ atpset_thms  end
wenzelm@21588
   651
      val user_rules = filter check_named
paulson@22382
   652
                         (map ResAxioms.pairname
paulson@24215
   653
                           (if null user_thms then whitelist else user_thms))
paulson@19894
   654
  in
paulson@21224
   655
      (filter check_named included_thms, user_rules)
paulson@19894
   656
  end;
mengj@19768
   657
paulson@21290
   658
(***************************************************************)
paulson@21290
   659
(* Type Classes Present in the Axiom or Conjecture Clauses     *)
paulson@21290
   660
(***************************************************************)
paulson@21290
   661
paulson@21290
   662
fun add_classes (sorts, cset) = foldl setinsert cset (List.concat sorts);
paulson@21290
   663
paulson@21290
   664
(*Remove this trivial type class*)
paulson@21290
   665
fun delete_type cset = Symtab.delete_safe "HOL.type" cset;
paulson@21290
   666
paulson@21290
   667
fun tvar_classes_of_terms ts =
paulson@21290
   668
  let val sorts_list = map (map #2 o term_tvars) ts
paulson@21290
   669
  in  Symtab.keys (delete_type (foldl add_classes Symtab.empty sorts_list))  end;
paulson@21290
   670
paulson@21290
   671
fun tfree_classes_of_terms ts =
paulson@21290
   672
  let val sorts_list = map (map #2 o term_tfrees) ts
paulson@21290
   673
  in  Symtab.keys (delete_type (foldl add_classes Symtab.empty sorts_list))  end;
paulson@20526
   674
paulson@21373
   675
(*fold type constructors*)
paulson@21373
   676
fun fold_type_consts f (Type (a, Ts)) x = fold (fold_type_consts f) Ts (f (a,x))
paulson@21373
   677
  | fold_type_consts f T x = x;
paulson@21373
   678
paulson@21373
   679
val add_type_consts_in_type = fold_type_consts setinsert;
paulson@21373
   680
paulson@21397
   681
(*Type constructors used to instantiate overloaded constants are the only ones needed.*)
paulson@21397
   682
fun add_type_consts_in_term thy =
paulson@21397
   683
  let val const_typargs = Sign.const_typargs thy
paulson@21397
   684
      fun add_tcs (Const cT) x = fold add_type_consts_in_type (const_typargs cT) x
paulson@21397
   685
        | add_tcs (Abs (_, T, u)) x = add_tcs u x
paulson@21397
   686
        | add_tcs (t $ u) x = add_tcs t (add_tcs u x)
paulson@21397
   687
        | add_tcs _ x = x
paulson@21397
   688
  in  add_tcs  end
paulson@21373
   689
paulson@21397
   690
fun type_consts_of_terms thy ts =
paulson@21397
   691
  Symtab.keys (fold (add_type_consts_in_term thy) ts Symtab.empty);
paulson@21373
   692
paulson@21373
   693
mengj@19194
   694
(***************************************************************)
mengj@19194
   695
(* ATP invocation methods setup                                *)
mengj@19194
   696
(***************************************************************)
mengj@19194
   697
wenzelm@21588
   698
fun cnf_hyps_thms ctxt =
wenzelm@20224
   699
    let val ths = Assumption.prems_of ctxt
wenzelm@19617
   700
    in fold (fold (insert Thm.eq_thm) o ResAxioms.skolem_thm) ths [] end;
mengj@19194
   701
paulson@20526
   702
(*Translation mode can be auto-detected, or forced to be first-order or higher-order*)
mengj@19194
   703
datatype mode = Auto | Fol | Hol;
mengj@19194
   704
paulson@19450
   705
val linkup_logic_mode = ref Auto;
paulson@19205
   706
paulson@20526
   707
(*Ensures that no higher-order theorems "leak out"*)
paulson@22382
   708
fun restrict_to_logic thy logic cls =
paulson@22382
   709
  if is_fol_logic logic then filter (Meson.is_fol_term thy o prop_of o fst) cls
wenzelm@21588
   710
                        else cls;
paulson@20526
   711
paulson@21470
   712
(**** Predicates to detect unwanted clauses (prolific or likely to cause unsoundness) ****)
paulson@21470
   713
paulson@21470
   714
(** Too general means, positive equality literal with a variable X as one operand,
paulson@21470
   715
  when X does not occur properly in the other operand. This rules out clearly
paulson@21470
   716
  inconsistent clauses such as V=a|V=b, though it by no means guarantees soundness. **)
wenzelm@21588
   717
paulson@21470
   718
fun occurs ix =
paulson@21470
   719
    let fun occ(Var (jx,_)) = (ix=jx)
paulson@21470
   720
          | occ(t1$t2)      = occ t1 orelse occ t2
paulson@21470
   721
          | occ(Abs(_,_,t)) = occ t
paulson@21470
   722
          | occ _           = false
paulson@21470
   723
    in occ end;
paulson@21470
   724
paulson@21470
   725
fun is_recordtype T = not (null (RecordPackage.dest_recTs T));
paulson@21470
   726
paulson@21470
   727
(*Unwanted equalities include
paulson@21470
   728
  (1) those between a variable that does not properly occur in the second operand,
paulson@21470
   729
  (2) those between a variable and a record, since these seem to be prolific "cases" thms
wenzelm@21588
   730
*)
paulson@21470
   731
fun too_general_eqterms (Var (ix,T), t) = not (occurs ix t) orelse is_recordtype T
paulson@21470
   732
  | too_general_eqterms _ = false;
paulson@21470
   733
paulson@21470
   734
fun too_general_equality (Const ("op =", _) $ x $ y) =
paulson@21470
   735
      too_general_eqterms (x,y) orelse too_general_eqterms(y,x)
paulson@21470
   736
  | too_general_equality _ = false;
paulson@21470
   737
paulson@21470
   738
(* tautologous? *)
paulson@21470
   739
fun is_taut (Const ("Trueprop", _) $ Const ("True", _)) = true
paulson@21470
   740
  | is_taut _ = false;
paulson@21470
   741
paulson@21431
   742
(*True if the term contains a variable whose (atomic) type is in the given list.*)
wenzelm@21588
   743
fun has_typed_var tycons =
paulson@21431
   744
  let fun var_tycon (Var (_, Type(a,_))) = a mem_string tycons
paulson@21431
   745
        | var_tycon _ = false
paulson@21431
   746
  in  exists var_tycon o term_vars  end;
paulson@21431
   747
paulson@22217
   748
(*Clauses are forbidden to contain variables of these types. The typical reason is that
paulson@22217
   749
  they lead to unsoundness. Note that "unit" satisfies numerous equations like ?X=().
paulson@22217
   750
  The resulting clause will have no type constraint, yielding false proofs. Even "bool"
paulson@22217
   751
  leads to many unsound proofs, though (obviously) only for higher-order problems.*)
paulson@24215
   752
val unwanted_types = ["Product_Type.unit","bool"];
paulson@22217
   753
paulson@21470
   754
fun unwanted t =
paulson@24215
   755
    is_taut t orelse has_typed_var unwanted_types t orelse
paulson@21470
   756
    forall too_general_equality (dest_disj t);
paulson@21470
   757
paulson@21431
   758
(*Clauses containing variables of type "unit" or "bool" are unlikely to be useful and
paulson@21431
   759
  likely to lead to unsound proofs.*)
paulson@22217
   760
fun remove_unwanted_clauses cls = filter (not o unwanted o prop_of o fst) cls;
paulson@21431
   761
wenzelm@24320
   762
fun tptp_writer thy logic = ResHolClause.tptp_write_file thy (logic=FOL);
paulson@19445
   763
wenzelm@24320
   764
fun dfg_writer thy logic = ResHolClause.dfg_write_file thy (logic=FOL);
mengj@19194
   765
paulson@20022
   766
(*Called by the oracle-based methods declared in res_atp_methods.ML*)
mengj@19722
   767
fun write_subgoal_file dfg mode ctxt conjectures user_thms n =
wenzelm@24300
   768
    let val conj_cls = Meson.make_clauses conjectures
paulson@24827
   769
                         |> map ResAxioms.combinators |> Meson.finish_cnf
wenzelm@21588
   770
        val hyp_cls = cnf_hyps_thms ctxt
wenzelm@21588
   771
        val goal_cls = conj_cls@hyp_cls
wenzelm@21588
   772
        val goal_tms = map prop_of goal_cls
paulson@22382
   773
        val thy = ProofContext.theory_of ctxt
wenzelm@21588
   774
        val logic = case mode of
paulson@21431
   775
                            Auto => problem_logic_goals [goal_tms]
wenzelm@21588
   776
                          | Fol => FOL
wenzelm@21588
   777
                          | Hol => HOL
wenzelm@21588
   778
        val (included_thms,user_rules) = get_clasimp_atp_lemmas ctxt user_thms
wenzelm@22865
   779
        val cla_simp_atp_clauses = included_thms
wenzelm@21588
   780
                                     |> ResAxioms.cnf_rules_pairs |> make_unique
paulson@22382
   781
                                     |> restrict_to_logic thy logic
paulson@21470
   782
                                     |> remove_unwanted_clauses
wenzelm@21588
   783
        val user_cls = ResAxioms.cnf_rules_pairs user_rules
paulson@24287
   784
        val axclauses = make_unique (user_cls @ relevance_filter thy cla_simp_atp_clauses goal_tms)
paulson@21431
   785
        val subs = tfree_classes_of_terms goal_tms
paulson@21373
   786
        and axtms = map (prop_of o #1) axclauses
paulson@21373
   787
        val supers = tvar_classes_of_terms axtms
paulson@21431
   788
        and tycons = type_consts_of_terms thy (goal_tms@axtms)
paulson@21290
   789
        (*TFrees in conjecture clauses; TVars in axiom clauses*)
paulson@22645
   790
        val (supers',arity_clauses) = ResClause.make_arity_clauses thy tycons supers
paulson@22645
   791
        val classrel_clauses = ResClause.make_classrel_clauses thy subs supers'
wenzelm@21588
   792
        val writer = if dfg then dfg_writer else tptp_writer
wenzelm@21588
   793
        and file = atp_input_file()
wenzelm@21588
   794
        and user_lemmas_names = map #1 user_rules
mengj@19194
   795
    in
wenzelm@24320
   796
        writer thy logic goal_cls file (axclauses,classrel_clauses,arity_clauses) user_lemmas_names;
wenzelm@22130
   797
        Output.debug (fn () => "Writing to " ^ file);
wenzelm@21588
   798
        file
mengj@19194
   799
    end;
mengj@19194
   800
mengj@19194
   801
mengj@19194
   802
(**** remove tmp files ****)
wenzelm@21588
   803
fun cond_rm_tmp file =
wenzelm@22130
   804
    if !Output.debugging orelse !destdir <> ""
wenzelm@22130
   805
    then Output.debug (fn () => "ATP input kept...")
paulson@20870
   806
    else OS.FileSys.remove file;
mengj@19194
   807
mengj@19194
   808
mengj@19194
   809
(***************************************************************)
mengj@19194
   810
(* automatic ATP invocation                                    *)
mengj@19194
   811
(***************************************************************)
mengj@19194
   812
paulson@17306
   813
(* call prover with settings and problem file for the current subgoal *)
paulson@17764
   814
fun watcher_call_provers sign sg_terms (childin, childout, pid) =
wenzelm@16802
   815
  let
paulson@17422
   816
    fun make_atp_list [] n = []
paulson@17717
   817
      | make_atp_list (sg_term::xs) n =
wenzelm@16802
   818
          let
paulson@17717
   819
            val probfile = prob_pathname n
paulson@17690
   820
            val time = Int.toString (!time_limit)
wenzelm@16802
   821
          in
wenzelm@22130
   822
            Output.debug (fn () => "problem file in watcher_call_provers is " ^ probfile);
paulson@17764
   823
            (*options are separated by Watcher.setting_sep, currently #"%"*)
paulson@24425
   824
            case !prover of
paulson@24425
   825
                Recon.SPASS =>
paulson@24425
   826
		  let val spass = helper_path "SPASS_HOME" "SPASS"
paulson@24425
   827
		      val sopts =
paulson@24425
   828
       "-Auto%-SOS=1%-PGiven=0%-PProblem=0%-Splits=0%-FullRed=0%-DocProof%-TimeLimit=" ^ time
paulson@24425
   829
		  in
paulson@24425
   830
		      ("spass", spass, sopts, probfile) :: make_atp_list xs (n+1)
paulson@24425
   831
		  end
paulson@24425
   832
              | Recon.Vampire =>
paulson@24425
   833
		  let val vampire = helper_path "VAMPIRE_HOME" "vampire"
paulson@24546
   834
		      val vopts = "--output_syntax tptp%--mode casc%-t " ^ time
paulson@24425
   835
		  in
paulson@24425
   836
		      ("vampire", vampire, vopts, probfile) :: make_atp_list xs (n+1)
paulson@24425
   837
		  end
paulson@24425
   838
              | Recon.E =>
paulson@24425
   839
		  let val eproof = helper_path "E_HOME" "eproof"
paulson@24425
   840
                      val eopts = "--tstp-in%--tstp-out%-l5%-xAutoDev%-tAutoDev%--silent%--cpu-limit=" ^ time
paulson@24425
   841
		  in
paulson@24425
   842
		     ("E", eproof, eopts, probfile) :: make_atp_list xs (n+1)
paulson@24425
   843
		  end
wenzelm@16802
   844
          end
paulson@15452
   845
paulson@17422
   846
    val atp_list = make_atp_list sg_terms 1
wenzelm@16802
   847
  in
wenzelm@16802
   848
    Watcher.callResProvers(childout,atp_list);
wenzelm@22130
   849
    Output.debug (fn () => "Sent commands to watcher!")
wenzelm@16802
   850
  end
wenzelm@21588
   851
paulson@22193
   852
(*For debugging the generated set of theorem names*)
paulson@21888
   853
fun trace_vector fname =
paulson@22193
   854
  let val path = File.explode_platform_path (fname ^ "_thm_names")
paulson@21888
   855
  in  Vector.app (File.append path o (fn s => s ^ "\n"))  end;
quigley@16357
   856
paulson@20022
   857
(*We write out problem files for each subgoal. Argument probfile generates filenames,
paulson@18986
   858
  and allows the suppression of the suffix "_1" in problem-generation mode.
paulson@18986
   859
  FIXME: does not cope with &&, and it isn't easy because one could have multiple
paulson@18986
   860
  subgoals, each involving &&.*)
paulson@24546
   861
fun write_problem_files probfile (ctxt, chain_ths, th) =
paulson@18753
   862
  let val goals = Thm.prems_of th
wenzelm@22130
   863
      val _ = Output.debug (fn () => "number of subgoals = " ^ Int.toString (length goals))
paulson@17717
   864
      val thy = ProofContext.theory_of ctxt
paulson@20457
   865
      fun get_neg_subgoals [] _ = []
wenzelm@22865
   866
        | get_neg_subgoals (gl::gls) n = #1 (ResAxioms.neg_conjecture_clauses th n) ::
paulson@21999
   867
                                         get_neg_subgoals gls (n+1)
paulson@20526
   868
      val goal_cls = get_neg_subgoals goals 1
paulson@20457
   869
      val logic = case !linkup_logic_mode of
paulson@23387
   870
                Auto => problem_logic_goals (map (map prop_of) goal_cls)
wenzelm@21588
   871
              | Fol => FOL
wenzelm@21588
   872
              | Hol => HOL
paulson@24546
   873
      val (included_thms,white_thms) = get_clasimp_atp_lemmas ctxt chain_ths
paulson@22382
   874
      val included_cls = included_thms |> ResAxioms.cnf_rules_pairs |> make_unique
paulson@22382
   875
                                       |> restrict_to_logic thy logic
paulson@21470
   876
                                       |> remove_unwanted_clauses
wenzelm@22130
   877
      val _ = Output.debug (fn () => "included clauses = " ^ Int.toString(length included_cls))
paulson@20526
   878
      val white_cls = ResAxioms.cnf_rules_pairs white_thms
paulson@20526
   879
      (*clauses relevant to goal gl*)
paulson@24287
   880
      val axcls_list = map (fn ngcls => white_cls @ relevance_filter thy included_cls (map prop_of ngcls)) goal_cls
wenzelm@22130
   881
      val _ = app (fn axcls => Output.debug (fn () => "filtered clauses = " ^ Int.toString(length axcls)))
paulson@21070
   882
                  axcls_list
paulson@24425
   883
      val writer = if !prover = Recon.SPASS then dfg_writer else tptp_writer
paulson@20526
   884
      fun write_all [] [] _ = []
wenzelm@21588
   885
        | write_all (ccls::ccls_list) (axcls::axcls_list) k =
paulson@20868
   886
            let val fname = probfile k
paulson@22217
   887
                val _ = Output.debug (fn () => "About to write file " ^ fname)
paulson@20868
   888
                val axcls = make_unique axcls
paulson@22217
   889
                val _ = Output.debug (fn () => "Conjecture Clauses (before duplicate removal)")
paulson@22217
   890
                val _ = app (fn th => Output.debug (fn _ => string_of_thm th)) ccls
paulson@20868
   891
                val ccls = subtract_cls ccls axcls
paulson@22217
   892
                val _ = Output.debug (fn () => "Conjecture Clauses (AFTER duplicate removal)")
paulson@22217
   893
                val _ = app (fn th => Output.debug (fn _ => string_of_thm th)) ccls
paulson@21431
   894
                val ccltms = map prop_of ccls
paulson@21373
   895
                and axtms = map (prop_of o #1) axcls
paulson@21431
   896
                val subs = tfree_classes_of_terms ccltms
paulson@21431
   897
                and supers = tvar_classes_of_terms axtms
paulson@21431
   898
                and tycons = type_consts_of_terms thy (ccltms@axtms)
paulson@21290
   899
                (*TFrees in conjecture clauses; TVars in axiom clauses*)
paulson@22645
   900
                val (supers',arity_clauses) = ResClause.make_arity_clauses thy tycons supers
paulson@22645
   901
                val _ = Output.debug (fn () => "arity clauses = " ^ Int.toString (length arity_clauses))
paulson@22645
   902
                val classrel_clauses = ResClause.make_classrel_clauses thy subs supers'
wenzelm@22130
   903
                val _ = Output.debug (fn () => "classrel clauses = " ^ Int.toString (length classrel_clauses))
wenzelm@24320
   904
                val clnames = writer thy logic ccls fname (axcls,classrel_clauses,arity_clauses) []
paulson@21888
   905
                val thm_names = Vector.fromList clnames
paulson@22193
   906
                val _ = if !Output.debugging then trace_vector fname thm_names else ()
paulson@20870
   907
            in  (thm_names,fname) :: write_all ccls_list axcls_list (k+1)  end
paulson@20870
   908
      val (thm_names_list, filenames) = ListPair.unzip (write_all goal_cls axcls_list 1)
mengj@19194
   909
  in
paulson@20870
   910
      (filenames, thm_names_list)
mengj@19194
   911
  end;
quigley@15644
   912
wenzelm@21588
   913
val last_watcher_pid = ref (NONE : (TextIO.instream * TextIO.outstream *
paulson@17775
   914
                                    Posix.Process.pid * string list) option);
paulson@17775
   915
paulson@17775
   916
fun kill_last_watcher () =
wenzelm@21588
   917
    (case !last_watcher_pid of
paulson@17775
   918
         NONE => ()
wenzelm@21588
   919
       | SOME (_, _, pid, files) =>
wenzelm@22130
   920
          (Output.debug (fn () => "Killing old watcher, pid = " ^ string_of_pid pid);
wenzelm@21588
   921
           Watcher.killWatcher pid;
wenzelm@21588
   922
           ignore (map (try cond_rm_tmp) files)))
wenzelm@22130
   923
     handle OS.SysErr _ => Output.debug (fn () => "Attempt to kill watcher failed");
paulson@17525
   924
paulson@21980
   925
(*writes out the current problems and calls ATPs*)
paulson@24546
   926
fun isar_atp (ctxt, chain_ths, th) =
paulson@17717
   927
  if Thm.no_prems th then ()
wenzelm@16802
   928
  else
wenzelm@16802
   929
    let
paulson@17775
   930
      val _ = kill_last_watcher()
paulson@24546
   931
      val (files,thm_names_list) = write_problem_files prob_pathname (ctxt, chain_ths, th)
paulson@22012
   932
      val (childin, childout, pid) = Watcher.createWatcher (ctxt, th, thm_names_list)
paulson@15608
   933
    in
paulson@17772
   934
      last_watcher_pid := SOME (childin, childout, pid, files);
wenzelm@22130
   935
      Output.debug (fn () => "problem files: " ^ space_implode ", " files);
wenzelm@22130
   936
      Output.debug (fn () => "pid: " ^ string_of_pid pid);
wenzelm@22578
   937
      watcher_call_provers (Thm.theory_of_thm th) (Thm.prems_of th) (childin, childout, pid)
paulson@20954
   938
    end;
paulson@20954
   939
paulson@20954
   940
(*For ML scripts, and primarily, for debugging*)
wenzelm@21588
   941
fun callatp () =
paulson@20954
   942
  let val th = topthm()
paulson@20954
   943
      val ctxt = ProofContext.init (theory_of_thm th)
paulson@24546
   944
  in  isar_atp (ctxt, [], th)  end;
paulson@15608
   945
wenzelm@24634
   946
val isar_atp_writeonly = PrintMode.setmp []
paulson@24546
   947
      (fn (ctxt, chain_ths, th) =>
paulson@17717
   948
       if Thm.no_prems th then ()
wenzelm@21588
   949
       else
wenzelm@21588
   950
         let val probfile = if Thm.nprems_of th = 1 then probfile_nosuffix
wenzelm@21588
   951
                            else prob_pathname
paulson@24546
   952
         in ignore (write_problem_files probfile (ctxt, chain_ths, th)) end);
paulson@15452
   953
quigley@16357
   954
wenzelm@22865
   955
(** the Isar toplevel command **)
wenzelm@16802
   956
wenzelm@22865
   957
fun sledgehammer state =
wenzelm@22865
   958
  let
paulson@24546
   959
    val (ctxt, (chain_ths, goal)) = Proof.get_goal (Toplevel.proof_of state);
wenzelm@22865
   960
    val thy = ProofContext.theory_of ctxt;
wenzelm@16802
   961
  in
wenzelm@22130
   962
    Output.debug (fn () => "subgoals in isar_atp:\n" ^
wenzelm@21588
   963
                  Pretty.string_of (ProofContext.pretty_term ctxt
wenzelm@21588
   964
                    (Logic.mk_conjunction_list (Thm.prems_of goal))));
wenzelm@22130
   965
    Output.debug (fn () => "current theory: " ^ Context.theory_name thy);
paulson@24546
   966
    app (fn th => Output.debug (fn _ => "chained: " ^ string_of_thm th)) chain_ths;
paulson@24546
   967
    if !time_limit > 0 then isar_atp (ctxt, chain_ths, goal)
wenzelm@22865
   968
    else (warning ("Writing problem file only: " ^ !problem_name);
paulson@24546
   969
          isar_atp_writeonly (ctxt, chain_ths, goal))
paulson@19205
   970
  end;
paulson@19205
   971
wenzelm@22865
   972
val _ = OuterSyntax.add_parsers
wenzelm@22865
   973
  [OuterSyntax.command "sledgehammer" "call automatic theorem provers" OuterKeyword.diag
wenzelm@22865
   974
    (Scan.succeed (Toplevel.no_timing o Toplevel.unknown_proof o Toplevel.keep sledgehammer))];
paulson@17091
   975
paulson@15347
   976
end;