src/HOL/Tools/res_axioms.ML
author wenzelm
Thu Sep 28 23:42:50 2006 +0200 (2006-09-28)
changeset 20774 8f947ffb5eb8
parent 20710 384bfce59254
child 20783 17114542d2d4
permissions -rw-r--r--
ResAtpset.get_atpset;
paulson@15347
     1
(*  Author: Jia Meng, Cambridge University Computer Laboratory
paulson@15347
     2
    ID: $Id$
paulson@15347
     3
    Copyright 2004 University of Cambridge
paulson@15347
     4
wenzelm@20461
     5
Transformation of axiom rules (elim/intro/etc) into CNF forms.
paulson@15347
     6
*)
paulson@15347
     7
paulson@20445
     8
(*FIXME: does this signature serve any purpose?*)
paulson@15997
     9
signature RES_AXIOMS =
paulson@15997
    10
  sig
paulson@15997
    11
  val elimRule_tac : thm -> Tactical.tactic
paulson@16012
    12
  val elimR2Fol : thm -> term
paulson@15997
    13
  val transform_elim : thm -> thm
paulson@15997
    14
  val cnf_axiom : (string * thm) -> thm list
paulson@15997
    15
  val meta_cnf_axiom : thm -> thm list
paulson@15997
    16
  val claset_rules_of_thy : theory -> (string * thm) list
paulson@15997
    17
  val simpset_rules_of_thy : theory -> (string * thm) list
paulson@17484
    18
  val claset_rules_of_ctxt: Proof.context -> (string * thm) list
paulson@17484
    19
  val simpset_rules_of_ctxt : Proof.context -> (string * thm) list
mengj@17905
    20
  val pairname : thm -> (string * thm)
paulson@18510
    21
  val skolem_thm : thm -> thm list
paulson@20419
    22
  val to_nnf : thm -> thm
mengj@19353
    23
  val cnf_rules_pairs : (string * Thm.thm) list -> (Thm.thm * (string * int)) list list;
wenzelm@18708
    24
  val meson_method_setup : theory -> theory
wenzelm@18708
    25
  val setup : theory -> theory
mengj@19196
    26
mengj@19196
    27
  val atpset_rules_of_thy : theory -> (string * thm) list
mengj@19196
    28
  val atpset_rules_of_ctxt : Proof.context -> (string * thm) list
paulson@15997
    29
  end;
wenzelm@20461
    30
paulson@20419
    31
structure ResAxioms =
wenzelm@20461
    32
paulson@15997
    33
struct
paulson@15347
    34
paulson@20419
    35
(*FIXME DELETE: For running the comparison between combinators and abstractions.
paulson@20419
    36
  CANNOT be a ref, as the setting is used while Isabelle is built.*)
paulson@20419
    37
val abstract_lambdas = true;
paulson@20419
    38
paulson@20419
    39
val trace_abs = ref false;
mengj@18000
    40
paulson@20445
    41
(*Store definitions of abstraction functions, ensuring that identical right-hand
paulson@20445
    42
  sides are denoted by the same functions and thereby reducing the need for
paulson@20445
    43
  extensionality in proofs.
paulson@20445
    44
  FIXME!  Store in theory data!!*)
paulson@20445
    45
val abstraction_cache = ref Net.empty : thm Net.net ref;
paulson@20445
    46
paulson@15997
    47
(**** Transformation of Elimination Rules into First-Order Formulas****)
paulson@15347
    48
paulson@15390
    49
(* a tactic used to prove an elim-rule. *)
paulson@16009
    50
fun elimRule_tac th =
paulson@20419
    51
    (resolve_tac [impI,notI] 1) THEN (etac th 1) THEN REPEAT(fast_tac HOL_cs 1);
paulson@15347
    52
paulson@15956
    53
fun add_EX tm [] = tm
paulson@15956
    54
  | add_EX tm ((x,xtp)::xs) = add_EX (HOLogic.exists_const xtp $ Abs(x,xtp,tm)) xs;
paulson@15347
    55
paulson@19894
    56
(*Checks for the premise ~P when the conclusion is P.*)
wenzelm@20461
    57
fun is_neg (Const("Trueprop",_) $ (Const("Not",_) $ Free(p,_)))
paulson@19894
    58
           (Const("Trueprop",_) $ Free(q,_)) = (p = q)
paulson@15371
    59
  | is_neg _ _ = false;
paulson@15371
    60
paulson@20017
    61
exception ELIMR2FOL;
paulson@20017
    62
paulson@20017
    63
(*Handles the case where the dummy "conclusion" variable appears negated in the
paulson@20017
    64
  premises, so the final consequent must be kept.*)
paulson@15371
    65
fun strip_concl' prems bvs (Const ("==>",_) $ P $ Q) =
paulson@19894
    66
      strip_concl' (HOLogic.dest_Trueprop P :: prems) bvs  Q
wenzelm@20461
    67
  | strip_concl' prems bvs P =
paulson@15956
    68
      let val P' = HOLogic.Not $ (HOLogic.dest_Trueprop P)
