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