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