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