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