src/HOL/Tools/Sledgehammer/sledgehammer_fact_preprocessor.ML
author blanchet
Wed Jun 02 17:19:44 2010 +0200 (2010-06-02)
changeset 37323 2f2f0d246d0f
parent 37171 fc1e20373e6a
child 37332 51d99ba6fc4d
permissions -rw-r--r--
handle Vampire's definitions smoothly
blanchet@35826
     1
(*  Title:      HOL/Tools/Sledgehammer/sledgehammer_fact_preprocessor.ML
wenzelm@33311
     2
    Author:     Jia Meng, Cambridge University Computer Laboratory
blanchet@36393
     3
    Author:     Jasmin Blanchette, TU Muenchen
paulson@15347
     4
wenzelm@20461
     5
Transformation of axiom rules (elim/intro/etc) into CNF forms.
paulson@15347
     6
*)
paulson@15347
     7
blanchet@35826
     8
signature SLEDGEHAMMER_FACT_PREPROCESSOR =
wenzelm@21505
     9
sig
blanchet@37171
    10
  val chained_prefix: string
wenzelm@32955
    11
  val trace: bool Unsynchronized.ref
wenzelm@32955
    12
  val trace_msg: (unit -> string) -> unit
blanchet@35865
    13
  val skolem_prefix: string
blanchet@36492
    14
  val skolem_infix: string
wenzelm@27179
    15
  val cnf_axiom: theory -> thm -> thm list
wenzelm@27184
    16
  val multi_base_blacklist: string list
paulson@25243
    17
  val bad_for_atp: thm -> bool
wenzelm@35568
    18
  val type_has_topsort: typ -> bool
wenzelm@27179
    19
  val cnf_rules_pairs: theory -> (string * thm) list -> (thm * (string * int)) list
wenzelm@32740
    20
  val suppress_endtheory: bool Unsynchronized.ref
wenzelm@32740
    21
    (*for emergency use where endtheory causes problems*)
blanchet@36478
    22
  val strip_subgoal : thm -> int -> (string * typ) list * term list * term
blanchet@36398
    23
  val neg_clausify: thm -> thm list
blanchet@36398
    24
  val neg_conjecture_clauses:
blanchet@36398
    25
    Proof.context -> thm -> int -> thm list list * (string * typ) list
blanchet@36394
    26
  val neg_clausify_tac: Proof.context -> int -> tactic
wenzelm@24669
    27
  val setup: theory -> theory
wenzelm@21505
    28
end;
mengj@19196
    29
blanchet@35826
    30
structure Sledgehammer_Fact_Preprocessor : SLEDGEHAMMER_FACT_PREPROCESSOR =
paulson@15997
    31
struct
paulson@15347
    32
blanchet@35865
    33
open Sledgehammer_FOL_Clause
blanchet@35865
    34
blanchet@37171
    35
(* Used to label theorems chained into the goal. *)
blanchet@37171
    36
val chained_prefix = "Sledgehammer.chained_"
blanchet@37171
    37
wenzelm@32955
    38
val trace = Unsynchronized.ref false;
blanchet@35865
    39
fun trace_msg msg = if !trace then tracing (msg ()) else ();
blanchet@35865
    40
blanchet@35865
    41
val skolem_prefix = "sko_"
blanchet@36492
    42
val skolem_infix = "$"
wenzelm@32955
    43
wenzelm@33832
    44
fun freeze_thm th = #1 (Drule.legacy_freeze_thaw th);
paulson@20863
    45
wenzelm@35568
    46
val type_has_topsort = Term.exists_subtype
wenzelm@35568
    47
  (fn TFree (_, []) => true
wenzelm@35568
    48
    | TVar (_, []) => true
wenzelm@35568
    49
    | _ => false);
wenzelm@27184
    50
wenzelm@28544
    51
paulson@15997
    52
(**** Transformation of Elimination Rules into First-Order Formulas****)
paulson@15347
    53
wenzelm@29064
    54
val cfalse = cterm_of @{theory HOL} HOLogic.false_const;
wenzelm@29064
    55
val ctp_false = cterm_of @{theory HOL} (HOLogic.mk_Trueprop HOLogic.false_const);
wenzelm@20461
    56
paulson@21430
    57
(*Converts an elim-rule into an equivalent theorem that does not have the
paulson@21430
    58
  predicate variable.  Leaves other theorems unchanged.  We simply instantiate the
paulson@21430
    59
  conclusion variable to False.*)
paulson@16009
    60
fun transform_elim th =
paulson@21430
    61
  case concl_of th of    (*conclusion variable*)
blanchet@35963
    62
       @{const Trueprop} $ (v as Var (_, @{typ bool})) =>
wenzelm@29064
    63
           Thm.instantiate ([], [(cterm_of @{theory HOL} v, cfalse)]) th
blanchet@35963
    64
    | v as Var(_, @{typ prop}) =>
wenzelm@29064
    65
           Thm.instantiate ([], [(cterm_of @{theory HOL} v, ctp_false)]) th
