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