src/HOL/Tools/Sledgehammer/clausifier.ML
author blanchet
Mon Jun 28 17:32:28 2010 +0200 (2010-06-28)
changeset 37617 f73cd4069f69
parent 37616 c8d2d84d6011
child 37618 fa57a87f92a0
permissions -rw-r--r--
always perform "inline" skolemization, polymorphism or not, Skolem cache or not
blanchet@37574
     1
(*  Title:      HOL/Tools/Sledgehammer/clausifier.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@37574
     8
signature CLAUSIFIER =
wenzelm@21505
     9
sig
blanchet@37500
    10
  type cnf_thm = thm * ((string * int) * thm)
blanchet@37543
    11
wenzelm@32955
    12
  val trace: bool Unsynchronized.ref
blanchet@37410
    13
  val skolem_theory_name: string
blanchet@35865
    14
  val skolem_prefix: string
blanchet@36492
    15
  val skolem_infix: string
blanchet@37399
    16
  val is_skolem_const_name: string -> bool
blanchet@37572
    17
  val num_type_args: theory -> string -> int
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@37584
    23
  val saturate_cache: theory -> theory option
blanchet@37584
    24
  val auto_saturate_cache: bool Unsynchronized.ref
blanchet@36398
    25
  val neg_clausify: thm -> thm list
blanchet@36398
    26
  val neg_conjecture_clauses:
blanchet@36398
    27
    Proof.context -> thm -> int -> thm list list * (string * typ) list
wenzelm@24669
    28
  val setup: theory -> theory
wenzelm@21505
    29
end;
mengj@19196
    30
blanchet@37574
    31
structure Clausifier : CLAUSIFIER =
paulson@15997
    32
struct
paulson@15347
    33
blanchet@37500
    34
type cnf_thm = thm * ((string * int) * thm)
blanchet@37500
    35
wenzelm@32955
    36
val trace = Unsynchronized.ref false;
blanchet@35865
    37
fun trace_msg msg = if !trace then tracing (msg ()) else ();
blanchet@35865
    38
blanchet@37616
    39
val skolem_theory_name = "Sledgehammer" ^ Long_Name.separator ^ "Sko"
blanchet@35865
    40
val skolem_prefix = "sko_"
blanchet@36492
    41
val skolem_infix = "$"
wenzelm@32955
    42
wenzelm@35568
    43
val type_has_topsort = Term.exists_subtype
wenzelm@35568
    44
  (fn TFree (_, []) => true
wenzelm@35568
    45
    | TVar (_, []) => true
wenzelm@35568
    46
    | _ => false);
wenzelm@27184
    47
wenzelm@28544
    48
paulson@15997
    49
(**** Transformation of Elimination Rules into First-Order Formulas****)
paulson@15347
    50
wenzelm@29064
    51
val cfalse = cterm_of @{theory HOL} HOLogic.false_const;
wenzelm@29064
    52
val ctp_false = cterm_of @{theory HOL} (HOLogic.mk_Trueprop HOLogic.false_const);
wenzelm@20461
    53
paulson@21430
    54
(*Converts an elim-rule into an equivalent theorem that does not have the
paulson@21430
    55
  predicate variable.  Leaves other theorems unchanged.  We simply instantiate the
paulson@21430
    56
  conclusion variable to False.*)
paulson@16009
    57
fun transform_elim th =
paulson@21430
    58
  case concl_of th of    (*conclusion variable*)
blanchet@35963
    59
       @{const Trueprop} $ (v as Var (_, @{typ bool})) =>
wenzelm@29064
    60
           Thm.instantiate ([], [(cterm_of @{theory HOL} v, cfalse)]) th
blanchet@35963
    61
    | v as Var(_, @{typ prop}) =>
wenzelm@29064
    62
           Thm.instantiate ([], [(cterm_of @{theory HOL} v, ctp_false)]) th
paulson@21430
    63
    | _ => th;
paulson@15997
    64
paulson@24742
    65
(*To enforce single-threading*)
paulson@24742
    66
exception Clausify_failure of theory;
wenzelm@20461
    67
wenzelm@28544
    68
paulson@16009
    69
(**** SKOLEMIZATION BY INFERENCE (lcp) ****)
paulson@16009
    70
blanchet@36492
    71
(*Keep the full complexity of the original name*)
blanchet@36492
    72
fun flatten_name s = space_implode "_X" (Long_Name.explode s);
blanchet@36492
    73
blanchet@37399
    74
fun skolem_name thm_name j var_name =
blanchet@37399
    75
  skolem_prefix ^ thm_name ^ "_" ^ Int.toString j ^
blanchet@36492
    76
  skolem_infix ^ (if var_name = "" then "g" else flatten_name var_name)
blanchet@36492
    77
blanchet@37399
    78
(* Hack: Could return false positives (e.g., a user happens to declare a
blanchet@37399
    79
   constant called "SomeTheory.sko_means_shoe_in_$wedish". *)
blanchet@37399
    80
val is_skolem_const_name =
blanchet@37399
    81
  Long_Name.base_name
blanchet@37399
    82
  #> String.isPrefix skolem_prefix andf String.isSubstring skolem_infix
blanchet@37399
    83
blanchet@37572
    84
(* The number of type arguments of a constant, zero if it's monomorphic. For
blanchet@37572
    85
   (instances of) Skolem pseudoconstants, this information is encoded in the
blanchet@37572
    86
   constant name. *)
blanchet@37572
    87
fun num_type_args thy s =
blanchet@37572
    88
  if String.isPrefix skolem_theory_name s then
blanchet@37572
    89
    s |> unprefix skolem_theory_name
blanchet@37572
    90
      |> space_explode skolem_infix |> hd
blanchet@37572
    91
      |> space_explode "_" |> List.last |> Int.fromString |> the
blanchet@37572
    92
  else
blanchet@37572
    93
    (s, Sign.the_const_type thy s) |> Sign.const_typargs thy |> length
blanchet@37572
    94
blanchet@37410
    95
fun mk_skolem_id t =
blanchet@37436
    96
  let val T = fastype_of t in
blanchet@37496
    97
    Const (@{const_name skolem_id}, T --> T) $ t
blanchet@37436
    98
  end
blanchet@37410
    99
blanchet@37617
   100
fun beta_eta_under_lambdas (Abs (s, T, t')) =
blanchet@37617
   101
    Abs (s, T, beta_eta_under_lambdas t')
blanchet@37617
   102
  | beta_eta_under_lambdas t = Envir.beta_eta_contract t
blanchet@37512
   103
paulson@18141
   104
(*Traverse a theorem, accumulating Skolem function definitions.*)
blanchet@37617
   105
fun assume_skolem_funs th =
blanchet@37399
   106
  let
blanchet@37617
   107
    fun dec_sko (Const (@{const_name Ex}, _) $ (body as Abs (s', T, p))) rhss =
blanchet@37399
   108
        (*Existential: declare a Skolem function, then insert into body and continue*)
blanchet@37399
   109
        let
blanchet@37617
   110
          val args = OldTerm.term_frees body
blanchet@37399
   111
          val Ts = map type_of args
blanchet@37399
   112
          val cT = Ts ---> T (* FIXME: use "skolem_type_and_args" *)
blanchet@37500
   113
          (* Forms a lambda-abstraction over the formal parameters *)
blanchet@37500
   114
          val rhs =
blanchet@37500
   115
            list_abs_free (map dest_Free args,
blanchet@37617
   116
                           HOLogic.choice_const T $ beta_eta_under_lambdas body)
blanchet@37518
   117
            |> mk_skolem_id
blanchet@37518
   118
          val comb = list_comb (rhs, args)
blanchet@37617
   119
        in dec_sko (subst_bound (comb, p)) (rhs :: rhss) end
blanchet@37617
   120
      | dec_sko (Const (@{const_name All},_) $ Abs (a, T, p)) rhss =
blanchet@37399
   121
        (*Universal quant: insert a free variable into body and continue*)
blanchet@37399
   122
        let val fname = Name.variant (OldTerm.add_term_names (p,[])) a
blanchet@37617
   123
        in dec_sko (subst_bound (Free(fname,T), p)) rhss end
blanchet@37617
   124
      | dec_sko (@{const "op &"} $ p $ q) rhss = rhss |> dec_sko p |> dec_sko q
blanchet@37617
   125
      | dec_sko (@{const "op |"} $ p $ q) rhss = rhss |> dec_sko p |> dec_sko q
blanchet@37617
   126
      | dec_sko (@{const Trueprop} $ p) rhss = dec_sko p rhss
blanchet@37617
   127
      | dec_sko _ rhss = rhss
paulson@20419
   128
  in  dec_sko (prop_of th) []  end;
paulson@20419
   129
paulson@20419
   130
paulson@24827
   131
(**** REPLACING ABSTRACTIONS BY COMBINATORS ****)
paulson@20419
   132
paulson@20419
   133
(*Returns the vars of a theorem*)
paulson@20419
   134
fun vars_of_thm th =
wenzelm@22691
   135
  map (Thm.cterm_of (theory_of_thm th) o Var) (Thm.fold_terms Term.add_vars th []);
paulson@20419
   136
blanchet@37540
   137
val fun_cong_all = @{thm expand_fun_eq [THEN iffD1]}
paulson@20419
   138
blanchet@37540
   139
(* Removes the lambdas from an equation of the form t = (%x. u). *)
blanchet@37540
   140
fun extensionalize th =
blanchet@37540
   141
  case prop_of th of
blanchet@37540
   142
    _ $ (Const (@{const_name "op ="}, Type (_, [Type (@{type_name fun}, _), _]))
blanchet@37540
   143
         $ _ $ Abs (s, _, _)) => extensionalize (th RS fun_cong_all)
blanchet@37540
   144
  | _ => th
paulson@20419
   145
blanchet@37416
   146
fun is_quasi_lambda_free (Const (@{const_name skolem_id}, _) $ _) = true
blanchet@37416
   147
  | is_quasi_lambda_free (t1 $ t2) =
blanchet@37416
   148
    is_quasi_lambda_free t1 andalso is_quasi_lambda_free t2
blanchet@37416
   149
  | is_quasi_lambda_free (Abs _) = false
blanchet@37416
   150
  | is_quasi_lambda_free _ = true
wenzelm@20461
   151
wenzelm@32010
   152
val [f_B,g_B] = map (cterm_of @{theory}) (OldTerm.term_vars (prop_of @{thm abs_B}));
wenzelm@32010
   153
val [g_C,f_C] = map (cterm_of @{theory}) (OldTerm.term_vars (prop_of @{thm abs_C}));
wenzelm@32010
   154
val [f_S,g_S] = map (cterm_of @{theory}) (OldTerm.term_vars (prop_of @{thm abs_S}));
paulson@20863
   155
paulson@24827
   156
(*FIXME: requires more use of cterm constructors*)
paulson@24827
   157
fun abstract ct =
wenzelm@28544
   158
  let
wenzelm@28544
   159
      val thy = theory_of_cterm ct
paulson@25256
   160
      val Abs(x,_,body) = term_of ct
blanchet@35963
   161
      val Type(@{type_name fun}, [xT,bodyT]) = typ_of (ctyp_of_term ct)
paulson@24827
   162
      val cxT = ctyp_of thy xT and cbodyT = ctyp_of thy bodyT
wenzelm@27184
   163
      fun makeK() = instantiate' [SOME cxT, SOME cbodyT] [SOME (cterm_of thy body)] @{thm abs_K}
paulson@24827
   164
  in
paulson@24827
   165
      case body of
paulson@24827
   166
          Const _ => makeK()
paulson@24827
   167
        | Free _ => makeK()
paulson@24827
   168
        | Var _ => makeK()  (*though Var isn't expected*)
wenzelm@27184
   169
        | Bound 0 => instantiate' [SOME cxT] [] @{thm abs_I} (*identity: I*)
paulson@24827
   170
        | rator$rand =>
wenzelm@27184
   171
            if loose_bvar1 (rator,0) then (*C or S*)
wenzelm@27179
   172
               if loose_bvar1 (rand,0) then (*S*)
wenzelm@27179
   173
                 let val crator = cterm_of thy (Abs(x,xT,rator))
wenzelm@27179
   174
                     val crand = cterm_of thy (Abs(x,xT,rand))
wenzelm@27184
   175
                     val abs_S' = cterm_instantiate [(f_S,crator),(g_S,crand)] @{thm abs_S}
wenzelm@27184
   176
                     val (_,rhs) = Thm.dest_equals (cprop_of abs_S')
wenzelm@27179
   177
                 in
wenzelm@27179
   178
                   Thm.transitive abs_S' (Conv.binop_conv abstract rhs)
wenzelm@27179
   179
                 end
wenzelm@27179
   180
               else (*C*)
wenzelm@27179
   181
                 let val crator = cterm_of thy (Abs(x,xT,rator))
wenzelm@27184
   182
                     val abs_C' = cterm_instantiate [(f_C,crator),(g_C,cterm_of thy rand)] @{thm abs_C}
wenzelm@27184
   183
                     val (_,rhs) = Thm.dest_equals (cprop_of abs_C')
wenzelm@27179
   184
                 in
wenzelm@27179
   185
                   Thm.transitive abs_C' (Conv.fun_conv (Conv.arg_conv abstract) rhs)
wenzelm@27179
   186
                 end
wenzelm@27184
   187
            else if loose_bvar1 (rand,0) then (*B or eta*)
wenzelm@36945
   188
               if rand = Bound 0 then Thm.eta_conversion ct
wenzelm@27179
   189
               else (*B*)
wenzelm@27179
   190
                 let val crand = cterm_of thy (Abs(x,xT,rand))
wenzelm@27179
   191
                     val crator = cterm_of thy rator
wenzelm@27184
   192
                     val abs_B' = cterm_instantiate [(f_B,crator),(g_B,crand)] @{thm abs_B}
wenzelm@27184
   193
                     val (_,rhs) = Thm.dest_equals (cprop_of abs_B')
blanchet@37349
   194
                 in Thm.transitive abs_B' (Conv.arg_conv abstract rhs) end
wenzelm@27179
   195
            else makeK()
blanchet@37349
   196
        | _ => raise Fail "abstract: Bad term"
paulson@24827
   197
  end;
paulson@20863
   198
blanchet@37349
   199
(* Traverse a theorem, remplacing lambda-abstractions with combinators. *)
blanchet@37349
   200
fun do_introduce_combinators ct =
blanchet@37416
   201
  if is_quasi_lambda_free (term_of ct) then
blanchet@37349
   202
    Thm.reflexive ct
blanchet@37349
   203
  else case term_of ct of
blanchet@37349
   204
    Abs _ =>
blanchet@37349
   205
    let
blanchet@37349
   206
      val (cv, cta) = Thm.dest_abs NONE ct
blanchet@37349
   207
      val (v, _) = dest_Free (term_of cv)
blanchet@37349
   208
      val u_th = do_introduce_combinators cta
blanchet@37349
   209
      val cu = Thm.rhs_of u_th
blanchet@37349
   210
      val comb_eq = abstract (Thm.cabs cv cu)
blanchet@37349
   211
    in Thm.transitive (Thm.abstract_rule v cv u_th) comb_eq end
blanchet@37349
   212
  | _ $ _ =>
blanchet@37349
   213
    let val (ct1, ct2) = Thm.dest_comb ct in
blanchet@37349
   214
        Thm.combination (do_introduce_combinators ct1)
blanchet@37349
   215
                        (do_introduce_combinators ct2)
blanchet@37349
   216
    end
blanchet@37349
   217
blanchet@37349
   218
fun introduce_combinators th =
blanchet@37416
   219
  if is_quasi_lambda_free (prop_of th) then
blanchet@37349
   220
    th
paulson@24827
   221
  else
blanchet@37349
   222
    let
blanchet@37349
   223
      val th = Drule.eta_contraction_rule th
blanchet@37349
   224
      val eqth = do_introduce_combinators (cprop_of th)
blanchet@37349
   225
    in Thm.equal_elim eqth th end
blanchet@37349
   226
    handle THM (msg, _, _) =>
blanchet@37349
   227
           (warning ("Error in the combinator translation of " ^
blanchet@37349
   228
                     Display.string_of_thm_without_context th ^
blanchet@37349
   229
                     "\nException message: " ^ msg ^ ".");
blanchet@37349
   230
            (* A type variable of sort "{}" will make abstraction fail. *)
blanchet@37349
   231
            TrueI)
paulson@16009
   232
paulson@16009
   233
(*cterms are used throughout for efficiency*)
wenzelm@29064
   234
val cTrueprop = Thm.cterm_of @{theory HOL} HOLogic.Trueprop;
paulson@16009
   235
paulson@16009
   236
(*Given an abstraction over n variables, replace the bound variables by free
paulson@16009
   237
  ones. Return the body, along with the list of free variables.*)
wenzelm@20461
   238
fun c_variant_abs_multi (ct0, vars) =
paulson@16009
   239
      let val (cv,ct) = Thm.dest_abs NONE ct0
paulson@16009
   240
      in  c_variant_abs_multi (ct, cv::vars)  end
paulson@16009
   241
      handle CTERM _ => (ct0, rev vars);
paulson@16009
   242
blanchet@37617
   243
val skolem_id_def_raw = @{thms skolem_id_def_raw}
blanchet@37617
   244
blanchet@37617
   245
(* Given the definition of a Skolem function, return a theorem to replace
blanchet@37617
   246
   an existential formula by a use of that function.
paulson@18141
   247
   Example: "EX x. x : A & x ~: B ==> sko A B : A & sko A B ~: B"  [.] *)
blanchet@37617
   248
fun skolem_theorem_of_def thy rhs0 =
blanchet@37399
   249
  let
blanchet@37617
   250
    val rhs = rhs0 |> Type.legacy_freeze_thaw |> #1 |> Thm.cterm_of thy
blanchet@37617
   251
    val rhs' = rhs |> Thm.dest_comb |> snd
blanchet@37617
   252
    val (ch, frees) = c_variant_abs_multi (rhs', [])
blanchet@37617
   253
    val (hilbert, cabs) = ch |> Thm.dest_comb |>> term_of
blanchet@37617
   254
    val T =
blanchet@37617
   255
      case hilbert of
blanchet@37617
   256
        Const (@{const_name Eps}, Type (@{type_name fun}, [_, T])) => T
blanchet@37617
   257
      | _ => raise TERM ("skolem_theorem_of_def: expected \"Eps\"", [hilbert])
blanchet@37617
   258
    val cex = Thm.cterm_of thy (HOLogic.exists_const T)
blanchet@37617
   259
    val ex_tm = Thm.capply cTrueprop (Thm.capply cex cabs)
blanchet@37617
   260
    and conc =
blanchet@37617
   261
      Drule.list_comb (rhs, frees)
blanchet@37617
   262
      |> Drule.beta_conv cabs |> Thm.capply cTrueprop
blanchet@37617
   263
    fun tacf [prem] =
blanchet@37617
   264
      rewrite_goals_tac skolem_id_def_raw
blanchet@37617
   265
      THEN rtac ((prem |> rewrite_rule skolem_id_def_raw)
blanchet@37617
   266
                 RS @{thm someI_ex}) 1
blanchet@37617
   267
  in
blanchet@37617
   268
    Goal.prove_internal [ex_tm] conc tacf
blanchet@37617
   269
    |> forall_intr_list frees
blanchet@37617
   270
    |> Thm.forall_elim_vars 0  (*Introduce Vars, but don't discharge defs.*)
blanchet@37617
   271
    |> Thm.varifyT_global
blanchet@37617
   272
  end
paulson@24742
   273
paulson@20863
   274
(*Converts an Isabelle theorem (intro, elim or simp format, even higher-order) into NNF.*)
paulson@24937
   275
fun to_nnf th ctxt0 =
wenzelm@27179
   276
  let val th1 = th |> transform_elim |> zero_var_indexes
wenzelm@32262
   277
      val ((_, [th2]), ctxt) = Variable.import true [th1] ctxt0
blanchet@37540
   278
      val th3 = th2 |> Conv.fconv_rule Object_Logic.atomize
blanchet@37540
   279
                    |> extensionalize
blanchet@37540
   280
                    |> Meson.make_nnf ctxt
paulson@24937
   281
  in  (th3, ctxt)  end;
paulson@16009
   282
blanchet@37349
   283
(*** Blacklisting (more in "Sledgehammer_Fact_Filter") ***)
paulson@25007
   284
blanchet@37348
   285
val max_lambda_nesting = 3
wenzelm@27184
   286
blanchet@37348
   287
fun term_has_too_many_lambdas max (t1 $ t2) =
blanchet@37348
   288
    exists (term_has_too_many_lambdas max) [t1, t2]
blanchet@37348
   289
  | term_has_too_many_lambdas max (Abs (_, _, t)) =
blanchet@37348
   290
    max = 0 orelse term_has_too_many_lambdas (max - 1) t
blanchet@37348
   291
  | term_has_too_many_lambdas _ _ = false
paulson@25007
   292
blanchet@37348
   293
fun is_formula_type T = (T = HOLogic.boolT orelse T = propT)
paulson@25007
   294
blanchet@37348
   295
(* Don't count nested lambdas at the level of formulas, since they are
blanchet@37348
   296
   quantifiers. *)
blanchet@37348
   297
fun formula_has_too_many_lambdas Ts (Abs (_, T, t)) =
blanchet@37348
   298
    formula_has_too_many_lambdas (T :: Ts) t
blanchet@37348
   299
  | formula_has_too_many_lambdas Ts t =
blanchet@37348
   300
    if is_formula_type (fastype_of1 (Ts, t)) then
blanchet@37348
   301
      exists (formula_has_too_many_lambdas Ts) (#2 (strip_comb t))
blanchet@37348
   302
    else
blanchet@37348
   303
      term_has_too_many_lambdas max_lambda_nesting t
paulson@25007
   304
blanchet@37348
   305
(* The max apply depth of any "metis" call in "Metis_Examples" (on 31-10-2007)
blanchet@37348
   306
   was 11. *)
blanchet@37348
   307
val max_apply_depth = 15
wenzelm@27184
   308
blanchet@37348
   309
fun apply_depth (f $ t) = Int.max (apply_depth f, apply_depth t + 1)
blanchet@37348
   310
  | apply_depth (Abs (_, _, t)) = apply_depth t
blanchet@37348
   311
  | apply_depth _ = 0
paulson@25256
   312
blanchet@37348
   313
fun is_formula_too_complex t =
blanchet@37348
   314
  apply_depth t > max_apply_depth orelse Meson.too_many_clauses NONE t orelse
blanchet@37348
   315
  formula_has_too_many_lambdas [] t
wenzelm@27184
   316
paulson@25243
   317
fun is_strange_thm th =
paulson@25243
   318
  case head_of (concl_of th) of
blanchet@35963
   319
      Const (a, _) => (a <> @{const_name Trueprop} andalso
blanchet@35963
   320
                       a <> @{const_name "=="})
paulson@25243
   321
    | _ => false;
paulson@25243
   322
blanchet@37348
   323
fun is_theorem_bad_for_atps thm =
blanchet@37348
   324
  let val t = prop_of thm in
blanchet@37348
   325
    is_formula_too_complex t orelse exists_type type_has_topsort t orelse
blanchet@37348
   326
    is_strange_thm thm
blanchet@37348
   327
  end
paulson@25243
   328
blanchet@35963
   329
(* FIXME: put other record thms here, or declare as "no_atp" *)
blanchet@37616
   330
(* FIXME: move to "Sledgehammer_Fact_Filter" *)
paulson@25007
   331
val multi_base_blacklist =
blanchet@35963
   332
  ["defs", "select_defs", "update_defs", "induct", "inducts", "split", "splits",
blanchet@35963
   333
   "split_asm", "cases", "ext_cases"];
paulson@25007
   334
wenzelm@27184
   335
(*Skolemize a named theorem, with Skolem functions as additional premises.*)
blanchet@37617
   336
fun skolemize_theorem thy th =
blanchet@37617
   337
  if member (op =) multi_base_blacklist
blanchet@37617
   338
            (Long_Name.base_name (Thm.get_name_hint th)) orelse
blanchet@37348
   339
     is_theorem_bad_for_atps th then
blanchet@37345
   340
    []
wenzelm@27184
   341
  else
wenzelm@27184
   342
    let
wenzelm@36603
   343
      val ctxt0 = Variable.global_thm_context th
blanchet@37349
   344
      val (nnfth, ctxt) = to_nnf th ctxt0
blanchet@37617
   345
      val sko_ths = map (skolem_theorem_of_def thy) (assume_skolem_funs nnfth)
blanchet@37617
   346
      val (cnfs, ctxt) = Meson.make_cnf sko_ths nnfth ctxt
blanchet@37349
   347
    in
blanchet@37349
   348
      cnfs |> map introduce_combinators
blanchet@37349
   349
           |> Variable.export ctxt ctxt0
blanchet@37349
   350
           |> Meson.finish_cnf
blanchet@37617
   351
           |> map Thm.close_derivation
blanchet@37349
   352
    end
blanchet@37349
   353
    handle THM _ => []
wenzelm@27184
   354
paulson@24742
   355
(*The cache prevents repeated clausification of a theorem, and also repeated declaration of
paulson@24742
   356
  Skolem functions.*)
wenzelm@33522
   357
structure ThmCache = Theory_Data
wenzelm@22846
   358
(
wenzelm@28544
   359
  type T = thm list Thmtab.table * unit Symtab.table;
wenzelm@28544
   360
  val empty = (Thmtab.empty, Symtab.empty);
wenzelm@26618
   361
  val extend = I;
wenzelm@33522
   362
  fun merge ((cache1, seen1), (cache2, seen2)) : T =
wenzelm@27184
   363
    (Thmtab.merge (K true) (cache1, cache2), Symtab.merge (K true) (seen1, seen2));
wenzelm@22846
   364
);
paulson@22516
   365
blanchet@36228
   366
(* Convert Isabelle theorems into axiom clauses. *)
wenzelm@27179
   367
fun cnf_axiom thy th0 =
wenzelm@27184
   368
  let val th = Thm.transfer thy th0 in
blanchet@37617
   369
    case Thmtab.lookup (#1 (ThmCache.get thy)) th of
blanchet@37416
   370
      SOME cls => cls
blanchet@37617
   371
    | NONE => skolemize_theorem thy th
blanchet@37617
   372
  end
paulson@15347
   373
paulson@18141
   374
paulson@22471
   375
(**** Translate a set of theorems into CNF ****)
paulson@15347
   376
paulson@21290
   377
(*The combination of rev and tail recursion preserves the original order*)
blanchet@37416
   378
fun cnf_rules_pairs thy =
blanchet@37416
   379
  let
blanchet@37500
   380
    fun do_one _ [] = []
blanchet@37500
   381
      | do_one ((name, k), th) (cls :: clss) =
blanchet@37500
   382
        (cls, ((name, k), th)) :: do_one ((name, k + 1), th) clss
blanchet@37500
   383
    fun do_all pairs [] = pairs
blanchet@37500
   384
      | do_all pairs ((name, th) :: ths) =
blanchet@37416
   385
        let
blanchet@37500
   386
          val new_pairs = do_one ((name, 0), th) (cnf_axiom thy th)
blanchet@37570
   387
                          handle THM _ => []
blanchet@37500
   388
        in do_all (new_pairs @ pairs) ths end
blanchet@37500
   389
  in do_all [] o rev end
mengj@19353
   390
mengj@19196
   391
blanchet@35865
   392
(**** Convert all facts of the theory into FOL or HOL clauses ****)
paulson@15347
   393
blanchet@37584
   394
fun saturate_cache thy =
wenzelm@28544
   395
  let
blanchet@37617
   396
    val (cache, seen) = ThmCache.get thy
blanchet@37617
   397
    val facts = PureThy.facts_of thy
wenzelm@33306
   398
    val new_facts = (facts, []) |-> Facts.fold_static (fn (name, ths) =>
blanchet@37617
   399
      if Facts.is_concealed facts name orelse Symtab.defined seen name then I
blanchet@37617
   400
      else cons (name, ths))
wenzelm@28544
   401
    val new_thms = (new_facts, []) |-> fold (fn (name, ths) =>
blanchet@37399
   402
      if member (op =) multi_base_blacklist (Long_Name.base_name name) then
blanchet@37399
   403
        I
blanchet@37399
   404
      else
blanchet@37399
   405
        fold_index (fn (i, th) =>
blanchet@37617
   406
          if is_theorem_bad_for_atps th orelse Thmtab.defined cache th then
blanchet@37399
   407
            I
blanchet@37399
   408
          else
blanchet@37399
   409
            cons (name ^ "_" ^ string_of_int (i + 1), Thm.transfer thy th)) ths)
blanchet@37617
   410
    val entries =
blanchet@37617
   411
      Par_List.map (fn (_, th) => (th, skolemize_theorem thy th))
blanchet@37617
   412
                   (sort_distinct (Thm.thm_ord o pairself snd) new_thms)
wenzelm@28544
   413
  in
blanchet@37617
   414
    if null entries then
blanchet@37399
   415
      NONE
wenzelm@28544
   416
    else
blanchet@37617
   417
      thy |> ThmCache.map (fn p => p |>> fold Thmtab.update entries
blanchet@37617
   418
                                     ||> fold Symtab.update
blanchet@37617
   419
                                              (map (rpair () o #1) new_facts))
blanchet@37617
   420
          |> SOME
blanchet@37617
   421
  end
paulson@24854
   422
blanchet@37511
   423
(* For emergency use where the Skolem cache causes problems. *)
blanchet@37584
   424
val auto_saturate_cache = Unsynchronized.ref true
paulson@20457
   425
blanchet@37584
   426
fun conditionally_saturate_cache thy =
blanchet@37584
   427
  if !auto_saturate_cache then saturate_cache thy else NONE
wenzelm@27179
   428
blanchet@36398
   429
paulson@21999
   430
(*** Converting a subgoal into negated conjecture clauses. ***)
paulson@21999
   431
wenzelm@32262
   432
fun neg_skolemize_tac ctxt =
blanchet@37332
   433
  EVERY' [rtac ccontr, Object_Logic.atomize_prems_tac, Meson.skolemize_tac ctxt]
blanchet@36398
   434
blanchet@35869
   435
val neg_clausify =
blanchet@37349
   436
  single
blanchet@37349
   437
  #> Meson.make_clauses_unsorted
blanchet@37349
   438
  #> map introduce_combinators
blanchet@37349
   439
  #> Meson.finish_cnf
paulson@21999
   440
wenzelm@32257
   441
fun neg_conjecture_clauses ctxt st0 n =
wenzelm@32257
   442
  let
blanchet@37332
   443
    (* "Option" is thrown if the assumptions contain schematic variables. *)
blanchet@37332
   444
    val st = Seq.hd (neg_skolemize_tac ctxt n st0) handle Option.Option => st0
blanchet@37332
   445
    val ({params, prems, ...}, _) =
blanchet@37332
   446
      Subgoal.focus (Variable.set_body false ctxt) n st
blanchet@37332
   447
  in (map neg_clausify prems, map (dest_Free o term_of o #2) params) end
paulson@21999
   448
wenzelm@27184
   449
wenzelm@27184
   450
(** setup **)
wenzelm@27184
   451
wenzelm@27184
   452
val setup =
blanchet@37584
   453
  perhaps conditionally_saturate_cache
blanchet@37584
   454
  #> Theory.at_end conditionally_saturate_cache
paulson@18510
   455
wenzelm@20461
   456
end;