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