paulson@21430
    66
    | _ => th;
paulson@15997
    67
paulson@24742
    68
(*To enforce single-threading*)
paulson@24742
    69
exception Clausify_failure of theory;
wenzelm@20461
    70
wenzelm@28544
    71
paulson@16009
    72
(**** SKOLEMIZATION BY INFERENCE (lcp) ****)
paulson@16009
    73
blanchet@36492
    74
(*Keep the full complexity of the original name*)
blanchet@36492
    75
fun flatten_name s = space_implode "_X" (Long_Name.explode s);
blanchet@36492
    76
blanchet@36492
    77
fun skolem_name thm_name nref var_name =
blanchet@36492
    78
  skolem_prefix ^ thm_name ^ "_" ^ Int.toString (Unsynchronized.inc nref) ^
blanchet@36492
    79
  skolem_infix ^ (if var_name = "" then "g" else flatten_name var_name)
blanchet@36492
    80
paulson@24742
    81
fun rhs_extra_types lhsT rhs =
paulson@24742
    82
  let val lhs_vars = Term.add_tfreesT lhsT []
paulson@24742
    83
      fun add_new_TFrees (TFree v) =
wenzelm@24821
    84
            if member (op =) lhs_vars v then I else insert (op =) (TFree v)
wenzelm@24821
    85
        | add_new_TFrees _ = I
paulson@24742
    86
      val rhs_consts = fold_aterms (fn Const c => insert (op =) c | _ => I) rhs []
