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