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