paulson@19894
    69
      in add_EX (foldr1 HOLogic.mk_conj (P'::prems)) bvs end;
paulson@15371
    70
paulson@20017
    71
(*Recurrsion over the minor premise of an elimination rule. Final consequent
paulson@20017
    72
  is ignored, as it is the dummy "conclusion" variable.*)
wenzelm@20461
    73
fun strip_concl prems bvs concl (Const ("all", _) $ Abs (x,xtp,body)) =
paulson@18141
    74
      strip_concl prems ((x,xtp)::bvs) concl body
paulson@15371
    75
  | strip_concl prems bvs concl (Const ("==>",_) $ P $ Q) =
paulson@18141
    76
      if (is_neg P concl) then (strip_concl' prems bvs Q)
paulson@18141
    77
      else strip_concl (HOLogic.dest_Trueprop P::prems) bvs  concl Q
wenzelm@20461
    78
  | strip_concl prems bvs concl Q =
paulson@20017
    79
      if concl aconv Q then add_EX (foldr1 HOLogic.mk_conj prems) bvs
paulson@20017
    80
      else raise ELIMR2FOL (*expected conclusion not found!*)
wenzelm@20461
    81
paulson@20017
    82
fun trans_elim (major,[],_) = HOLogic.Not $ major
paulson@20017
    83
  | trans_elim (major,minors,concl) =
paulson@20017
    84
      let val disjs = foldr1 HOLogic.mk_disj (map (strip_concl [] [] concl) minors)
paulson@20017
    85
      in  HOLogic.mk_imp (major, disjs)  end;
paulson@15347
    86
paulson@16012
    87
(* convert an elim rule into an equivalent formula, of type term. *)
wenzelm@20461
    88
fun elimR2Fol elimR =
wenzelm@20292
    89
  let val elimR' = #1 (Drule.freeze_thaw elimR)
paulson@19894
    90
      val (prems,concl) = (prems_of elimR', concl_of elimR')
paulson@20017
    91
      val cv = case concl of    (*conclusion variable*)
wenzelm@20461
    92
                  Const("Trueprop",_) $ (v as Free(_,Type("bool",[]))) => v
wenzelm@20461
    93
                | v as Free(_, Type("prop",[])) => v
wenzelm@20461
    94
                | _ => raise ELIMR2FOL
paulson@20017
    95
  in case prems of
paulson@20017
    96
      [] => raise ELIMR2FOL
wenzelm@20461
    97
    | (Const("Trueprop",_) $ major) :: minors =>
paulson@20017
    98
        if member (op aconv) (term_frees major) cv then raise ELIMR2FOL
paulson@20017
    99
        else (trans_elim (major, minors, concl) handle TERM _ => raise ELIMR2FOL)
paulson@20017
   100
    | _ => raise ELIMR2FOL
paulson@20017
   101
  end;
paulson@15347
   102
wenzelm@20461
   103
(* convert an elim-rule into an equivalent theorem that does not have the
wenzelm@20461
   104
   predicate variable.  Leave other theorems unchanged.*)
paulson@16009
   105
fun transform_elim th =
paulson@20017
   106
    let val ctm = cterm_of (sign_of_thm th) (HOLogic.mk_Trueprop (elimR2Fol th))
paulson@18009
   107
    in Goal.prove_raw [] ctm (fn _ => elimRule_tac th) end
paulson@20017
   108
    handle ELIMR2FOL => th (*not an elimination rule*)
wenzelm@20461
   109
         | exn => (warning ("transform_elim failed: " ^ Toplevel.exn_message exn ^
wenzelm@20461
   110
                            " for theorem " ^ string_of_thm th); th)
paulson@20017
   111
paulson@15997
   112
paulson@15997
   113
(**** Transformation of Clasets and Simpsets into First-Order Axioms ****)
paulson@15997
   114
paulson@16563
   115
(*Transfer a theorem into theory Reconstruction.thy if it is not already
paulson@15359
   116
  inside that theory -- because it's needed for Skolemization *)
paulson@15359
   117
paulson@16563
   118
(*This will refer to the final version of theory Reconstruction.*)
wenzelm@20461
   119
val recon_thy_ref = Theory.self_ref (the_context ());
paulson@15359
   120
paulson@16563
   121
(*If called while Reconstruction is being created, it will transfer to the
paulson@16563
   122
  current version. If called afterward, it will transfer to the final version.*)
paulson@16009
   123
fun transfer_to_Reconstruction th =
paulson@16563
   124
    transfer (Theory.deref recon_thy_ref) th handle THM _ => th;
paulson@15347
   125
paulson@15955
   126
fun is_taut th =
paulson@15955
   127
      case (prop_of th) of
paulson@15955
   128
           (Const ("Trueprop", _) $ Const ("True", _)) => true
paulson@15955
   129
         | _ => false;
paulson@15955
   130
paulson@15955
   131
(* remove tautologous clauses *)
paulson@15955
   132
val rm_redundant_cls = List.filter (not o is_taut);
wenzelm@20461
   133
wenzelm@20461
   134
paulson@16009
   135
(**** SKOLEMIZATION BY INFERENCE (lcp) ****)
paulson@16009
   136
paulson@18141
   137
(*Traverse a theorem, declaring Skolem function definitions. String s is the suggested
paulson@18141
   138
  prefix for the Skolem constant. Result is a new theory*)
paulson@18141
   139
fun declare_skofuns s th thy =
paulson@20419
   140
  let fun dec_sko (Const ("Ex",_) $ (xtp as Abs(_,T,p))) (thy, axs) =
wenzelm@20461
   141
            (*Existential: declare a Skolem function, then insert into body and continue*)
wenzelm@20624
   142
            let val cname = Name.internal (gensym ("sko_" ^ s ^ "_"))
wenzelm@20461
   143
                val args = term_frees xtp  (*get the formal parameter list*)
wenzelm@20461
   144
                val Ts = map type_of args
wenzelm@20461
   145
                val cT = Ts ---> T
wenzelm@20461
   146
                val c = Const (Sign.full_name thy cname, cT)
wenzelm@20461
   147
                val rhs = list_abs_free (map dest_Free args, HOLogic.choice_const T $ xtp)
wenzelm@20461
   148
                        (*Forms a lambda-abstraction over the formal parameters*)
wenzelm@20461
   149
                val thy' = Theory.add_consts_i [(cname, cT, NoSyn)] thy
wenzelm@20461
   150
                           (*Theory is augmented with the constant, then its def*)
wenzelm@20461
   151
                val cdef = cname ^ "_def"
wenzelm@20461
   152
                val thy'' = Theory.add_defs_i false false [(cdef, equals cT $ c $ rhs)] thy'
wenzelm@20461
   153
            in dec_sko (subst_bound (list_comb(c,args), p))
wenzelm@20461
   154
                       (thy'', get_axiom thy'' cdef :: axs)
wenzelm@20461
   155
            end
wenzelm@20461
   156
        | dec_sko (Const ("All",_) $ (xtp as Abs(a,T,p))) thx =
wenzelm@20461
   157
            (*Universal quant: insert a free variable into body and continue*)
wenzelm@20461
   158
            let val fname = Name.variant (add_term_names (p,[])) a
wenzelm@20461
   159
            in dec_sko (subst_bound (Free(fname,T), p)) thx end
wenzelm@20461
   160
        | dec_sko (Const ("op &", _) $ p $ q) thx = dec_sko q (dec_sko p thx)
wenzelm@20461
   161
        | dec_sko (Const ("op |", _) $ p $ q) thx = dec_sko q (dec_sko p thx)
wenzelm@20461
   162
        | dec_sko (Const ("Trueprop", _) $ p) thx = dec_sko p thx
wenzelm@20461
   163
        | dec_sko t thx = thx (*Do nothing otherwise*)
paulson@20419
   164
  in  dec_sko (prop_of th) (thy,[])  end;
paulson@18141
   165
paulson@18141
   166
(*Traverse a theorem, accumulating Skolem function definitions.*)
paulson@18141
   167
fun assume_skofuns th =
paulson@18141
   168
  let fun dec_sko (Const ("Ex",_) $ (xtp as Abs(_,T,p))) defs =
wenzelm@20461
   169
            (*Existential: declare a Skolem function, then insert into body and continue*)
wenzelm@20461
   170
            let val skos = map (#1 o Logic.dest_equals) defs  (*existing sko fns*)
wenzelm@20461
   171
                val args = term_frees xtp \\ skos  (*the formal parameters*)
wenzelm@20461
   172
                val Ts = map type_of args
wenzelm@20461
   173
                val cT = Ts ---> T
wenzelm@20461
   174
                val c = Free (gensym "sko_", cT)
wenzelm@20461
   175
                val rhs = list_abs_free (map dest_Free args,
wenzelm@20461
   176
                                         HOLogic.choice_const T $ xtp)
wenzelm@20461
   177
                      (*Forms a lambda-abstraction over the formal parameters*)
wenzelm@20461
   178
                val def = equals cT $ c $ rhs
wenzelm@20461
   179
            in dec_sko (subst_bound (list_comb(c,args), p))
wenzelm@20461
   180
                       (def :: defs)
wenzelm@20461
   181
            end
wenzelm@20461
   182
        | dec_sko (Const ("All",_) $ (xtp as Abs(a,T,p))) defs =
wenzelm@20461
   183
            (*Universal quant: insert a free variable into body and continue*)
wenzelm@20461
   184
            let val fname = Name.variant (add_term_names (p,[])) a
wenzelm@20461
   185
            in dec_sko (subst_bound (Free(fname,T), p)) defs end
wenzelm@20461
   186
        | dec_sko (Const ("op &", _) $ p $ q) defs = dec_sko q (dec_sko p defs)
wenzelm@20461
   187
        | dec_sko (Const ("op |", _) $ p $ q) defs = dec_sko q (dec_sko p defs)
wenzelm@20461
   188
        | dec_sko (Const ("Trueprop", _) $ p) defs = dec_sko p defs
wenzelm@20461
   189
        | dec_sko t defs = defs (*Do nothing otherwise*)
paulson@20419
   190
  in  dec_sko (prop_of th) []  end;
paulson@20419
   191
paulson@20419
   192
paulson@20419
   193
(**** REPLACING ABSTRACTIONS BY FUNCTION DEFINITIONS ****)
paulson@20419
   194
paulson@20419
   195
(*Returns the vars of a theorem*)
paulson@20419
   196
fun vars_of_thm th =
paulson@20445
   197
  map (Thm.cterm_of (theory_of_thm th) o Var) (Drule.fold_terms Term.add_vars th []);
paulson@20419
   198
paulson@20419
   199
(*Make a version of fun_cong with a given variable name*)
paulson@20419
   200
local
paulson@20419
   201
    val fun_cong' = fun_cong RS asm_rl; (*renumber f, g to prevent clashes with (a,0)*)
paulson@20419
   202
    val cx = hd (vars_of_thm fun_cong');
paulson@20419
   203
    val ty = typ_of (ctyp_of_term cx);
paulson@20445
   204
    val thy = theory_of_thm fun_cong;
paulson@20419
   205
    fun mkvar a = cterm_of thy (Var((a,0),ty));
paulson@20419
   206
in
paulson@20419
   207
fun xfun_cong x = Thm.instantiate ([], [(cx, mkvar x)]) fun_cong'
paulson@20419
   208
end;
paulson@20419
   209
paulson@20419
   210
(*Removes the lambdas from an equation of the form t = (%x. u)*)
wenzelm@20461
   211
fun strip_lambdas th =
paulson@20419
   212
  case prop_of th of
wenzelm@20461
   213
      _ $ (Const ("op =", _) $ _ $ Abs (x,_,_)) =>
paulson@20419
   214
          strip_lambdas (#1 (Drule.freeze_thaw (th RS xfun_cong x)))
paulson@20419
   215
    | _ => th;
paulson@20419
   216
wenzelm@20461
   217
(*Convert meta- to object-equality. Fails for theorems like split_comp_eq,
paulson@20419
   218
  where some types have the empty sort.*)
wenzelm@20461
   219
fun object_eq th = th RS def_imp_eq
paulson@20419
   220
    handle THM _ => error ("Theorem contains empty sort: " ^ string_of_thm th);
wenzelm@20461
   221
paulson@20419
   222
(*Contract all eta-redexes in the theorem, lest they give rise to needless abstractions*)
paulson@20419
   223
fun eta_conversion_rule th =
paulson@20419
   224
  equal_elim (eta_conversion (cprop_of th)) th;
wenzelm@20461
   225
paulson@20445
   226
fun crhs_of th =
paulson@20419
   227
  case Drule.strip_comb (cprop_of th) of
wenzelm@20461
   228
      (f, [_, rhs]) =>
paulson@20457
   229
          (case term_of f of Const ("==", _) => rhs
paulson@20445
   230
             | _ => raise THM ("crhs_of", 0, [th]))
paulson@20445
   231
    | _ => raise THM ("crhs_of", 1, [th]);
paulson@20445
   232
paulson@20525
   233
fun lhs_of th =
paulson@20525
   234
  case prop_of th of (Const("==",_) $ lhs $ _) => lhs
paulson@20525
   235
    | _ => raise THM ("lhs_of", 1, [th]);
paulson@20525
   236
paulson@20445
   237
fun rhs_of th =
paulson@20457
   238
  case prop_of th of (Const("==",_) $ _ $ rhs) => rhs
paulson@20457
   239
    | _ => raise THM ("rhs_of", 1, [th]);
paulson@20419
   240
paulson@20419
   241
(*Apply a function definition to an argument, beta-reducing the result.*)
paulson@20419
   242
fun beta_comb cf x =
paulson@20419
   243
  let val th1 = combination cf (reflexive x)
paulson@20445
   244
      val th2 = beta_conversion false (crhs_of th1)
paulson@20419
   245
  in  transitive th1 th2  end;
paulson@20419
   246
paulson@20419
   247
(*Apply a function definition to arguments, beta-reducing along the way.*)
paulson@20419
   248
fun list_combination cf [] = cf
paulson@20419
   249
  | list_combination cf (x::xs) = list_combination (beta_comb cf x) xs;
paulson@20419
   250
paulson@20419
   251
fun list_cabs ([] ,     t) = t
paulson@20419
   252
  | list_cabs (v::vars, t) = Thm.cabs v (list_cabs(vars,t));
paulson@20419
   253
wenzelm@20461
   254
fun assert_eta_free ct =
wenzelm@20461
   255
  let val t = term_of ct
wenzelm@20461
   256
  in if (t aconv Envir.eta_contract t) then ()
paulson@20419
   257
     else error ("Eta redex in term: " ^ string_of_cterm ct)
paulson@20419
   258
  end;
paulson@20419
   259
wenzelm@20461
   260
fun eq_absdef (th1, th2) =
paulson@20445
   261
    Context.joinable (theory_of_thm th1, theory_of_thm th2)  andalso
paulson@20445
   262
    rhs_of th1 aconv rhs_of th2;
paulson@20445
   263
paulson@20445
   264
fun lambda_free (Abs _) = false
paulson@20445
   265
  | lambda_free (t $ u) = lambda_free t andalso lambda_free u
paulson@20445
   266
  | lambda_free _ = true;
wenzelm@20461
   267
wenzelm@20461
   268
fun monomorphic t =
wenzelm@20461
   269
  Term.fold_types (Term.fold_atyps (fn TVar _ => K false | _ => I)) t true;
wenzelm@20461
   270
paulson@20710
   271
fun dest_abs_list ct =
paulson@20710
   272
  let val (cv,ct') = Thm.dest_abs NONE ct
paulson@20710
   273
      val (cvs,cu) = dest_abs_list ct'
paulson@20710
   274
  in (cv::cvs, cu) end
paulson@20710
   275
  handle CTERM _ => ([],ct);
paulson@20710
   276
paulson@20710
   277
fun lambda_list [] u = u
paulson@20710
   278
  | lambda_list (v::vs) u = lambda v (lambda_list vs u);
paulson@20710
   279
paulson@20710
   280
fun abstract_rule_list [] [] th = th
paulson@20710
   281
  | abstract_rule_list (v::vs) (ct::cts) th = abstract_rule v ct (abstract_rule_list vs cts th)
paulson@20710
   282
  | abstract_rule_list _ _ th = raise THM ("abstract_rule_list", 0, [th]);
paulson@20710
   283
paulson@20419
   284
(*Traverse a theorem, declaring abstraction function definitions. String s is the suggested
paulson@20419
   285
  prefix for the constants. Resulting theory is returned in the first theorem. *)
paulson@20419
   286
fun declare_absfuns th =
wenzelm@20461
   287
  let fun abstract thy ct =
paulson@20445
   288
        if lambda_free (term_of ct) then (transfer thy (reflexive ct), [])
paulson@20445
   289
        else
paulson@20445
   290
        case term_of ct of
paulson@20710
   291
          Abs _ =>
wenzelm@20624
   292
            let val cname = Name.internal (gensym "abs_");
wenzelm@20461
   293
                val _ = assert_eta_free ct;
paulson@20710
   294
                val (cvs,cta) = dest_abs_list ct
paulson@20710
   295
                val (vs,Tvs) = ListPair.unzip (map (dest_Free o term_of) cvs)
wenzelm@20461
   296
                val (u'_th,defs) = abstract thy cta
paulson@20445
   297
                val cu' = crhs_of u'_th
paulson@20710
   298
                val abs_v_u = lambda_list (map term_of cvs) (term_of cu')
wenzelm@20461
   299
                (*get the formal parameters: ALL variables free in the term*)
wenzelm@20461
   300
                val args = term_frees abs_v_u
wenzelm@20461
   301
                val rhs = list_abs_free (map dest_Free args, abs_v_u)
wenzelm@20461
   302
                      (*Forms a lambda-abstraction over the formal parameters*)
wenzelm@20461
   303
                val v_rhs = Logic.varify rhs
wenzelm@20461
   304
                val (ax,thy) =
wenzelm@20461
   305
                 case List.find (fn ax => v_rhs aconv rhs_of ax)
wenzelm@20461
   306
                        (Net.match_term (!abstraction_cache) v_rhs) of
wenzelm@20461
   307
                     SOME ax => (ax,thy)   (*cached axiom, current theory*)
wenzelm@20461
   308
                   | NONE =>
wenzelm@20461
   309
                      let val Ts = map type_of args
paulson@20710
   310
                          val cT = Ts ---> (Tvs ---> typ_of (ctyp_of_term cu'))
wenzelm@20461
   311
                          val thy = theory_of_thm u'_th
wenzelm@20461
   312
                          val c = Const (Sign.full_name thy cname, cT)
wenzelm@20461
   313
                          val thy = Theory.add_consts_i [(cname, cT, NoSyn)] thy
wenzelm@20461
   314
                                     (*Theory is augmented with the constant,
wenzelm@20461
   315
                                       then its definition*)
wenzelm@20461
   316
                          val cdef = cname ^ "_def"
wenzelm@20461
   317
                          val thy = Theory.add_defs_i false false
wenzelm@20461
   318
                                       [(cdef, equals cT $ c $ rhs)] thy
wenzelm@20461
   319
                          val ax = get_axiom thy cdef
wenzelm@20461
   320
                          val _ = abstraction_cache := Net.insert_term eq_absdef (v_rhs,ax)
wenzelm@20461
   321
                                    (!abstraction_cache)
wenzelm@20461
   322
                            handle Net.INSERT =>
wenzelm@20461
   323
                              raise THM ("declare_absfuns: INSERT", 0, [th,u'_th,ax])
wenzelm@20461
   324
                       in  (ax,thy)  end
wenzelm@20461
   325
                val _ = assert (v_rhs aconv rhs_of ax) "declare_absfuns: rhs mismatch"
wenzelm@20461
   326
                val def = #1 (Drule.freeze_thaw ax)
wenzelm@20461
   327
                val def_args = list_combination def (map (cterm_of thy) args)
paulson@20710
   328
            in (transitive (abstract_rule_list vs cvs u'_th) (symmetric def_args),
wenzelm@20461
   329
                def :: defs) end
wenzelm@20461
   330
        | (t1$t2) =>
wenzelm@20461
   331
            let val (ct1,ct2) = Thm.dest_comb ct
wenzelm@20461
   332
                val (th1,defs1) = abstract thy ct1
wenzelm@20461
   333
                val (th2,defs2) = abstract (theory_of_thm th1) ct2
wenzelm@20461
   334
            in  (combination th1 th2, defs1@defs2)  end
paulson@20419
   335
      val _ = if !trace_abs then warning (string_of_thm th) else ();
paulson@20419
   336
      val (eqth,defs) = abstract (theory_of_thm th) (cprop_of th)
paulson@20419
   337
      val ths = equal_elim eqth th ::
paulson@20419
   338
                map (forall_intr_vars o strip_lambdas o object_eq) defs
paulson@20419
   339
  in  (theory_of_thm eqth, ths)  end;
paulson@20419
   340
paulson@20567
   341
fun name_of def = SOME (#1 (dest_Free (lhs_of def))) handle _ => NONE;
paulson@20567
   342
paulson@20525
   343
(*A name is valid provided it isn't the name of a defined abstraction.*)
paulson@20567
   344
fun valid_name defs (Free(x,T)) = not (x mem_string (List.mapPartial name_of defs))
paulson@20525
   345
  | valid_name defs _ = false;
paulson@20525
   346
paulson@20419
   347
fun assume_absfuns th =
paulson@20445
   348
  let val thy = theory_of_thm th
paulson@20445
   349
      val cterm = cterm_of thy
paulson@20525
   350
      fun abstract ct =
paulson@20445
   351
        if lambda_free (term_of ct) then (reflexive ct, [])
paulson@20445
   352
        else
paulson@20445
   353
        case term_of ct of
paulson@20419
   354
          Abs (_,T,u) =>
paulson@20710
   355
            let val _ = assert_eta_free ct;
paulson@20710
   356
                val (cvs,cta) = dest_abs_list ct
paulson@20710
   357
                val (vs,Tvs) = ListPair.unzip (map (dest_Free o term_of) cvs)
paulson@20525
   358
                val (u'_th,defs) = abstract cta
paulson@20445
   359
                val cu' = crhs_of u'_th
paulson@20710
   360
                (*Could use Thm.cabs instead of lambda to work at level of cterms*)
paulson@20710
   361
                val abs_v_u = lambda_list (map term_of cvs) (term_of cu')
paulson@20525
   362
                (*get the formal parameters: free variables not present in the defs
paulson@20525
   363
                  (to avoid taking abstraction function names as parameters) *)
paulson@20710
   364
                val args = filter (valid_name defs) (term_frees abs_v_u)
paulson@20710
   365
                val crhs = list_cabs (map cterm args, cterm abs_v_u)
wenzelm@20461
   366
                      (*Forms a lambda-abstraction over the formal parameters*)
wenzelm@20461
   367
                val rhs = term_of crhs
paulson@20525
   368
                val def =  (*FIXME: can we also reuse the const-abstractions?*)
wenzelm@20461
   369
                 case List.find (fn ax => rhs aconv rhs_of ax andalso
wenzelm@20461
   370
                                          Context.joinable (thy, theory_of_thm ax))
wenzelm@20461
   371
                        (Net.match_term (!abstraction_cache) rhs) of
wenzelm@20461
   372
                     SOME ax => ax
wenzelm@20461
   373
                   | NONE =>
wenzelm@20461
   374
                      let val Ts = map type_of args
paulson@20710
   375
                          val const_ty = Ts ---> (Tvs ---> typ_of (ctyp_of_term cu'))
wenzelm@20461
   376
                          val c = Free (gensym "abs_", const_ty)
wenzelm@20461
   377
                          val ax = assume (Thm.capply (cterm (equals const_ty $ c)) crhs)
wenzelm@20461
   378
                          val _ = abstraction_cache := Net.insert_term eq_absdef (rhs,ax)
wenzelm@20461
   379
                                    (!abstraction_cache)
wenzelm@20461
   380
                            handle Net.INSERT =>
wenzelm@20461
   381
                              raise THM ("assume_absfuns: INSERT", 0, [th,u'_th,ax])
wenzelm@20461
   382
                      in ax end
wenzelm@20461
   383
                val _ = assert (rhs aconv rhs_of def) "assume_absfuns: rhs mismatch"
wenzelm@20461
   384
                val def_args = list_combination def (map cterm args)
paulson@20710
   385
            in (transitive (abstract_rule_list vs cvs u'_th) (symmetric def_args),
wenzelm@20461
   386
                def :: defs) end
wenzelm@20461
   387
        | (t1$t2) =>
wenzelm@20461
   388
            let val (ct1,ct2) = Thm.dest_comb ct
paulson@20525
   389
                val (t1',defs1) = abstract ct1
paulson@20525
   390
                val (t2',defs2) = abstract ct2
wenzelm@20461
   391
            in  (combination t1' t2', defs1@defs2)  end
paulson@20525
   392
      val (eqth,defs) = abstract (cprop_of th)
paulson@20419
   393
  in  equal_elim eqth th ::
paulson@20419
   394
      map (forall_intr_vars o strip_lambdas o object_eq) defs
paulson@20419
   395
  end;
paulson@20419
   396
paulson@16009
   397
paulson@16009
   398
(*cterms are used throughout for efficiency*)
paulson@18141
   399
val cTrueprop = Thm.cterm_of HOL.thy HOLogic.Trueprop;
paulson@16009
   400
paulson@16009
   401
(*cterm version of mk_cTrueprop*)
paulson@16009
   402
fun c_mkTrueprop A = Thm.capply cTrueprop A;
paulson@16009
   403
paulson@16009
   404
(*Given an abstraction over n variables, replace the bound variables by free
paulson@16009
   405
  ones. Return the body, along with the list of free variables.*)
wenzelm@20461
   406
fun c_variant_abs_multi (ct0, vars) =
paulson@16009
   407
      let val (cv,ct) = Thm.dest_abs NONE ct0
paulson@16009
   408
      in  c_variant_abs_multi (ct, cv::vars)  end
paulson@16009
   409
      handle CTERM _ => (ct0, rev vars);
paulson@16009
   410
wenzelm@20461
   411
(*Given the definition of a Skolem function, return a theorem to replace
wenzelm@20461
   412
  an existential formula by a use of that function.
paulson@18141
   413
   Example: "EX x. x : A & x ~: B ==> sko A B : A & sko A B ~: B"  [.] *)
wenzelm@20461
   414
fun skolem_of_def def =
wenzelm@20292
   415
  let val (c,rhs) = Drule.dest_equals (cprop_of (#1 (Drule.freeze_thaw def)))
paulson@16009
   416
      val (ch, frees) = c_variant_abs_multi (rhs, [])
paulson@18141
   417
      val (chilbert,cabs) = Thm.dest_comb ch
paulson@18141
   418
      val {sign,t, ...} = rep_cterm chilbert
paulson@18141
   419
      val T = case t of Const ("Hilbert_Choice.Eps", Type("fun",[_,T])) => T
paulson@18141
   420
                      | _ => raise THM ("skolem_of_def: expected Eps", 0, [def])
paulson@16009
   421
      val cex = Thm.cterm_of sign (HOLogic.exists_const T)
paulson@16009
   422
      val ex_tm = c_mkTrueprop (Thm.capply cex cabs)
paulson@16009
   423
      and conc =  c_mkTrueprop (Drule.beta_conv cabs (Drule.list_comb(c,frees)));
paulson@18141
   424
      fun tacf [prem] = rewrite_goals_tac [def] THEN rtac (prem RS someI_ex) 1
wenzelm@20461
   425
  in  Goal.prove_raw [ex_tm] conc tacf
paulson@18141
   426
       |> forall_intr_list frees
paulson@18141
   427
       |> forall_elim_vars 0  (*Introduce Vars, but don't discharge defs.*)
paulson@18141
   428
       |> Thm.varifyT
paulson@18141
   429
  end;
paulson@16009
   430
mengj@18198
   431
(*Converts an Isabelle theorem (intro, elim or simp format) into nnf.*)
mengj@18198
   432
(*It now works for HOL too. *)
wenzelm@20461
   433
fun to_nnf th =
paulson@18141
   434
    th |> transfer_to_Reconstruction
paulson@20419
   435
       |> transform_elim |> zero_var_indexes |> Drule.freeze_thaw |> #1
paulson@20710
   436
       |> ObjectLogic.atomize_thm |> make_nnf |> strip_lambdas;
paulson@16009
   437
wenzelm@20461
   438
(*The cache prevents repeated clausification of a theorem,
wenzelm@20461
   439
  and also repeated declaration of Skolem functions*)
paulson@18510
   440
  (* FIXME better use Termtab!? No, we MUST use theory data!!*)
paulson@15955
   441
val clause_cache = ref (Symtab.empty : (thm * thm list) Symtab.table)
paulson@15955
   442
paulson@18141
   443
paulson@18141
   444
(*Generate Skolem functions for a theorem supplied in nnf*)
paulson@18141
   445
fun skolem_of_nnf th =
paulson@18141
   446
  map (skolem_of_def o assume o (cterm_of (theory_of_thm th))) (assume_skofuns th);
paulson@18141
   447
paulson@20457
   448
fun assert_lambda_free ths = assert (forall (lambda_free o prop_of) ths);
paulson@20457
   449
paulson@20445
   450
fun assume_abstract th =
paulson@20457
   451
  if lambda_free (prop_of th) then [th]
wenzelm@20461
   452
  else th |> eta_conversion_rule |> assume_absfuns
paulson@20457
   453
          |> tap (fn ths => assert_lambda_free ths "assume_abstract: lambdas")
paulson@20445
   454
paulson@20419
   455
(*Replace lambdas by assumed function definitions in the theorems*)
paulson@20445
   456
fun assume_abstract_list ths =
paulson@20445
   457
  if abstract_lambdas then List.concat (map assume_abstract ths)
paulson@20419
   458
  else map eta_conversion_rule ths;
paulson@20419
   459
paulson@20419
   460
(*Replace lambdas by declared function definitions in the theorems*)
paulson@20419
   461
fun declare_abstract' (thy, []) = (thy, [])
paulson@20419
   462
  | declare_abstract' (thy, th::ths) =
wenzelm@20461
   463
      let val (thy', th_defs) =
paulson@20457
   464
            if lambda_free (prop_of th) then (thy, [th])
paulson@20445
   465
            else
wenzelm@20461
   466
                th |> zero_var_indexes |> Drule.freeze_thaw |> #1
wenzelm@20461
   467
                   |> eta_conversion_rule |> transfer thy |> declare_absfuns
wenzelm@20461
   468
          val _ = assert_lambda_free th_defs "declare_abstract: lambdas"
wenzelm@20461
   469
          val (thy'', ths') = declare_abstract' (thy', ths)
paulson@20419
   470
      in  (thy'', th_defs @ ths')  end;
paulson@20419
   471
paulson@20421
   472
(*FIXME DELETE if we decide to switch to abstractions*)
paulson@20419
   473
fun declare_abstract (thy, ths) =
paulson@20419
   474
  if abstract_lambdas then declare_abstract' (thy, ths)
paulson@20419
   475
  else (thy, map eta_conversion_rule ths);
paulson@20419
   476
paulson@18510
   477
(*Skolemize a named theorem, with Skolem functions as additional premises.*)
wenzelm@20461
   478
(*also works for HOL*)
wenzelm@20461
   479
fun skolem_thm th =
paulson@18510
   480
  let val nnfth = to_nnf th
paulson@20419
   481
  in  Meson.make_cnf (skolem_of_nnf nnfth) nnfth
paulson@20445
   482
      |> assume_abstract_list |> Meson.finish_cnf |> rm_redundant_cls
paulson@18510
   483
  end
paulson@18510
   484
  handle THM _ => [];
paulson@18141
   485
paulson@18510
   486
(*Declare Skolem functions for a theorem, supplied in nnf and with its name.
paulson@18510
   487
  It returns a modified theory, unless skolemization fails.*)
paulson@16009
   488
fun skolem thy (name,th) =
paulson@20419
   489
  let val cname = (case name of "" => gensym "" | s => Sign.base_name s)
paulson@20419
   490
      val _ = Output.debug ("skolemizing " ^ name ^ ": ")
wenzelm@20461
   491
  in Option.map
wenzelm@20461
   492
        (fn nnfth =>
paulson@18141
   493
          let val (thy',defs) = declare_skofuns cname nnfth thy
paulson@20419
   494
              val cnfs = Meson.make_cnf (map skolem_of_def defs) nnfth
paulson@20419
   495
              val (thy'',cnfs') = declare_abstract (thy',cnfs)
paulson@20419
   496
          in (thy'', rm_redundant_cls (Meson.finish_cnf cnfs'))
paulson@20419
   497
          end)
wenzelm@20461
   498
      (SOME (to_nnf th)  handle THM _ => NONE)
paulson@18141
   499
  end;
paulson@16009
   500
paulson@18510
   501
(*Populate the clause cache using the supplied theorem. Return the clausal form
paulson@18510
   502
  and modified theory.*)
wenzelm@20461
   503
fun skolem_cache_thm (name,th) thy =
paulson@18144
   504
  case Symtab.lookup (!clause_cache) name of
wenzelm@20461
   505
      NONE =>
wenzelm@20461
   506
        (case skolem thy (name, Thm.transfer thy th) of
wenzelm@20461
   507
             NONE => ([th],thy)
paulson@20473
   508
           | SOME (thy',cls) => 
paulson@20473
   509
               let val cls = map Drule.local_standard cls
paulson@20473
   510
               in
paulson@20473
   511
                  if null cls then warning ("skolem_cache: empty clause set for " ^ name)
paulson@20473
   512
                  else ();
paulson@20473
   513
                  change clause_cache (Symtab.update (name, (th, cls))); 
paulson@20473
   514
                  (cls,thy')
paulson@20473
   515
               end)
paulson@18144
   516
    | SOME (th',cls) =>
paulson@18510
   517
        if eq_thm(th,th') then (cls,thy)
wenzelm@20461
   518
        else (Output.debug ("skolem_cache: Ignoring variant of theorem " ^ name);
wenzelm@20461
   519
              Output.debug (string_of_thm th);
wenzelm@20461
   520
              Output.debug (string_of_thm th');
wenzelm@20461
   521
              ([th],thy));
wenzelm@20461
   522
wenzelm@20461
   523
(*Exported function to convert Isabelle theorems into axiom clauses*)
paulson@19894
   524
fun cnf_axiom (name,th) =
paulson@18144
   525
  case name of
wenzelm@20461
   526
        "" => skolem_thm th (*no name, so can't cache*)
paulson@18144
   527
      | s  => case Symtab.lookup (!clause_cache) s of
paulson@20473
   528
                NONE => 
paulson@20473
   529
                  let val cls = map Drule.local_standard (skolem_thm th)
wenzelm@20461
   530
                  in change clause_cache (Symtab.update (s, (th, cls))); cls end
wenzelm@20461
   531
              | SOME(th',cls) =>
wenzelm@20461
   532
                  if eq_thm(th,th') then cls
wenzelm@20461
   533
                  else (Output.debug ("cnf_axiom: duplicate or variant of theorem " ^ name);
wenzelm@20461
   534
                        Output.debug (string_of_thm th);
wenzelm@20461
   535
                        Output.debug (string_of_thm th');
wenzelm@20461
   536
                        cls);
paulson@15347
   537
paulson@18141
   538
fun pairname th = (Thm.name_of_thm th, th);
paulson@18141
   539
wenzelm@20461
   540
fun meta_cnf_axiom th =
paulson@15956
   541
    map Meson.make_meta_clause (cnf_axiom (pairname th));
paulson@15499
   542
paulson@15347
   543
paulson@15872
   544
(**** Extract and Clausify theorems from a theory's claset and simpset ****)
paulson@15347
   545
paulson@17404
   546
(*Preserve the name of "th" after the transformation "f"*)
paulson@17404
   547
fun preserve_name f th = Thm.name_thm (Thm.name_of_thm th, f th);
paulson@17404
   548
paulson@17484
   549
fun rules_of_claset cs =
paulson@17484
   550
  let val {safeIs,safeEs,hazIs,hazEs,...} = rep_cs cs
paulson@19175
   551
      val intros = safeIs @ hazIs
wenzelm@18532
   552
      val elims  = map Classical.classical_rule (safeEs @ hazEs)
paulson@17404
   553
  in
wenzelm@20461
   554
     Output.debug ("rules_of_claset intros: " ^ Int.toString(length intros) ^
paulson@17484
   555
            " elims: " ^ Int.toString(length elims));
paulson@20017
   556
     map pairname (intros @ elims)
paulson@17404
   557
  end;
paulson@15347
   558
paulson@17484
   559
fun rules_of_simpset ss =
paulson@17484
   560
  let val ({rules,...}, _) = rep_ss ss
paulson@17484
   561
      val simps = Net.entries rules
wenzelm@20461
   562
  in
wenzelm@18680
   563
      Output.debug ("rules_of_simpset: " ^ Int.toString(length simps));
paulson@17484
   564
      map (fn r => (#name r, #thm r)) simps
paulson@17484
   565
  end;
paulson@17484
   566
paulson@17484
   567
fun claset_rules_of_thy thy = rules_of_claset (claset_of thy);
paulson@17484
   568
fun simpset_rules_of_thy thy = rules_of_simpset (simpset_of thy);
paulson@17484
   569
wenzelm@20774
   570
fun atpset_rules_of_thy thy = map pairname (ResAtpset.get_atpset (Context.Theory thy));
mengj@19196
   571
mengj@19196
   572
paulson@17484
   573
fun claset_rules_of_ctxt ctxt = rules_of_claset (local_claset_of ctxt);
paulson@17484
   574
fun simpset_rules_of_ctxt ctxt = rules_of_simpset (local_simpset_of ctxt);
paulson@15347
   575
wenzelm@20774
   576
fun atpset_rules_of_ctxt ctxt = map pairname (ResAtpset.get_atpset (Context.Proof ctxt));
wenzelm@20774
   577
paulson@15347
   578
paulson@15872
   579
(**** Translate a set of classical/simplifier rules into CNF (still as type "thm")  ****)
paulson@15347
   580
paulson@19894
   581
(* classical rules: works for both FOL and HOL *)
paulson@19894
   582
fun cnf_rules [] err_list = ([],err_list)
wenzelm@20461
   583
  | cnf_rules ((name,th) :: ths) err_list =
paulson@19894
   584
      let val (ts,es) = cnf_rules ths err_list
wenzelm@20461
   585
      in  (cnf_axiom (name,th) :: ts,es) handle  _ => (ts, (th::es))  end;
paulson@15347
   586
paulson@19894
   587
fun pair_name_cls k (n, []) = []
paulson@19894
   588
  | pair_name_cls k (n, cls::clss) = (cls, (n,k)) :: pair_name_cls (k+1) (n, clss)
wenzelm@20461
   589
paulson@19894
   590
fun cnf_rules_pairs_aux pairs [] = pairs
paulson@19894
   591
  | cnf_rules_pairs_aux pairs ((name,th)::ths) =
paulson@20457
   592
      let val pairs' = (pair_name_cls 0 (name, cnf_axiom(name,th))) @ pairs
wenzelm@20461
   593
                       handle THM _ => pairs | ResClause.CLAUSE _ => pairs
wenzelm@20461
   594
                            | ResHolClause.LAM2COMB _ => pairs
paulson@19894
   595
      in  cnf_rules_pairs_aux pairs' ths  end;
wenzelm@20461
   596
paulson@19894
   597
val cnf_rules_pairs = cnf_rules_pairs_aux [];
mengj@19353
   598
mengj@19196
   599
mengj@18198
   600
(**** Convert all theorems of a claset/simpset into clauses (ResClause.clause, or ResHolClause.clause) ****)
paulson@15347
   601
paulson@20419
   602
(*Setup function: takes a theory and installs ALL known theorems into the clause cache*)
paulson@20457
   603
wenzelm@20461
   604
fun skolem_cache (name,th) thy =
wenzelm@20461
   605
  let val prop = Thm.prop_of th
paulson@20457
   606
  in
wenzelm@20461
   607
      if lambda_free prop orelse monomorphic prop
paulson@20457
   608
      then thy    (*monomorphic theorems can be Skolemized on demand*)
wenzelm@20461
   609
      else #2 (skolem_cache_thm (name,th) thy)
paulson@20457
   610
  end;
paulson@20457
   611
wenzelm@20461
   612
fun clause_cache_setup thy = fold skolem_cache (PureThy.all_thms_of thy) thy;
wenzelm@20461
   613
paulson@16563
   614
paulson@16563
   615
(*** meson proof methods ***)
paulson@16563
   616
paulson@16563
   617
fun cnf_rules_of_ths ths = List.concat (#1 (cnf_rules (map pairname ths) []));
paulson@16563
   618
paulson@16563
   619
fun meson_meth ths ctxt =
paulson@16563
   620
  Method.SIMPLE_METHOD' HEADGOAL
paulson@16563
   621
    (CHANGED_PROP o Meson.meson_claset_tac (cnf_rules_of_ths ths) (local_claset_of ctxt));
paulson@16563
   622
paulson@16563
   623
val meson_method_setup =
wenzelm@18708
   624
  Method.add_methods
wenzelm@20461
   625
    [("meson", Method.thms_ctxt_args meson_meth,
wenzelm@18833
   626
      "MESON resolution proof procedure")];
paulson@15347
   627
paulson@18510
   628
paulson@18510
   629
paulson@18510
   630
(*** The Skolemization attribute ***)
paulson@18510
   631
paulson@18510
   632
fun conj2_rule (th1,th2) = conjI OF [th1,th2];
paulson@18510
   633
paulson@20457
   634
(*Conjoin a list of theorems to form a single theorem*)
paulson@20457
   635
fun conj_rule []  = TrueI
paulson@20445
   636
  | conj_rule ths = foldr1 conj2_rule ths;
paulson@18510
   637
paulson@20419
   638
fun skolem_attr (Context.Theory thy, th) =
paulson@20419
   639
      let val name = Thm.name_of_thm th
wenzelm@20461
   640
          val (cls, thy') = skolem_cache_thm (name, th) thy
wenzelm@18728
   641
      in (Context.Theory thy', conj_rule cls) end
paulson@20419
   642
  | skolem_attr (context, th) = (context, conj_rule (skolem_thm th));
paulson@18510
   643
paulson@18510
   644
val setup_attrs = Attrib.add_attributes
paulson@20419
   645
  [("skolem", Attrib.no_args skolem_attr, "skolemization of a theorem")];
paulson@18510
   646
wenzelm@18708
   647
val setup = clause_cache_setup #> setup_attrs;
paulson@18510
   648
wenzelm@20461
   649
end;