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