src/HOL/Tools/res_axioms.ML
author wenzelm
Tue Sep 19 23:15:32 2006 +0200 (2006-09-19)
changeset 20624 ba081ac0ed7e
parent 20567 93ae490fe02c
child 20710 384bfce59254
permissions -rw-r--r--
sko/abs: Name.internal prevents choking of print_theory;
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@20419
   271
(*Traverse a theorem, declaring abstraction function definitions. String s is the suggested
paulson@20419
   272
  prefix for the constants. Resulting theory is returned in the first theorem. *)
paulson@20419
   273
fun declare_absfuns th =
wenzelm@20461
   274
  let fun abstract thy ct =
paulson@20445
   275
        if lambda_free (term_of ct) then (transfer thy (reflexive ct), [])
paulson@20445
   276
        else
paulson@20445
   277
        case term_of ct of
paulson@20419
   278
          Abs (_,T,u) =>
wenzelm@20624
   279
            let val cname = Name.internal (gensym "abs_");
wenzelm@20461
   280
                val _ = assert_eta_free ct;
wenzelm@20461
   281
                val (cv,cta) = Thm.dest_abs NONE ct
wenzelm@20461
   282
                val v = (#1 o dest_Free o term_of) cv
wenzelm@20461
   283
                val (u'_th,defs) = abstract thy cta
paulson@20445
   284
                val cu' = crhs_of u'_th
wenzelm@20461
   285
                val abs_v_u = lambda (term_of cv) (term_of cu')
wenzelm@20461
   286
                (*get the formal parameters: ALL variables free in the term*)
wenzelm@20461
   287
                val args = term_frees abs_v_u
wenzelm@20461
   288
                val rhs = list_abs_free (map dest_Free args, abs_v_u)
wenzelm@20461
   289
                      (*Forms a lambda-abstraction over the formal parameters*)
wenzelm@20461
   290
                val v_rhs = Logic.varify rhs
wenzelm@20461
   291
                val (ax,thy) =
wenzelm@20461
   292
                 case List.find (fn ax => v_rhs aconv rhs_of ax)
wenzelm@20461
   293
                        (Net.match_term (!abstraction_cache) v_rhs) of
wenzelm@20461
   294
                     SOME ax => (ax,thy)   (*cached axiom, current theory*)
wenzelm@20461
   295
                   | NONE =>
wenzelm@20461
   296
                      let val Ts = map type_of args
wenzelm@20461
   297
                          val cT = Ts ---> (T --> typ_of (ctyp_of_term cu'))
wenzelm@20461
   298
                          val thy = theory_of_thm u'_th
wenzelm@20461
   299
                          val c = Const (Sign.full_name thy cname, cT)
wenzelm@20461
   300
                          val thy = Theory.add_consts_i [(cname, cT, NoSyn)] thy
wenzelm@20461
   301
                                     (*Theory is augmented with the constant,
wenzelm@20461
   302
                                       then its definition*)
wenzelm@20461
   303
                          val cdef = cname ^ "_def"
wenzelm@20461
   304
                          val thy = Theory.add_defs_i false false
wenzelm@20461
   305
                                       [(cdef, equals cT $ c $ rhs)] thy
wenzelm@20461
   306
                          val ax = get_axiom thy cdef
wenzelm@20461
   307
                          val _ = abstraction_cache := Net.insert_term eq_absdef (v_rhs,ax)
wenzelm@20461
   308
                                    (!abstraction_cache)
wenzelm@20461
   309
                            handle Net.INSERT =>
wenzelm@20461
   310
                              raise THM ("declare_absfuns: INSERT", 0, [th,u'_th,ax])
wenzelm@20461
   311
                       in  (ax,thy)  end
wenzelm@20461
   312
                val _ = assert (v_rhs aconv rhs_of ax) "declare_absfuns: rhs mismatch"
wenzelm@20461
   313
                val def = #1 (Drule.freeze_thaw ax)
wenzelm@20461
   314
                val def_args = list_combination def (map (cterm_of thy) args)
wenzelm@20461
   315
            in (transitive (abstract_rule v cv u'_th) (symmetric def_args),
wenzelm@20461
   316
                def :: defs) end
wenzelm@20461
   317
        | (t1$t2) =>
wenzelm@20461
   318
            let val (ct1,ct2) = Thm.dest_comb ct
wenzelm@20461
   319
                val (th1,defs1) = abstract thy ct1
wenzelm@20461
   320
                val (th2,defs2) = abstract (theory_of_thm th1) ct2
wenzelm@20461
   321
            in  (combination th1 th2, defs1@defs2)  end
paulson@20419
   322
      val _ = if !trace_abs then warning (string_of_thm th) else ();
paulson@20419
   323
      val (eqth,defs) = abstract (theory_of_thm th) (cprop_of th)
paulson@20419
   324
      val ths = equal_elim eqth th ::
paulson@20419
   325
                map (forall_intr_vars o strip_lambdas o object_eq) defs
paulson@20419
   326
  in  (theory_of_thm eqth, ths)  end;
paulson@20419
   327
paulson@20567
   328
fun name_of def = SOME (#1 (dest_Free (lhs_of def))) handle _ => NONE;
paulson@20567
   329
paulson@20525
   330
(*A name is valid provided it isn't the name of a defined abstraction.*)
paulson@20567
   331
fun valid_name defs (Free(x,T)) = not (x mem_string (List.mapPartial name_of defs))
paulson@20525
   332
  | valid_name defs _ = false;
paulson@20525
   333
paulson@20419
   334
fun assume_absfuns th =
paulson@20445
   335
  let val thy = theory_of_thm th
paulson@20445
   336
      val cterm = cterm_of thy
paulson@20525
   337
      fun abstract ct =
paulson@20445
   338
        if lambda_free (term_of ct) then (reflexive ct, [])
paulson@20445
   339
        else
paulson@20445
   340
        case term_of ct of
paulson@20419
   341
          Abs (_,T,u) =>
wenzelm@20461
   342
            let val (cv,cta) = Thm.dest_abs NONE ct
wenzelm@20461
   343
                val _ = assert_eta_free ct;
wenzelm@20461
   344
                val v = (#1 o dest_Free o term_of) cv
paulson@20525
   345
                val (u'_th,defs) = abstract cta
paulson@20445
   346
                val cu' = crhs_of u'_th
wenzelm@20461
   347
                val abs_v_u = Thm.cabs cv cu'
paulson@20525
   348
                (*get the formal parameters: free variables not present in the defs
paulson@20525
   349
                  (to avoid taking abstraction function names as parameters) *)
paulson@20525
   350
                val args = filter (valid_name defs) (term_frees (term_of abs_v_u))
wenzelm@20461
   351
                val crhs = list_cabs (map cterm args, abs_v_u)
wenzelm@20461
   352
                      (*Forms a lambda-abstraction over the formal parameters*)
wenzelm@20461
   353
                val rhs = term_of crhs
paulson@20525
   354
                val def =  (*FIXME: can we also reuse the const-abstractions?*)
wenzelm@20461
   355
                 case List.find (fn ax => rhs aconv rhs_of ax andalso
wenzelm@20461
   356
                                          Context.joinable (thy, theory_of_thm ax))
wenzelm@20461
   357
                        (Net.match_term (!abstraction_cache) rhs) of
wenzelm@20461
   358
                     SOME ax => ax
wenzelm@20461
   359
                   | NONE =>
wenzelm@20461
   360
                      let val Ts = map type_of args
wenzelm@20461
   361
                          val const_ty = Ts ---> (T --> typ_of (ctyp_of_term cu'))
wenzelm@20461
   362
                          val c = Free (gensym "abs_", const_ty)
wenzelm@20461
   363
                          val ax = assume (Thm.capply (cterm (equals const_ty $ c)) crhs)
wenzelm@20461
   364
                          val _ = abstraction_cache := Net.insert_term eq_absdef (rhs,ax)
wenzelm@20461
   365
                                    (!abstraction_cache)
wenzelm@20461
   366
                            handle Net.INSERT =>
wenzelm@20461
   367
                              raise THM ("assume_absfuns: INSERT", 0, [th,u'_th,ax])
wenzelm@20461
   368
                      in ax end
wenzelm@20461
   369
                val _ = assert (rhs aconv rhs_of def) "assume_absfuns: rhs mismatch"
wenzelm@20461
   370
                val def_args = list_combination def (map cterm args)
wenzelm@20461
   371
            in (transitive (abstract_rule v cv u'_th) (symmetric def_args),
wenzelm@20461
   372
                def :: defs) end
wenzelm@20461
   373
        | (t1$t2) =>
wenzelm@20461
   374
            let val (ct1,ct2) = Thm.dest_comb ct
paulson@20525
   375
                val (t1',defs1) = abstract ct1
paulson@20525
   376
                val (t2',defs2) = abstract ct2
wenzelm@20461
   377
            in  (combination t1' t2', defs1@defs2)  end
paulson@20525
   378
      val (eqth,defs) = abstract (cprop_of th)
paulson@20419
   379
  in  equal_elim eqth th ::
paulson@20419
   380
      map (forall_intr_vars o strip_lambdas o object_eq) defs
paulson@20419
   381
  end;
paulson@20419
   382
paulson@16009
   383
paulson@16009
   384
(*cterms are used throughout for efficiency*)
paulson@18141
   385
val cTrueprop = Thm.cterm_of HOL.thy HOLogic.Trueprop;
paulson@16009
   386
paulson@16009
   387
(*cterm version of mk_cTrueprop*)
paulson@16009
   388
fun c_mkTrueprop A = Thm.capply cTrueprop A;
paulson@16009
   389
paulson@16009
   390
(*Given an abstraction over n variables, replace the bound variables by free
paulson@16009
   391
  ones. Return the body, along with the list of free variables.*)
wenzelm@20461
   392
fun c_variant_abs_multi (ct0, vars) =
paulson@16009
   393
      let val (cv,ct) = Thm.dest_abs NONE ct0
paulson@16009
   394
      in  c_variant_abs_multi (ct, cv::vars)  end
paulson@16009
   395
      handle CTERM _ => (ct0, rev vars);
paulson@16009
   396
wenzelm@20461
   397
(*Given the definition of a Skolem function, return a theorem to replace
wenzelm@20461
   398
  an existential formula by a use of that function.
paulson@18141
   399
   Example: "EX x. x : A & x ~: B ==> sko A B : A & sko A B ~: B"  [.] *)
wenzelm@20461
   400
fun skolem_of_def def =
wenzelm@20292
   401
  let val (c,rhs) = Drule.dest_equals (cprop_of (#1 (Drule.freeze_thaw def)))
paulson@16009
   402
      val (ch, frees) = c_variant_abs_multi (rhs, [])
paulson@18141
   403
      val (chilbert,cabs) = Thm.dest_comb ch
paulson@18141
   404
      val {sign,t, ...} = rep_cterm chilbert
paulson@18141
   405
      val T = case t of Const ("Hilbert_Choice.Eps", Type("fun",[_,T])) => T
paulson@18141
   406
                      | _ => raise THM ("skolem_of_def: expected Eps", 0, [def])
paulson@16009
   407
      val cex = Thm.cterm_of sign (HOLogic.exists_const T)
paulson@16009
   408
      val ex_tm = c_mkTrueprop (Thm.capply cex cabs)
paulson@16009
   409
      and conc =  c_mkTrueprop (Drule.beta_conv cabs (Drule.list_comb(c,frees)));
paulson@18141
   410
      fun tacf [prem] = rewrite_goals_tac [def] THEN rtac (prem RS someI_ex) 1
wenzelm@20461
   411
  in  Goal.prove_raw [ex_tm] conc tacf
paulson@18141
   412
       |> forall_intr_list frees
paulson@18141
   413
       |> forall_elim_vars 0  (*Introduce Vars, but don't discharge defs.*)
paulson@18141
   414
       |> Thm.varifyT
paulson@18141
   415
  end;
paulson@16009
   416
mengj@18198
   417
(*Converts an Isabelle theorem (intro, elim or simp format) into nnf.*)
mengj@18198
   418
(*It now works for HOL too. *)
wenzelm@20461
   419
fun to_nnf th =
paulson@18141
   420
    th |> transfer_to_Reconstruction
paulson@20419
   421
       |> transform_elim |> zero_var_indexes |> Drule.freeze_thaw |> #1
paulson@16588
   422
       |> ObjectLogic.atomize_thm |> make_nnf;
paulson@16009
   423
wenzelm@20461
   424
(*The cache prevents repeated clausification of a theorem,
wenzelm@20461
   425
  and also repeated declaration of Skolem functions*)
paulson@18510
   426
  (* FIXME better use Termtab!? No, we MUST use theory data!!*)
paulson@15955
   427
val clause_cache = ref (Symtab.empty : (thm * thm list) Symtab.table)
paulson@15955
   428
paulson@18141
   429
paulson@18141
   430
(*Generate Skolem functions for a theorem supplied in nnf*)
paulson@18141
   431
fun skolem_of_nnf th =
paulson@18141
   432
  map (skolem_of_def o assume o (cterm_of (theory_of_thm th))) (assume_skofuns th);
paulson@18141
   433
paulson@20457
   434
fun assert_lambda_free ths = assert (forall (lambda_free o prop_of) ths);
paulson@20457
   435
paulson@20445
   436
fun assume_abstract th =
paulson@20457
   437
  if lambda_free (prop_of th) then [th]
wenzelm@20461
   438
  else th |> eta_conversion_rule |> assume_absfuns
paulson@20457
   439
          |> tap (fn ths => assert_lambda_free ths "assume_abstract: lambdas")
paulson@20445
   440
paulson@20419
   441
(*Replace lambdas by assumed function definitions in the theorems*)
paulson@20445
   442
fun assume_abstract_list ths =
paulson@20445
   443
  if abstract_lambdas then List.concat (map assume_abstract ths)
paulson@20419
   444
  else map eta_conversion_rule ths;
paulson@20419
   445
paulson@20419
   446
(*Replace lambdas by declared function definitions in the theorems*)
paulson@20419
   447
fun declare_abstract' (thy, []) = (thy, [])
paulson@20419
   448
  | declare_abstract' (thy, th::ths) =
wenzelm@20461
   449
      let val (thy', th_defs) =
paulson@20457
   450
            if lambda_free (prop_of th) then (thy, [th])
paulson@20445
   451
            else
wenzelm@20461
   452
                th |> zero_var_indexes |> Drule.freeze_thaw |> #1
wenzelm@20461
   453
                   |> eta_conversion_rule |> transfer thy |> declare_absfuns
wenzelm@20461
   454
          val _ = assert_lambda_free th_defs "declare_abstract: lambdas"
wenzelm@20461
   455
          val (thy'', ths') = declare_abstract' (thy', ths)
paulson@20419
   456
      in  (thy'', th_defs @ ths')  end;
paulson@20419
   457
paulson@20421
   458
(*FIXME DELETE if we decide to switch to abstractions*)
paulson@20419
   459
fun declare_abstract (thy, ths) =
paulson@20419
   460
  if abstract_lambdas then declare_abstract' (thy, ths)
paulson@20419
   461
  else (thy, map eta_conversion_rule ths);
paulson@20419
   462
paulson@18510
   463
(*Skolemize a named theorem, with Skolem functions as additional premises.*)
wenzelm@20461
   464
(*also works for HOL*)
wenzelm@20461
   465
fun skolem_thm th =
paulson@18510
   466
  let val nnfth = to_nnf th
paulson@20419
   467
  in  Meson.make_cnf (skolem_of_nnf nnfth) nnfth
paulson@20445
   468
      |> assume_abstract_list |> Meson.finish_cnf |> rm_redundant_cls
paulson@18510
   469
  end
paulson@18510
   470
  handle THM _ => [];
paulson@18141
   471
paulson@18510
   472
(*Declare Skolem functions for a theorem, supplied in nnf and with its name.
paulson@18510
   473
  It returns a modified theory, unless skolemization fails.*)
paulson@16009
   474
fun skolem thy (name,th) =
paulson@20419
   475
  let val cname = (case name of "" => gensym "" | s => Sign.base_name s)
paulson@20419
   476
      val _ = Output.debug ("skolemizing " ^ name ^ ": ")
wenzelm@20461
   477
  in Option.map
wenzelm@20461
   478
        (fn nnfth =>
paulson@18141
   479
          let val (thy',defs) = declare_skofuns cname nnfth thy
paulson@20419
   480
              val cnfs = Meson.make_cnf (map skolem_of_def defs) nnfth
paulson@20419
   481
              val (thy'',cnfs') = declare_abstract (thy',cnfs)
paulson@20419
   482
          in (thy'', rm_redundant_cls (Meson.finish_cnf cnfs'))
paulson@20419
   483
          end)
wenzelm@20461
   484
      (SOME (to_nnf th)  handle THM _ => NONE)
paulson@18141
   485
  end;
paulson@16009
   486
paulson@18510
   487
(*Populate the clause cache using the supplied theorem. Return the clausal form
paulson@18510
   488
  and modified theory.*)
wenzelm@20461
   489
fun skolem_cache_thm (name,th) thy =
paulson@18144
   490
  case Symtab.lookup (!clause_cache) name of
wenzelm@20461
   491
      NONE =>
wenzelm@20461
   492
        (case skolem thy (name, Thm.transfer thy th) of
wenzelm@20461
   493
             NONE => ([th],thy)
paulson@20473
   494
           | SOME (thy',cls) => 
paulson@20473
   495
               let val cls = map Drule.local_standard cls
paulson@20473
   496
               in
paulson@20473
   497
                  if null cls then warning ("skolem_cache: empty clause set for " ^ name)
paulson@20473
   498
                  else ();
paulson@20473
   499
                  change clause_cache (Symtab.update (name, (th, cls))); 
paulson@20473
   500
                  (cls,thy')
paulson@20473
   501
               end)
paulson@18144
   502
    | SOME (th',cls) =>
paulson@18510
   503
        if eq_thm(th,th') then (cls,thy)
wenzelm@20461
   504
        else (Output.debug ("skolem_cache: Ignoring variant of theorem " ^ name);
wenzelm@20461
   505
              Output.debug (string_of_thm th);
wenzelm@20461
   506
              Output.debug (string_of_thm th');
wenzelm@20461
   507
              ([th],thy));
wenzelm@20461
   508
wenzelm@20461
   509
(*Exported function to convert Isabelle theorems into axiom clauses*)
paulson@19894
   510
fun cnf_axiom (name,th) =
paulson@18144
   511
  case name of
wenzelm@20461
   512
        "" => skolem_thm th (*no name, so can't cache*)
paulson@18144
   513
      | s  => case Symtab.lookup (!clause_cache) s of
paulson@20473
   514
                NONE => 
paulson@20473
   515
                  let val cls = map Drule.local_standard (skolem_thm th)
wenzelm@20461
   516
                  in change clause_cache (Symtab.update (s, (th, cls))); cls end
wenzelm@20461
   517
              | SOME(th',cls) =>
wenzelm@20461
   518
                  if eq_thm(th,th') then cls
wenzelm@20461
   519
                  else (Output.debug ("cnf_axiom: duplicate or variant of theorem " ^ name);
wenzelm@20461
   520
                        Output.debug (string_of_thm th);
wenzelm@20461
   521
                        Output.debug (string_of_thm th');
wenzelm@20461
   522
                        cls);
paulson@15347
   523
paulson@18141
   524
fun pairname th = (Thm.name_of_thm th, th);
paulson@18141
   525
wenzelm@20461
   526
fun meta_cnf_axiom th =
paulson@15956
   527
    map Meson.make_meta_clause (cnf_axiom (pairname th));
paulson@15499
   528
paulson@15347
   529
paulson@15872
   530
(**** Extract and Clausify theorems from a theory's claset and simpset ****)
paulson@15347
   531
paulson@17404
   532
(*Preserve the name of "th" after the transformation "f"*)
paulson@17404
   533
fun preserve_name f th = Thm.name_thm (Thm.name_of_thm th, f th);
paulson@17404
   534
paulson@17484
   535
fun rules_of_claset cs =
paulson@17484
   536
  let val {safeIs,safeEs,hazIs,hazEs,...} = rep_cs cs
paulson@19175
   537
      val intros = safeIs @ hazIs
wenzelm@18532
   538
      val elims  = map Classical.classical_rule (safeEs @ hazEs)
paulson@17404
   539
  in
wenzelm@20461
   540
     Output.debug ("rules_of_claset intros: " ^ Int.toString(length intros) ^
paulson@17484
   541
            " elims: " ^ Int.toString(length elims));
paulson@20017
   542
     map pairname (intros @ elims)
paulson@17404
   543
  end;
paulson@15347
   544
paulson@17484
   545
fun rules_of_simpset ss =
paulson@17484
   546
  let val ({rules,...}, _) = rep_ss ss
paulson@17484
   547
      val simps = Net.entries rules
wenzelm@20461
   548
  in
wenzelm@18680
   549
      Output.debug ("rules_of_simpset: " ^ Int.toString(length simps));
paulson@17484
   550
      map (fn r => (#name r, #thm r)) simps
paulson@17484
   551
  end;
paulson@17484
   552
paulson@17484
   553
fun claset_rules_of_thy thy = rules_of_claset (claset_of thy);
paulson@17484
   554
fun simpset_rules_of_thy thy = rules_of_simpset (simpset_of thy);
paulson@17484
   555
mengj@19196
   556
fun atpset_rules_of_thy thy = map pairname (ResAtpSet.atp_rules_of_thy thy);
mengj@19196
   557
mengj@19196
   558
paulson@17484
   559
fun claset_rules_of_ctxt ctxt = rules_of_claset (local_claset_of ctxt);
paulson@17484
   560
fun simpset_rules_of_ctxt ctxt = rules_of_simpset (local_simpset_of ctxt);
paulson@15347
   561
mengj@19196
   562
fun atpset_rules_of_ctxt ctxt = map pairname (ResAtpSet.atp_rules_of_ctxt ctxt);
paulson@15347
   563
paulson@15872
   564
(**** Translate a set of classical/simplifier rules into CNF (still as type "thm")  ****)
paulson@15347
   565
paulson@19894
   566
(* classical rules: works for both FOL and HOL *)
paulson@19894
   567
fun cnf_rules [] err_list = ([],err_list)
wenzelm@20461
   568
  | cnf_rules ((name,th) :: ths) err_list =
paulson@19894
   569
      let val (ts,es) = cnf_rules ths err_list
wenzelm@20461
   570
      in  (cnf_axiom (name,th) :: ts,es) handle  _ => (ts, (th::es))  end;
paulson@15347
   571
paulson@19894
   572
fun pair_name_cls k (n, []) = []
paulson@19894
   573
  | pair_name_cls k (n, cls::clss) = (cls, (n,k)) :: pair_name_cls (k+1) (n, clss)
wenzelm@20461
   574
paulson@19894
   575
fun cnf_rules_pairs_aux pairs [] = pairs
paulson@19894
   576
  | cnf_rules_pairs_aux pairs ((name,th)::ths) =
paulson@20457
   577
      let val pairs' = (pair_name_cls 0 (name, cnf_axiom(name,th))) @ pairs
wenzelm@20461
   578
                       handle THM _ => pairs | ResClause.CLAUSE _ => pairs
wenzelm@20461
   579
                            | ResHolClause.LAM2COMB _ => pairs
paulson@19894
   580
      in  cnf_rules_pairs_aux pairs' ths  end;
wenzelm@20461
   581
paulson@19894
   582
val cnf_rules_pairs = cnf_rules_pairs_aux [];
mengj@19353
   583
mengj@19196
   584
mengj@18198
   585
(**** Convert all theorems of a claset/simpset into clauses (ResClause.clause, or ResHolClause.clause) ****)
paulson@15347
   586
paulson@20419
   587
(*Setup function: takes a theory and installs ALL known theorems into the clause cache*)
paulson@20457
   588
wenzelm@20461
   589
fun skolem_cache (name,th) thy =
wenzelm@20461
   590
  let val prop = Thm.prop_of th
paulson@20457
   591
  in
wenzelm@20461
   592
      if lambda_free prop orelse monomorphic prop
paulson@20457
   593
      then thy    (*monomorphic theorems can be Skolemized on demand*)
wenzelm@20461
   594
      else #2 (skolem_cache_thm (name,th) thy)
paulson@20457
   595
  end;
paulson@20457
   596
wenzelm@20461
   597
fun clause_cache_setup thy = fold skolem_cache (PureThy.all_thms_of thy) thy;
wenzelm@20461
   598
paulson@16563
   599
paulson@16563
   600
(*** meson proof methods ***)
paulson@16563
   601
paulson@16563
   602
fun cnf_rules_of_ths ths = List.concat (#1 (cnf_rules (map pairname ths) []));
paulson@16563
   603
paulson@16563
   604
fun meson_meth ths ctxt =
paulson@16563
   605
  Method.SIMPLE_METHOD' HEADGOAL
paulson@16563
   606
    (CHANGED_PROP o Meson.meson_claset_tac (cnf_rules_of_ths ths) (local_claset_of ctxt));
paulson@16563
   607
paulson@16563
   608
val meson_method_setup =
wenzelm@18708
   609
  Method.add_methods
wenzelm@20461
   610
    [("meson", Method.thms_ctxt_args meson_meth,
wenzelm@18833
   611
      "MESON resolution proof procedure")];
paulson@15347
   612
paulson@18510
   613
paulson@18510
   614
paulson@18510
   615
(*** The Skolemization attribute ***)
paulson@18510
   616
paulson@18510
   617
fun conj2_rule (th1,th2) = conjI OF [th1,th2];
paulson@18510
   618
paulson@20457
   619
(*Conjoin a list of theorems to form a single theorem*)
paulson@20457
   620
fun conj_rule []  = TrueI
paulson@20445
   621
  | conj_rule ths = foldr1 conj2_rule ths;
paulson@18510
   622
paulson@20419
   623
fun skolem_attr (Context.Theory thy, th) =
paulson@20419
   624
      let val name = Thm.name_of_thm th
wenzelm@20461
   625
          val (cls, thy') = skolem_cache_thm (name, th) thy
wenzelm@18728
   626
      in (Context.Theory thy', conj_rule cls) end
paulson@20419
   627
  | skolem_attr (context, th) = (context, conj_rule (skolem_thm th));
paulson@18510
   628
paulson@18510
   629
val setup_attrs = Attrib.add_attributes
paulson@20419
   630
  [("skolem", Attrib.no_args skolem_attr, "skolemization of a theorem")];
paulson@18510
   631
wenzelm@18708
   632
val setup = clause_cache_setup #> setup_attrs;
paulson@18510
   633
wenzelm@20461
   634
end;