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