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