paulson@24742
    87
  in fold (#2 #> Term.fold_atyps add_new_TFrees) rhs_consts [] end;
paulson@24742
    88
paulson@18141
    89
(*Traverse a theorem, declaring Skolem function definitions. String s is the suggested
wenzelm@27174
    90
  prefix for the Skolem constant.*)
wenzelm@27174
    91
fun declare_skofuns s th =
wenzelm@27174
    92
  let
wenzelm@33222
    93
    val nref = Unsynchronized.ref 0    (* FIXME ??? *)
blanchet@36492
    94
    fun dec_sko (Const (@{const_name Ex}, _) $ (xtp as Abs (s', T, p))) (axs, thy) =
wenzelm@27174
    95
          (*Existential: declare a Skolem function, then insert into body and continue*)
wenzelm@27174
    96
          let
blanchet@36492
    97
            val cname = skolem_name s nref s'
wenzelm@29265
    98
            val args0 = OldTerm.term_frees xtp  (*get the formal parameter list*)
wenzelm@27174
    99
            val Ts = map type_of args0
wenzelm@27174
   100
            val extraTs = rhs_extra_types (Ts ---> T) xtp
wenzelm@27174
   101
            val argsx = map (fn T => Free (gensym "vsk", T)) extraTs
wenzelm@27174
   102
            val args = argsx @ args0
wenzelm@27174
   103
            val cT = extraTs ---> Ts ---> T
wenzelm@27174
   104
            val rhs = list_abs_free (map dest_Free args, HOLogic.choice_const T $ xtp)
wenzelm@27174
   105
                    (*Forms a lambda-abstraction over the formal parameters*)
wenzelm@28110
   106
            val (c, thy') =
wenzelm@33173
   107
              Sign.declare_const ((Binding.conceal (Binding.name cname), cT), NoSyn) thy
wenzelm@27174
   108
            val cdef = cname ^ "_def"
wenzelm@36106
   109
            val ((_, ax), thy'') =
wenzelm@35984
   110
              Thm.add_def true false (Binding.name cdef, Logic.mk_equals (c, rhs)) thy'
wenzelm@35984
   111
            val ax' = Drule.export_without_context ax
wenzelm@35984
   112
          in dec_sko (subst_bound (list_comb (c, args), p)) (ax' :: axs, thy'') end
blanchet@35963
   113
      | dec_sko (Const (@{const_name All}, _) $ (Abs (a, T, p))) thx =
wenzelm@27174
   114
          (*Universal quant: insert a free variable into body and continue*)
wenzelm@29270
   115
          let val fname = Name.variant (OldTerm.add_term_names (p, [])) a
wenzelm@27174
   116
          in dec_sko (subst_bound (Free (fname, T), p)) thx end
blanchet@35963
   117
      | dec_sko (@{const "op &"} $ p $ q) thx = dec_sko q (dec_sko p thx)
blanchet@35963
   118
      | dec_sko (@{const "op |"} $ p $ q) thx = dec_sko q (dec_sko p thx)
blanchet@35963
   119
      | dec_sko (@{const Trueprop} $ p) thx = dec_sko p thx
wenzelm@27174
   120
      | dec_sko t thx = thx (*Do nothing otherwise*)
wenzelm@27174
   121
  in fn thy => dec_sko (Thm.prop_of th) ([], thy) end;
paulson@18141
   122
paulson@18141
   123
(*Traverse a theorem, accumulating Skolem function definitions.*)
paulson@22731
   124
fun assume_skofuns s th =
wenzelm@33222
   125
  let val sko_count = Unsynchronized.ref 0   (* FIXME ??? *)
blanchet@36492
   126
      fun dec_sko (Const (@{const_name Ex}, _) $ (xtp as Abs (s', T, p))) defs =
wenzelm@20461
   127
            (*Existential: declare a Skolem function, then insert into body and continue*)
wenzelm@20461
   128
            let val skos = map (#1 o Logic.dest_equals) defs  (*existing sko fns*)
haftmann@33040
   129
                val args = subtract (op =) skos (OldTerm.term_frees xtp) (*the formal parameters*)
wenzelm@20461
   130
                val Ts = map type_of args
wenzelm@20461
   131
                val cT = Ts ---> T
blanchet@36492
   132
                val id = skolem_name s sko_count s'
paulson@22731
   133
                val c = Free (id, cT)
wenzelm@20461
   134
                val rhs = list_abs_free (map dest_Free args,
wenzelm@20461
   135
                                         HOLogic.choice_const T $ xtp)
wenzelm@20461
   136
                      (*Forms a lambda-abstraction over the formal parameters*)
wenzelm@27330
   137
                val def = Logic.mk_equals (c, rhs)
wenzelm@20461
   138
            in dec_sko (subst_bound (list_comb(c,args), p))
wenzelm@20461
   139
                       (def :: defs)
wenzelm@20461
   140
            end
blanchet@35963
   141
        | dec_sko (Const (@{const_name All},_) $ Abs (a, T, p)) defs =
wenzelm@20461
   142
            (*Universal quant: insert a free variable into body and continue*)
wenzelm@29270
   143
            let val fname = Name.variant (OldTerm.add_term_names (p,[])) a
wenzelm@20461
   144
            in dec_sko (subst_bound (Free(fname,T), p)) defs end
blanchet@35963
   145
        | dec_sko (@{const "op &"} $ p $ q) defs = dec_sko q (dec_sko p defs)
blanchet@35963
   146
        | dec_sko (@{const "op |"} $ p $ q) defs = dec_sko q (dec_sko p defs)
blanchet@35963
   147
        | dec_sko (@{const Trueprop} $ p) defs = dec_sko p defs
wenzelm@20461
   148
        | dec_sko t defs = defs (*Do nothing otherwise*)
paulson@20419
   149
  in  dec_sko (prop_of th) []  end;
paulson@20419
   150
paulson@20419
   151
paulson@24827
   152
(**** REPLACING ABSTRACTIONS BY COMBINATORS ****)
paulson@20419
   153
paulson@20419
   154
(*Returns the vars of a theorem*)
paulson@20419
   155
fun vars_of_thm th =
wenzelm@22691
   156
  map (Thm.cterm_of (theory_of_thm th) o Var) (Thm.fold_terms Term.add_vars th []);
paulson@20419
   157
paulson@20419
   158
(*Make a version of fun_cong with a given variable name*)
paulson@20419
   159
local
paulson@20419
   160
    val fun_cong' = fun_cong RS asm_rl; (*renumber f, g to prevent clashes with (a,0)*)
paulson@20419
   161
    val cx = hd (vars_of_thm fun_cong');
paulson@20419
   162
    val ty = typ_of (ctyp_of_term cx);
paulson@20445
   163
    val thy = theory_of_thm fun_cong;
paulson@20419
   164
    fun mkvar a = cterm_of thy (Var((a,0),ty));
paulson@20419
   165
in
paulson@20419
   166
fun xfun_cong x = Thm.instantiate ([], [(cx, mkvar x)]) fun_cong'
paulson@20419
   167
end;
paulson@20419
   168
paulson@20863
   169
(*Removes the lambdas from an equation of the form t = (%x. u).  A non-negative n,
paulson@20863
   170
  serves as an upper bound on how many to remove.*)
paulson@20863
   171
fun strip_lambdas 0 th = th
wenzelm@24669
   172
  | strip_lambdas n th =
paulson@20863
   173
      case prop_of th of
blanchet@35963
   174
          _ $ (Const (@{const_name "op ="}, _) $ _ $ Abs (x, _, _)) =>
wenzelm@24669
   175
              strip_lambdas (n-1) (freeze_thm (th RS xfun_cong x))
wenzelm@24669
   176
        | _ => th;
paulson@20419
   177
wenzelm@24669
   178
val lambda_free = not o Term.has_abs;
wenzelm@20461
   179
wenzelm@32010
   180
val [f_B,g_B] = map (cterm_of @{theory}) (OldTerm.term_vars (prop_of @{thm abs_B}));
wenzelm@32010
   181
val [g_C,f_C] = map (cterm_of @{theory}) (OldTerm.term_vars (prop_of @{thm abs_C}));
wenzelm@32010
   182
val [f_S,g_S] = map (cterm_of @{theory}) (OldTerm.term_vars (prop_of @{thm abs_S}));
paulson@20863
   183
paulson@24827
   184
(*FIXME: requires more use of cterm constructors*)
paulson@24827
   185
fun abstract ct =
wenzelm@28544
   186
  let
wenzelm@28544
   187
      val thy = theory_of_cterm ct
paulson@25256
   188
      val Abs(x,_,body) = term_of ct
blanchet@35963
   189
      val Type(@{type_name fun}, [xT,bodyT]) = typ_of (ctyp_of_term ct)
paulson@24827
   190
      val cxT = ctyp_of thy xT and cbodyT = ctyp_of thy bodyT
wenzelm@27184
   191
      fun makeK() = instantiate' [SOME cxT, SOME cbodyT] [SOME (cterm_of thy body)] @{thm abs_K}
paulson@24827
   192
  in
paulson@24827
   193
      case body of
paulson@24827
   194
          Const _ => makeK()
paulson@24827
   195
        | Free _ => makeK()
paulson@24827
   196
        | Var _ => makeK()  (*though Var isn't expected*)
wenzelm@27184
   197
        | Bound 0 => instantiate' [SOME cxT] [] @{thm abs_I} (*identity: I*)
paulson@24827
   198
        | rator$rand =>
wenzelm@27184
   199
            if loose_bvar1 (rator,0) then (*C or S*)
wenzelm@27179
   200
               if loose_bvar1 (rand,0) then (*S*)
wenzelm@27179
   201
                 let val crator = cterm_of thy (Abs(x,xT,rator))
wenzelm@27179
   202
                     val crand = cterm_of thy (Abs(x,xT,rand))
wenzelm@27184
   203
                     val abs_S' = cterm_instantiate [(f_S,crator),(g_S,crand)] @{thm abs_S}
wenzelm@27184
   204
                     val (_,rhs) = Thm.dest_equals (cprop_of abs_S')
wenzelm@27179
   205
                 in
wenzelm@27179
   206
                   Thm.transitive abs_S' (Conv.binop_conv abstract rhs)
wenzelm@27179
   207
                 end
wenzelm@27179
   208
               else (*C*)
wenzelm@27179
   209
                 let val crator = cterm_of thy (Abs(x,xT,rator))
wenzelm@27184
   210
                     val abs_C' = cterm_instantiate [(f_C,crator),(g_C,cterm_of thy rand)] @{thm abs_C}
wenzelm@27184
   211
                     val (_,rhs) = Thm.dest_equals (cprop_of abs_C')
wenzelm@27179
   212
                 in
wenzelm@27179
   213
                   Thm.transitive abs_C' (Conv.fun_conv (Conv.arg_conv abstract) rhs)
wenzelm@27179
   214
                 end
wenzelm@27184
   215
            else if loose_bvar1 (rand,0) then (*B or eta*)
wenzelm@36945
   216
               if rand = Bound 0 then Thm.eta_conversion ct
wenzelm@27179
   217
               else (*B*)
wenzelm@27179
   218
                 let val crand = cterm_of thy (Abs(x,xT,rand))
wenzelm@27179
   219
                     val crator = cterm_of thy rator
wenzelm@27184
   220
                     val abs_B' = cterm_instantiate [(f_B,crator),(g_B,crand)] @{thm abs_B}
wenzelm@27184
   221
                     val (_,rhs) = Thm.dest_equals (cprop_of abs_B')
wenzelm@27179
   222
                 in
wenzelm@27179
   223
                   Thm.transitive abs_B' (Conv.arg_conv abstract rhs)
wenzelm@27179
   224
                 end
wenzelm@27179
   225
            else makeK()
paulson@24827
   226
        | _ => error "abstract: Bad term"
paulson@24827
   227
  end;
paulson@20863
   228
paulson@20419
   229
(*Traverse a theorem, declaring abstraction function definitions. String s is the suggested
wenzelm@28544
   230
  prefix for the constants.*)
paulson@24827
   231
fun combinators_aux ct =
wenzelm@36945
   232
  if lambda_free (term_of ct) then Thm.reflexive ct
paulson@24827
   233
  else
paulson@24827
   234
  case term_of ct of
paulson@24827
   235
      Abs _ =>
wenzelm@32994
   236
        let val (cv, cta) = Thm.dest_abs NONE ct
wenzelm@32994
   237
            val (v, _) = dest_Free (term_of cv)
wenzelm@27179
   238
            val u_th = combinators_aux cta
wenzelm@27179
   239
            val cu = Thm.rhs_of u_th
wenzelm@27179
   240
            val comb_eq = abstract (Thm.cabs cv cu)
wenzelm@36945
   241
        in Thm.transitive (Thm.abstract_rule v cv u_th) comb_eq end
wenzelm@32994
   242
    | _ $ _ =>
wenzelm@32994
   243
        let val (ct1, ct2) = Thm.dest_comb ct
wenzelm@36945
   244
        in  Thm.combination (combinators_aux ct1) (combinators_aux ct2)  end;
wenzelm@27184
   245
paulson@24827
   246
fun combinators th =
wenzelm@27184
   247
  if lambda_free (prop_of th) then th
paulson@24827
   248
  else
wenzelm@28544
   249
    let val th = Drule.eta_contraction_rule th
wenzelm@27179
   250
        val eqth = combinators_aux (cprop_of th)
wenzelm@36945
   251
    in  Thm.equal_elim eqth th   end
wenzelm@27184
   252
    handle THM (msg,_,_) =>
wenzelm@32091
   253
      (warning (cat_lines
wenzelm@32091
   254
        ["Error in the combinator translation of " ^ Display.string_of_thm_without_context th,
wenzelm@32091
   255
          "  Exception message: " ^ msg]);
paulson@25256
   256
       TrueI);  (*A type variable of sort {} will cause make abstraction fail.*)
paulson@16009
   257
paulson@16009
   258
(*cterms are used throughout for efficiency*)
wenzelm@29064
   259
val cTrueprop = Thm.cterm_of @{theory HOL} HOLogic.Trueprop;
paulson@16009
   260
paulson@16009
   261
(*cterm version of mk_cTrueprop*)
paulson@16009
   262
fun c_mkTrueprop A = Thm.capply cTrueprop A;
paulson@16009
   263
paulson@16009
   264
(*Given an abstraction over n variables, replace the bound variables by free
paulson@16009
   265
  ones. Return the body, along with the list of free variables.*)
wenzelm@20461
   266
fun c_variant_abs_multi (ct0, vars) =
paulson@16009
   267
      let val (cv,ct) = Thm.dest_abs NONE ct0
paulson@16009
   268
      in  c_variant_abs_multi (ct, cv::vars)  end
paulson@16009
   269
      handle CTERM _ => (ct0, rev vars);
paulson@16009
   270
wenzelm@20461
   271
(*Given the definition of a Skolem function, return a theorem to replace
wenzelm@20461
   272
  an existential formula by a use of that function.
paulson@18141
   273
   Example: "EX x. x : A & x ~: B ==> sko A B : A & sko A B ~: B"  [.] *)
wenzelm@20461
   274
fun skolem_of_def def =
wenzelm@22902
   275
  let val (c,rhs) = Thm.dest_equals (cprop_of (freeze_thm def))
paulson@16009
   276
      val (ch, frees) = c_variant_abs_multi (rhs, [])
paulson@18141
   277
      val (chilbert,cabs) = Thm.dest_comb ch
wenzelm@26627
   278
      val thy = Thm.theory_of_cterm chilbert
wenzelm@26627
   279
      val t = Thm.term_of chilbert
blanchet@35963
   280
      val T = case t of
blanchet@35963
   281
                Const (@{const_name Eps}, Type (@{type_name fun},[_,T])) => T
blanchet@35963
   282
              | _ => raise THM ("skolem_of_def: expected Eps", 0, [def])
wenzelm@22596
   283
      val cex = Thm.cterm_of thy (HOLogic.exists_const T)
paulson@16009
   284
      val ex_tm = c_mkTrueprop (Thm.capply cex cabs)
paulson@16009
   285
      and conc =  c_mkTrueprop (Drule.beta_conv cabs (Drule.list_comb(c,frees)));
haftmann@31454
   286
      fun tacf [prem] = rewrite_goals_tac [def] THEN rtac (prem RS @{thm someI_ex}) 1
wenzelm@23352
   287
  in  Goal.prove_internal [ex_tm] conc tacf
paulson@18141
   288
       |> forall_intr_list frees
wenzelm@26653
   289
       |> Thm.forall_elim_vars 0  (*Introduce Vars, but don't discharge defs.*)
wenzelm@35845
   290
       |> Thm.varifyT_global
paulson@18141
   291
  end;
paulson@16009
   292
paulson@24742
   293
paulson@20863
   294
(*Converts an Isabelle theorem (intro, elim or simp format, even higher-order) into NNF.*)
paulson@24937
   295
fun to_nnf th ctxt0 =
wenzelm@27179
   296
  let val th1 = th |> transform_elim |> zero_var_indexes
wenzelm@32262
   297
      val ((_, [th2]), ctxt) = Variable.import true [th1] ctxt0
wenzelm@32262
   298
      val th3 = th2
wenzelm@35625
   299
        |> Conv.fconv_rule Object_Logic.atomize
wenzelm@32262
   300
        |> Meson.make_nnf ctxt |> strip_lambdas ~1
paulson@24937
   301
  in  (th3, ctxt)  end;
paulson@16009
   302
paulson@18141
   303
(*Generate Skolem functions for a theorem supplied in nnf*)
paulson@24937
   304
fun assume_skolem_of_def s th =
wenzelm@36945
   305
  map (skolem_of_def o Thm.assume o (cterm_of (theory_of_thm th))) (assume_skofuns s th);
paulson@18141
   306
paulson@25007
   307
blanchet@35963
   308
(*** Blacklisting (FIXME: duplicated in "Sledgehammer_Fact_Filter"?) ***)
paulson@25007
   309
paulson@25007
   310
val max_lambda_nesting = 3;
wenzelm@27184
   311
paulson@25007
   312
fun excessive_lambdas (f$t, k) = excessive_lambdas (f,k) orelse excessive_lambdas (t,k)
paulson@25007
   313
  | excessive_lambdas (Abs(_,_,t), k) = k=0 orelse excessive_lambdas (t,k-1)
paulson@25007
   314
  | excessive_lambdas _ = false;
paulson@25007
   315
paulson@25007
   316
fun is_formula_type T = (T = HOLogic.boolT orelse T = propT);
paulson@25007
   317
paulson@25007
   318
(*Don't count nested lambdas at the level of formulas, as they are quantifiers*)
paulson@25007
   319
fun excessive_lambdas_fm Ts (Abs(_,T,t)) = excessive_lambdas_fm (T::Ts) t
paulson@25007
   320
  | excessive_lambdas_fm Ts t =
paulson@25007
   321
      if is_formula_type (fastype_of1 (Ts, t))
paulson@25007
   322
      then exists (excessive_lambdas_fm Ts) (#2 (strip_comb t))
paulson@25007
   323
      else excessive_lambdas (t, max_lambda_nesting);
paulson@25007
   324
wenzelm@33027
   325
(*The max apply_depth of any metis call in Metis_Examples (on 31-10-2007) was 11.*)
paulson@25256
   326
val max_apply_depth = 15;
wenzelm@27184
   327
paulson@25256
   328
fun apply_depth (f$t) = Int.max (apply_depth f, apply_depth t + 1)
paulson@25256
   329
  | apply_depth (Abs(_,_,t)) = apply_depth t
paulson@25256
   330
  | apply_depth _ = 0;
paulson@25256
   331
wenzelm@27184
   332
fun too_complex t =
wenzelm@27184
   333
  apply_depth t > max_apply_depth orelse
paulson@26562
   334
  Meson.too_many_clauses NONE t orelse
paulson@25256
   335
  excessive_lambdas_fm [] t;
wenzelm@27184
   336
paulson@25243
   337
fun is_strange_thm th =
paulson@25243
   338
  case head_of (concl_of th) of
blanchet@35963
   339
      Const (a, _) => (a <> @{const_name Trueprop} andalso
blanchet@35963
   340
                       a <> @{const_name "=="})
paulson@25243
   341
    | _ => false;
paulson@25243
   342
wenzelm@27184
   343
fun bad_for_atp th =
wenzelm@33306
   344
  too_complex (prop_of th)
wenzelm@35568
   345
  orelse exists_type type_has_topsort (prop_of th)
paulson@25761
   346
  orelse is_strange_thm th;
paulson@25243
   347
blanchet@35963
   348
(* FIXME: put other record thms here, or declare as "no_atp" *)
paulson@25007
   349
val multi_base_blacklist =
blanchet@35963
   350
  ["defs", "select_defs", "update_defs", "induct", "inducts", "split", "splits",
blanchet@35963
   351
   "split_asm", "cases", "ext_cases"];
paulson@25007
   352
paulson@22731
   353
fun fake_name th =
wenzelm@27865
   354
  if Thm.has_name_hint th then flatten_name (Thm.get_name_hint th)
paulson@22731
   355
  else gensym "unknown_thm_";
paulson@22731
   356
wenzelm@27184
   357
(*Skolemize a named theorem, with Skolem functions as additional premises.*)
wenzelm@27184
   358
fun skolem_thm (s, th) =
wenzelm@30364
   359
  if member (op =) multi_base_blacklist (Long_Name.base_name s) orelse bad_for_atp th then []
wenzelm@27184
   360
  else
wenzelm@27184
   361
    let
wenzelm@36603
   362
      val ctxt0 = Variable.global_thm_context th
wenzelm@27184
   363
      val (nnfth, ctxt1) = to_nnf th ctxt0
wenzelm@27184
   364
      val (cnfs, ctxt2) = Meson.make_cnf (assume_skolem_of_def s nnfth) nnfth ctxt1
wenzelm@27184
   365
    in  cnfs |> map combinators |> Variable.export ctxt2 ctxt0 |> Meson.finish_cnf  end
wenzelm@27184
   366
    handle THM _ => [];
wenzelm@27184
   367
paulson@24742
   368
(*The cache prevents repeated clausification of a theorem, and also repeated declaration of
paulson@24742
   369
  Skolem functions.*)
wenzelm@33522
   370
structure ThmCache = Theory_Data
wenzelm@22846
   371
(
wenzelm@28544
   372
  type T = thm list Thmtab.table * unit Symtab.table;
wenzelm@28544
   373
  val empty = (Thmtab.empty, Symtab.empty);
wenzelm@26618
   374
  val extend = I;
wenzelm@33522
   375
  fun merge ((cache1, seen1), (cache2, seen2)) : T =
wenzelm@27184
   376
    (Thmtab.merge (K true) (cache1, cache2), Symtab.merge (K true) (seen1, seen2));
wenzelm@22846
   377
);
paulson@22516
   378
wenzelm@27184
   379
val lookup_cache = Thmtab.lookup o #1 o ThmCache.get;
wenzelm@27184
   380
val already_seen = Symtab.defined o #2 o ThmCache.get;
wenzelm@20461
   381
wenzelm@27184
   382
val update_cache = ThmCache.map o apfst o Thmtab.update;
wenzelm@27184
   383
fun mark_seen name = ThmCache.map (apsnd (Symtab.update (name, ())));
paulson@25007
   384
blanchet@36228
   385
(* Convert Isabelle theorems into axiom clauses. *)
wenzelm@27179
   386
fun cnf_axiom thy th0 =
wenzelm@27184
   387
  let val th = Thm.transfer thy th0 in
wenzelm@27184
   388
    case lookup_cache thy th of
wenzelm@27184
   389
      NONE => map Thm.close_derivation (skolem_thm (fake_name th, th))
wenzelm@27184
   390
    | SOME cls => cls
paulson@22516
   391
  end;
paulson@15347
   392
paulson@18141
   393
paulson@22471
   394
(**** Translate a set of theorems into CNF ****)
paulson@15347
   395
paulson@19894
   396
fun pair_name_cls k (n, []) = []
paulson@19894
   397
  | pair_name_cls k (n, cls::clss) = (cls, (n,k)) :: pair_name_cls (k+1) (n, clss)
wenzelm@20461
   398
wenzelm@27179
   399
fun cnf_rules_pairs_aux _ pairs [] = pairs
wenzelm@27179
   400
  | cnf_rules_pairs_aux thy pairs ((name,th)::ths) =
wenzelm@27179
   401
      let val pairs' = (pair_name_cls 0 (name, cnf_axiom thy th)) @ pairs
blanchet@35826
   402
                       handle THM _ => pairs |
blanchet@35865
   403
                              CLAUSE _ => pairs
wenzelm@27179
   404
      in  cnf_rules_pairs_aux thy pairs' ths  end;
wenzelm@20461
   405
paulson@21290
   406
(*The combination of rev and tail recursion preserves the original order*)
wenzelm@27179
   407
fun cnf_rules_pairs thy l = cnf_rules_pairs_aux thy [] (rev l);
mengj@19353
   408
mengj@19196
   409
blanchet@35865
   410
(**** Convert all facts of the theory into FOL or HOL clauses ****)
paulson@15347
   411
wenzelm@28544
   412
local
wenzelm@28544
   413
wenzelm@28544
   414
fun skolem_def (name, th) thy =
wenzelm@36603
   415
  let val ctxt0 = Variable.global_thm_context th in
wenzelm@28544
   416
    (case try (to_nnf th) ctxt0 of
wenzelm@28544
   417
      NONE => (NONE, thy)
wenzelm@28544
   418
    | SOME (nnfth, ctxt1) =>
wenzelm@28544
   419
        let val (defs, thy') = declare_skofuns (flatten_name name) nnfth thy
wenzelm@28544
   420
        in (SOME (th, ctxt0, ctxt1, nnfth, defs), thy') end)
wenzelm@28544
   421
  end;
paulson@24742
   422
wenzelm@28544
   423
fun skolem_cnfs (th, ctxt0, ctxt1, nnfth, defs) =
wenzelm@28544
   424
  let
wenzelm@28544
   425
    val (cnfs, ctxt2) = Meson.make_cnf (map skolem_of_def defs) nnfth ctxt1;
wenzelm@28544
   426
    val cnfs' = cnfs
wenzelm@28544
   427
      |> map combinators
wenzelm@28544
   428
      |> Variable.export ctxt2 ctxt0
wenzelm@28544
   429
      |> Meson.finish_cnf
wenzelm@28544
   430
      |> map Thm.close_derivation;
wenzelm@28544
   431
    in (th, cnfs') end;
wenzelm@28544
   432
wenzelm@28544
   433
in
paulson@24742
   434
wenzelm@27184
   435
fun saturate_skolem_cache thy =
wenzelm@28544
   436
  let
wenzelm@33306
   437
    val facts = PureThy.facts_of thy;
wenzelm@33306
   438
    val new_facts = (facts, []) |-> Facts.fold_static (fn (name, ths) =>
wenzelm@33306
   439
      if Facts.is_concealed facts name orelse already_seen thy name then I
wenzelm@33306
   440
      else cons (name, ths));
wenzelm@28544
   441
    val new_thms = (new_facts, []) |-> fold (fn (name, ths) =>
wenzelm@30364
   442
      if member (op =) multi_base_blacklist (Long_Name.base_name name) then I
wenzelm@28544
   443
      else fold_index (fn (i, th) =>
wenzelm@28544
   444
        if bad_for_atp th orelse is_some (lookup_cache thy th) then I
wenzelm@28544
   445
        else cons (name ^ "_" ^ string_of_int (i + 1), Thm.transfer thy th)) ths);
wenzelm@28544
   446
  in
wenzelm@28544
   447
    if null new_facts then NONE
wenzelm@28544
   448
    else
wenzelm@28544
   449
      let
wenzelm@28544
   450
        val (defs, thy') = thy
wenzelm@28544
   451
          |> fold (mark_seen o #1) new_facts
wenzelm@28544
   452
          |> fold_map skolem_def (sort_distinct (Thm.thm_ord o pairself snd) new_thms)
wenzelm@28544
   453
          |>> map_filter I;
wenzelm@29368
   454
        val cache_entries = Par_List.map skolem_cnfs defs;
wenzelm@28544
   455
      in SOME (fold update_cache cache_entries thy') end
wenzelm@28544
   456
  end;
wenzelm@27184
   457
wenzelm@28544
   458
end;
paulson@24854
   459
wenzelm@32740
   460
val suppress_endtheory = Unsynchronized.ref false;
wenzelm@27184
   461
wenzelm@27184
   462
fun clause_cache_endtheory thy =
wenzelm@27184
   463
  if ! suppress_endtheory then NONE
wenzelm@27184
   464
  else saturate_skolem_cache thy;
wenzelm@27184
   465
paulson@20457
   466
paulson@22516
   467
(*The cache can be kept smaller by inspecting the prop of each thm. Can ignore all that are
paulson@22516
   468
  lambda_free, but then the individual theory caches become much bigger.*)
paulson@21071
   469
wenzelm@27179
   470
blanchet@36398
   471
fun strip_subgoal goal i =
blanchet@36398
   472
  let
blanchet@36398
   473
    val (t, frees) = Logic.goal_params (prop_of goal) i
blanchet@36398
   474
    val hyp_ts = t |> Logic.strip_assums_hyp |> map (curry subst_bounds frees)
blanchet@36398
   475
    val concl_t = t |> Logic.strip_assums_concl |> curry subst_bounds frees
blanchet@36478
   476
  in (rev (map dest_Free frees), hyp_ts, concl_t) end
blanchet@36398
   477
paulson@21999
   478
(*** Converting a subgoal into negated conjecture clauses. ***)
paulson@21999
   479
wenzelm@32262
   480
fun neg_skolemize_tac ctxt =
wenzelm@35625
   481
  EVERY' [rtac ccontr, Object_Logic.atomize_prems_tac, Meson.skolemize_tac ctxt];
paulson@22471
   482
blanchet@36398
   483
fun neg_skolemize_tac ctxt =
blanchet@36398
   484
  EVERY' [rtac ccontr, Object_Logic.atomize_prems_tac, Meson.skolemize_tac ctxt];
blanchet@36398
   485
blanchet@35869
   486
val neg_clausify =
blanchet@36398
   487
  single #> Meson.make_clauses_unsorted #> map combinators #> Meson.finish_cnf
paulson@21999
   488
wenzelm@32257
   489
fun neg_conjecture_clauses ctxt st0 n =
wenzelm@32257
   490
  let
wenzelm@32262
   491
    val st = Seq.hd (neg_skolemize_tac ctxt n st0)
wenzelm@32257
   492
    val ({params, prems, ...}, _) = Subgoal.focus (Variable.set_body false ctxt) n st
blanchet@36398
   493
  in
blanchet@36398
   494
    (map neg_clausify prems, map (Term.dest_Free o Thm.term_of o #2) params)
blanchet@36398
   495
  end
paulson@21999
   496
wenzelm@24669
   497
(*Conversion of a subgoal to conjecture clauses. Each clause has
paulson@21999
   498
  leading !!-bound universal variables, to express generality. *)
wenzelm@32257
   499
fun neg_clausify_tac ctxt =
wenzelm@32262
   500
  neg_skolemize_tac ctxt THEN'
wenzelm@32257
   501
  SUBGOAL (fn (prop, i) =>
wenzelm@32257
   502
    let val ts = Logic.strip_assums_hyp prop in
wenzelm@32257
   503
      EVERY'
wenzelm@32283
   504
       [Subgoal.FOCUS
wenzelm@32257
   505
         (fn {prems, ...} =>
wenzelm@32257
   506
           (Method.insert_tac
blanchet@36398
   507
             (map forall_intr_vars (maps neg_clausify prems)) i)) ctxt,
wenzelm@32257
   508
        REPEAT_DETERM_N (length ts) o etac thin_rl] i
paulson@21999
   509
     end);
paulson@21999
   510
wenzelm@27184
   511
wenzelm@27184
   512
(** setup **)
wenzelm@27184
   513
wenzelm@27184
   514
val setup =
wenzelm@27184
   515
  perhaps saturate_skolem_cache #>
wenzelm@27184
   516
  Theory.at_end clause_cache_endtheory;
paulson@18510
   517
wenzelm@20461
   518
end;