src/HOL/Tools/Sledgehammer/sledgehammer_fact_preprocessor.ML
author blanchet
Tue Jun 22 14:28:22 2010 +0200 (2010-06-22 ago)
changeset 37498 b426cbdb5a23
parent 37496 9ae78e12e126
child 37500 7587b6e63454
permissions -rw-r--r--
removed Sledgehammer's support for the DFG syntax;
this removes 350 buggy lines from Sledgehammer. SPASS 3.5 and above support the TPTP syntax.
     1 (*  Title:      HOL/Tools/Sledgehammer/sledgehammer_fact_preprocessor.ML
     2     Author:     Jia Meng, Cambridge University Computer Laboratory
     3     Author:     Jasmin Blanchette, TU Muenchen
     4 
     5 Transformation of axiom rules (elim/intro/etc) into CNF forms.
     6 *)
     7 
     8 signature SLEDGEHAMMER_FACT_PREPROCESSOR =
     9 sig
    10   val chained_prefix: string
    11   val trace: bool Unsynchronized.ref
    12   val trace_msg: (unit -> string) -> unit
    13   val skolem_theory_name: string
    14   val skolem_prefix: string
    15   val skolem_infix: string
    16   val is_skolem_const_name: string -> bool
    17   val cnf_axiom: theory -> thm -> thm list
    18   val multi_base_blacklist: string list
    19   val is_theorem_bad_for_atps: thm -> bool
    20   val type_has_topsort: typ -> bool
    21   val cnf_rules_pairs:
    22     theory -> (string * thm) list -> (thm * (string * int)) list
    23   val saturate_skolem_cache: theory -> theory option
    24   val auto_saturate_skolem_cache: bool Unsynchronized.ref
    25     (* for emergency use where the Skolem cache causes problems *)
    26   val neg_clausify: thm -> thm list
    27   val neg_conjecture_clauses:
    28     Proof.context -> thm -> int -> thm list list * (string * typ) list
    29   val neg_clausify_tac: Proof.context -> int -> tactic
    30   val setup: theory -> theory
    31 end;
    32 
    33 structure Sledgehammer_Fact_Preprocessor : SLEDGEHAMMER_FACT_PREPROCESSOR =
    34 struct
    35 
    36 open Sledgehammer_FOL_Clause
    37 
    38 (* Used to label theorems chained into the goal. *)
    39 val chained_prefix = "Sledgehammer.chained_"
    40 
    41 val trace = Unsynchronized.ref false;
    42 fun trace_msg msg = if !trace then tracing (msg ()) else ();
    43 
    44 val skolem_theory_name = "Sledgehammer.Sko"
    45 val skolem_prefix = "sko_"
    46 val skolem_infix = "$"
    47 
    48 fun freeze_thm th = #1 (Drule.legacy_freeze_thaw th);
    49 
    50 val type_has_topsort = Term.exists_subtype
    51   (fn TFree (_, []) => true
    52     | TVar (_, []) => true
    53     | _ => false);
    54 
    55 
    56 (**** Transformation of Elimination Rules into First-Order Formulas****)
    57 
    58 val cfalse = cterm_of @{theory HOL} HOLogic.false_const;
    59 val ctp_false = cterm_of @{theory HOL} (HOLogic.mk_Trueprop HOLogic.false_const);
    60 
    61 (*Converts an elim-rule into an equivalent theorem that does not have the
    62   predicate variable.  Leaves other theorems unchanged.  We simply instantiate the
    63   conclusion variable to False.*)
    64 fun transform_elim th =
    65   case concl_of th of    (*conclusion variable*)
    66        @{const Trueprop} $ (v as Var (_, @{typ bool})) =>
    67            Thm.instantiate ([], [(cterm_of @{theory HOL} v, cfalse)]) th
    68     | v as Var(_, @{typ prop}) =>
    69            Thm.instantiate ([], [(cterm_of @{theory HOL} v, ctp_false)]) th
    70     | _ => th;
    71 
    72 (*To enforce single-threading*)
    73 exception Clausify_failure of theory;
    74 
    75 
    76 (**** SKOLEMIZATION BY INFERENCE (lcp) ****)
    77 
    78 (*Keep the full complexity of the original name*)
    79 fun flatten_name s = space_implode "_X" (Long_Name.explode s);
    80 
    81 fun skolem_name thm_name j var_name =
    82   skolem_prefix ^ thm_name ^ "_" ^ Int.toString j ^
    83   skolem_infix ^ (if var_name = "" then "g" else flatten_name var_name)
    84 
    85 (* Hack: Could return false positives (e.g., a user happens to declare a
    86    constant called "SomeTheory.sko_means_shoe_in_$wedish". *)
    87 val is_skolem_const_name =
    88   Long_Name.base_name
    89   #> String.isPrefix skolem_prefix andf String.isSubstring skolem_infix
    90 
    91 fun rhs_extra_types lhsT rhs =
    92   let val lhs_vars = Term.add_tfreesT lhsT []
    93       fun add_new_TFrees (TFree v) =
    94             if member (op =) lhs_vars v then I else insert (op =) (TFree v)
    95         | add_new_TFrees _ = I
    96       val rhs_consts = fold_aterms (fn Const c => insert (op =) c | _ => I) rhs []
    97   in fold (#2 #> Term.fold_atyps add_new_TFrees) rhs_consts [] end;
    98 
    99 fun skolem_type_and_args bound_T body =
   100   let
   101     val args1 = OldTerm.term_frees body
   102     val Ts1 = map type_of args1
   103     val Ts2 = rhs_extra_types (Ts1 ---> bound_T) body
   104     val args2 = map (fn T => Free (gensym "vsk", T)) Ts2
   105   in (Ts2 ---> Ts1 ---> bound_T, args2 @ args1) end
   106 
   107 (* Traverse a theorem, declaring Skolem function definitions. String "s" is the
   108    suggested prefix for the Skolem constants. *)
   109 fun declare_skolem_funs s th thy =
   110   let
   111     val skolem_count = Unsynchronized.ref 0    (* FIXME ??? *)
   112     fun dec_sko (Const (@{const_name Ex}, _) $ (body as Abs (s', T, p)))
   113                 (axs, thy) =
   114         (*Existential: declare a Skolem function, then insert into body and continue*)
   115         let
   116           val id = skolem_name s (Unsynchronized.inc skolem_count) s'
   117           val (cT, args) = skolem_type_and_args T body
   118           val rhs = list_abs_free (map dest_Free args,
   119                                    HOLogic.choice_const T $ body)
   120                   (*Forms a lambda-abstraction over the formal parameters*)
   121           val (c, thy) =
   122             Sign.declare_const ((Binding.conceal (Binding.name id), cT), NoSyn) thy
   123           val cdef = id ^ "_def"
   124           val ((_, ax), thy) =
   125             Thm.add_def true false (Binding.name cdef, Logic.mk_equals (c, rhs)) thy
   126           val ax' = Drule.export_without_context ax
   127         in dec_sko (subst_bound (list_comb (c, args), p)) (ax' :: axs, thy) end
   128       | dec_sko (Const (@{const_name All}, _) $ (Abs (a, T, p))) thx =
   129         (*Universal quant: insert a free variable into body and continue*)
   130         let val fname = Name.variant (OldTerm.add_term_names (p, [])) a
   131         in dec_sko (subst_bound (Free (fname, T), p)) thx end
   132       | dec_sko (@{const "op &"} $ p $ q) thx = dec_sko q (dec_sko p thx)
   133       | dec_sko (@{const "op |"} $ p $ q) thx = dec_sko q (dec_sko p thx)
   134       | dec_sko (@{const Trueprop} $ p) thx = dec_sko p thx
   135       | dec_sko _ thx = thx
   136   in dec_sko (prop_of th) ([], thy) end
   137 
   138 fun mk_skolem_id t =
   139   let val T = fastype_of t in
   140     Const (@{const_name skolem_id}, T --> T) $ t
   141   end
   142 
   143 (*Traverse a theorem, accumulating Skolem function definitions.*)
   144 fun assume_skolem_funs inline s th =
   145   let
   146     val skolem_count = Unsynchronized.ref 0   (* FIXME ??? *)
   147     fun dec_sko (Const (@{const_name Ex}, _) $ (body as Abs (s', T, p))) defs =
   148         (*Existential: declare a Skolem function, then insert into body and continue*)
   149         let
   150           val skos = map (#1 o Logic.dest_equals) defs  (*existing sko fns*)
   151           val args = subtract (op =) skos (OldTerm.term_frees body) (*the formal parameters*)
   152           val Ts = map type_of args
   153           val cT = Ts ---> T (* FIXME: use "skolem_type_and_args" *)
   154           val id = skolem_name s (Unsynchronized.inc skolem_count) s'
   155           val c = Free (id, cT)
   156           val rhs = list_abs_free (map dest_Free args,
   157                                    HOLogic.choice_const T $ body)
   158                     |> inline ? mk_skolem_id
   159                 (*Forms a lambda-abstraction over the formal parameters*)
   160           val def = Logic.mk_equals (c, rhs)
   161           val comb = list_comb (if inline then rhs else c, args)
   162         in dec_sko (subst_bound (comb, p)) (def :: defs) end
   163       | dec_sko (Const (@{const_name All},_) $ Abs (a, T, p)) defs =
   164         (*Universal quant: insert a free variable into body and continue*)
   165         let val fname = Name.variant (OldTerm.add_term_names (p,[])) a
   166         in dec_sko (subst_bound (Free(fname,T), p)) defs end
   167       | dec_sko (@{const "op &"} $ p $ q) defs = dec_sko q (dec_sko p defs)
   168       | dec_sko (@{const "op |"} $ p $ q) defs = dec_sko q (dec_sko p defs)
   169       | dec_sko (@{const Trueprop} $ p) defs = dec_sko p defs
   170       | dec_sko _ defs = defs
   171   in  dec_sko (prop_of th) []  end;
   172 
   173 
   174 (**** REPLACING ABSTRACTIONS BY COMBINATORS ****)
   175 
   176 (*Returns the vars of a theorem*)
   177 fun vars_of_thm th =
   178   map (Thm.cterm_of (theory_of_thm th) o Var) (Thm.fold_terms Term.add_vars th []);
   179 
   180 (*Make a version of fun_cong with a given variable name*)
   181 local
   182     val fun_cong' = fun_cong RS asm_rl; (*renumber f, g to prevent clashes with (a,0)*)
   183     val cx = hd (vars_of_thm fun_cong');
   184     val ty = typ_of (ctyp_of_term cx);
   185     val thy = theory_of_thm fun_cong;
   186     fun mkvar a = cterm_of thy (Var((a,0),ty));
   187 in
   188 fun xfun_cong x = Thm.instantiate ([], [(cx, mkvar x)]) fun_cong'
   189 end;
   190 
   191 (*Removes the lambdas from an equation of the form t = (%x. u).  A non-negative n,
   192   serves as an upper bound on how many to remove.*)
   193 fun strip_lambdas 0 th = th
   194   | strip_lambdas n th =
   195       case prop_of th of
   196           _ $ (Const (@{const_name "op ="}, _) $ _ $ Abs (x, _, _)) =>
   197               strip_lambdas (n-1) (freeze_thm (th RS xfun_cong x))
   198         | _ => th;
   199 
   200 fun is_quasi_lambda_free (Const (@{const_name skolem_id}, _) $ _) = true
   201   | is_quasi_lambda_free (t1 $ t2) =
   202     is_quasi_lambda_free t1 andalso is_quasi_lambda_free t2
   203   | is_quasi_lambda_free (Abs _) = false
   204   | is_quasi_lambda_free _ = true
   205 
   206 val [f_B,g_B] = map (cterm_of @{theory}) (OldTerm.term_vars (prop_of @{thm abs_B}));
   207 val [g_C,f_C] = map (cterm_of @{theory}) (OldTerm.term_vars (prop_of @{thm abs_C}));
   208 val [f_S,g_S] = map (cterm_of @{theory}) (OldTerm.term_vars (prop_of @{thm abs_S}));
   209 
   210 (*FIXME: requires more use of cterm constructors*)
   211 fun abstract ct =
   212   let
   213       val thy = theory_of_cterm ct
   214       val Abs(x,_,body) = term_of ct
   215       val Type(@{type_name fun}, [xT,bodyT]) = typ_of (ctyp_of_term ct)
   216       val cxT = ctyp_of thy xT and cbodyT = ctyp_of thy bodyT
   217       fun makeK() = instantiate' [SOME cxT, SOME cbodyT] [SOME (cterm_of thy body)] @{thm abs_K}
   218   in
   219       case body of
   220           Const _ => makeK()
   221         | Free _ => makeK()
   222         | Var _ => makeK()  (*though Var isn't expected*)
   223         | Bound 0 => instantiate' [SOME cxT] [] @{thm abs_I} (*identity: I*)
   224         | rator$rand =>
   225             if loose_bvar1 (rator,0) then (*C or S*)
   226                if loose_bvar1 (rand,0) then (*S*)
   227                  let val crator = cterm_of thy (Abs(x,xT,rator))
   228                      val crand = cterm_of thy (Abs(x,xT,rand))
   229                      val abs_S' = cterm_instantiate [(f_S,crator),(g_S,crand)] @{thm abs_S}
   230                      val (_,rhs) = Thm.dest_equals (cprop_of abs_S')
   231                  in
   232                    Thm.transitive abs_S' (Conv.binop_conv abstract rhs)
   233                  end
   234                else (*C*)
   235                  let val crator = cterm_of thy (Abs(x,xT,rator))
   236                      val abs_C' = cterm_instantiate [(f_C,crator),(g_C,cterm_of thy rand)] @{thm abs_C}
   237                      val (_,rhs) = Thm.dest_equals (cprop_of abs_C')
   238                  in
   239                    Thm.transitive abs_C' (Conv.fun_conv (Conv.arg_conv abstract) rhs)
   240                  end
   241             else if loose_bvar1 (rand,0) then (*B or eta*)
   242                if rand = Bound 0 then Thm.eta_conversion ct
   243                else (*B*)
   244                  let val crand = cterm_of thy (Abs(x,xT,rand))
   245                      val crator = cterm_of thy rator
   246                      val abs_B' = cterm_instantiate [(f_B,crator),(g_B,crand)] @{thm abs_B}
   247                      val (_,rhs) = Thm.dest_equals (cprop_of abs_B')
   248                  in Thm.transitive abs_B' (Conv.arg_conv abstract rhs) end
   249             else makeK()
   250         | _ => raise Fail "abstract: Bad term"
   251   end;
   252 
   253 (* Traverse a theorem, remplacing lambda-abstractions with combinators. *)
   254 fun do_introduce_combinators ct =
   255   if is_quasi_lambda_free (term_of ct) then
   256     Thm.reflexive ct
   257   else case term_of ct of
   258     Abs _ =>
   259     let
   260       val (cv, cta) = Thm.dest_abs NONE ct
   261       val (v, _) = dest_Free (term_of cv)
   262       val u_th = do_introduce_combinators cta
   263       val cu = Thm.rhs_of u_th
   264       val comb_eq = abstract (Thm.cabs cv cu)
   265     in Thm.transitive (Thm.abstract_rule v cv u_th) comb_eq end
   266   | _ $ _ =>
   267     let val (ct1, ct2) = Thm.dest_comb ct in
   268         Thm.combination (do_introduce_combinators ct1)
   269                         (do_introduce_combinators ct2)
   270     end
   271 
   272 fun introduce_combinators th =
   273   if is_quasi_lambda_free (prop_of th) then
   274     th
   275   else
   276     let
   277       val th = Drule.eta_contraction_rule th
   278       val eqth = do_introduce_combinators (cprop_of th)
   279     in Thm.equal_elim eqth th end
   280     handle THM (msg, _, _) =>
   281            (warning ("Error in the combinator translation of " ^
   282                      Display.string_of_thm_without_context th ^
   283                      "\nException message: " ^ msg ^ ".");
   284             (* A type variable of sort "{}" will make abstraction fail. *)
   285             TrueI)
   286 
   287 (*cterms are used throughout for efficiency*)
   288 val cTrueprop = Thm.cterm_of @{theory HOL} HOLogic.Trueprop;
   289 
   290 (*cterm version of mk_cTrueprop*)
   291 fun c_mkTrueprop A = Thm.capply cTrueprop A;
   292 
   293 (*Given an abstraction over n variables, replace the bound variables by free
   294   ones. Return the body, along with the list of free variables.*)
   295 fun c_variant_abs_multi (ct0, vars) =
   296       let val (cv,ct) = Thm.dest_abs NONE ct0
   297       in  c_variant_abs_multi (ct, cv::vars)  end
   298       handle CTERM _ => (ct0, rev vars);
   299 
   300 (*Given the definition of a Skolem function, return a theorem to replace
   301   an existential formula by a use of that function.
   302    Example: "EX x. x : A & x ~: B ==> sko A B : A & sko A B ~: B"  [.] *)
   303 fun skolem_theorem_of_def inline def =
   304   let
   305       val (c, rhs) = Thm.dest_equals (cprop_of (freeze_thm def))
   306       val rhs' = rhs |> inline ? (snd o Thm.dest_comb)
   307       val (ch, frees) = c_variant_abs_multi (rhs', [])
   308       val (chilbert, cabs) = ch |> Thm.dest_comb
   309       val thy = Thm.theory_of_cterm chilbert
   310       val t = Thm.term_of chilbert
   311       val T =
   312         case t of
   313           Const (@{const_name Eps}, Type (@{type_name fun}, [_, T])) => T
   314         | _ => raise TERM ("skolem_theorem_of_def: expected \"Eps\"", [t])
   315       val cex = Thm.cterm_of thy (HOLogic.exists_const T)
   316       val ex_tm = c_mkTrueprop (Thm.capply cex cabs)
   317       and conc =
   318         Drule.list_comb (if inline then rhs else c, frees)
   319         |> Drule.beta_conv cabs |> c_mkTrueprop
   320       fun tacf [prem] =
   321         (if inline then rewrite_goals_tac @{thms skolem_id_def_raw}
   322          else rewrite_goals_tac [def])
   323         THEN rtac ((prem |> inline ? rewrite_rule @{thms skolem_id_def_raw})
   324                    RS @{thm someI_ex}) 1
   325   in  Goal.prove_internal [ex_tm] conc tacf
   326        |> forall_intr_list frees
   327        |> Thm.forall_elim_vars 0  (*Introduce Vars, but don't discharge defs.*)
   328        |> Thm.varifyT_global
   329   end;
   330 
   331 
   332 (*Converts an Isabelle theorem (intro, elim or simp format, even higher-order) into NNF.*)
   333 fun to_nnf th ctxt0 =
   334   let val th1 = th |> transform_elim |> zero_var_indexes
   335       val ((_, [th2]), ctxt) = Variable.import true [th1] ctxt0
   336       val th3 = th2
   337         |> Conv.fconv_rule Object_Logic.atomize
   338         |> Meson.make_nnf ctxt |> strip_lambdas ~1
   339   in  (th3, ctxt)  end;
   340 
   341 (*Generate Skolem functions for a theorem supplied in nnf*)
   342 fun skolem_theorems_of_assume inline s th =
   343   map (skolem_theorem_of_def inline o Thm.assume o cterm_of (theory_of_thm th))
   344       (assume_skolem_funs inline s th)
   345 
   346 
   347 (*** Blacklisting (more in "Sledgehammer_Fact_Filter") ***)
   348 
   349 val max_lambda_nesting = 3
   350 
   351 fun term_has_too_many_lambdas max (t1 $ t2) =
   352     exists (term_has_too_many_lambdas max) [t1, t2]
   353   | term_has_too_many_lambdas max (Abs (_, _, t)) =
   354     max = 0 orelse term_has_too_many_lambdas (max - 1) t
   355   | term_has_too_many_lambdas _ _ = false
   356 
   357 fun is_formula_type T = (T = HOLogic.boolT orelse T = propT)
   358 
   359 (* Don't count nested lambdas at the level of formulas, since they are
   360    quantifiers. *)
   361 fun formula_has_too_many_lambdas Ts (Abs (_, T, t)) =
   362     formula_has_too_many_lambdas (T :: Ts) t
   363   | formula_has_too_many_lambdas Ts t =
   364     if is_formula_type (fastype_of1 (Ts, t)) then
   365       exists (formula_has_too_many_lambdas Ts) (#2 (strip_comb t))
   366     else
   367       term_has_too_many_lambdas max_lambda_nesting t
   368 
   369 (* The max apply depth of any "metis" call in "Metis_Examples" (on 31-10-2007)
   370    was 11. *)
   371 val max_apply_depth = 15
   372 
   373 fun apply_depth (f $ t) = Int.max (apply_depth f, apply_depth t + 1)
   374   | apply_depth (Abs (_, _, t)) = apply_depth t
   375   | apply_depth _ = 0
   376 
   377 fun is_formula_too_complex t =
   378   apply_depth t > max_apply_depth orelse Meson.too_many_clauses NONE t orelse
   379   formula_has_too_many_lambdas [] t
   380 
   381 fun is_strange_thm th =
   382   case head_of (concl_of th) of
   383       Const (a, _) => (a <> @{const_name Trueprop} andalso
   384                        a <> @{const_name "=="})
   385     | _ => false;
   386 
   387 fun is_theorem_bad_for_atps thm =
   388   let val t = prop_of thm in
   389     is_formula_too_complex t orelse exists_type type_has_topsort t orelse
   390     is_strange_thm thm
   391   end
   392 
   393 (* FIXME: put other record thms here, or declare as "no_atp" *)
   394 val multi_base_blacklist =
   395   ["defs", "select_defs", "update_defs", "induct", "inducts", "split", "splits",
   396    "split_asm", "cases", "ext_cases"];
   397 
   398 fun fake_name th =
   399   if Thm.has_name_hint th then flatten_name (Thm.get_name_hint th)
   400   else gensym "unknown_thm_";
   401 
   402 (*Skolemize a named theorem, with Skolem functions as additional premises.*)
   403 fun skolemize_theorem s th =
   404   if member (op =) multi_base_blacklist (Long_Name.base_name s) orelse
   405      is_theorem_bad_for_atps th then
   406     []
   407   else
   408     let
   409       val ctxt0 = Variable.global_thm_context th
   410       val (nnfth, ctxt) = to_nnf th ctxt0
   411       val inline = exists_type (exists_subtype (can dest_TFree)) (prop_of nnfth)
   412       val defs = skolem_theorems_of_assume inline s nnfth
   413       val (cnfs, ctxt) = Meson.make_cnf defs nnfth ctxt
   414     in
   415       cnfs |> map introduce_combinators
   416            |> Variable.export ctxt ctxt0
   417            |> Meson.finish_cnf
   418     end
   419     handle THM _ => []
   420 
   421 (*The cache prevents repeated clausification of a theorem, and also repeated declaration of
   422   Skolem functions.*)
   423 structure ThmCache = Theory_Data
   424 (
   425   type T = thm list Thmtab.table * unit Symtab.table;
   426   val empty = (Thmtab.empty, Symtab.empty);
   427   val extend = I;
   428   fun merge ((cache1, seen1), (cache2, seen2)) : T =
   429     (Thmtab.merge (K true) (cache1, cache2), Symtab.merge (K true) (seen1, seen2));
   430 );
   431 
   432 val lookup_cache = Thmtab.lookup o #1 o ThmCache.get;
   433 val already_seen = Symtab.defined o #2 o ThmCache.get;
   434 
   435 val update_cache = ThmCache.map o apfst o Thmtab.update;
   436 fun mark_seen name = ThmCache.map (apsnd (Symtab.update (name, ())));
   437 
   438 (* Convert Isabelle theorems into axiom clauses. *)
   439 fun cnf_axiom thy th0 =
   440   let val th = Thm.transfer thy th0 in
   441     case lookup_cache thy th of
   442       SOME cls => cls
   443     | NONE => map Thm.close_derivation (skolemize_theorem (fake_name th) th)
   444   end;
   445 
   446 
   447 (**** Translate a set of theorems into CNF ****)
   448 
   449 fun pair_name_cls _ (_, []) = []
   450   | pair_name_cls k (n, cls::clss) = (cls, (n,k)) :: pair_name_cls (k+1) (n, clss)
   451 
   452 (*The combination of rev and tail recursion preserves the original order*)
   453 fun cnf_rules_pairs thy =
   454   let
   455     fun aux pairs [] = pairs
   456       | aux pairs ((name, th) :: ths) =
   457         let
   458           val new_pairs = pair_name_cls 0 (name, cnf_axiom thy th)
   459                           handle THM _ => [] |
   460                                  CLAUSE _ => []
   461         in aux (new_pairs @ pairs) ths end
   462   in aux [] o rev end
   463 
   464 
   465 (**** Convert all facts of the theory into FOL or HOL clauses ****)
   466 
   467 local
   468 
   469 fun skolem_def (name, th) thy =
   470   let val ctxt0 = Variable.global_thm_context th in
   471     case try (to_nnf th) ctxt0 of
   472       NONE => (NONE, thy)
   473     | SOME (nnfth, ctxt) =>
   474       let val (defs, thy') = declare_skolem_funs (flatten_name name) nnfth thy
   475       in (SOME (th, ctxt0, ctxt, nnfth, defs), thy') end
   476   end;
   477 
   478 fun skolem_cnfs (th, ctxt0, ctxt, nnfth, defs) =
   479   let
   480     val (cnfs, ctxt) =
   481       Meson.make_cnf (map (skolem_theorem_of_def false) defs) nnfth ctxt
   482     val cnfs' = cnfs
   483       |> map introduce_combinators
   484       |> Variable.export ctxt ctxt0
   485       |> Meson.finish_cnf
   486       |> map Thm.close_derivation;
   487     in (th, cnfs') end;
   488 
   489 in
   490 
   491 fun saturate_skolem_cache thy =
   492   let
   493     val facts = PureThy.facts_of thy;
   494     val new_facts = (facts, []) |-> Facts.fold_static (fn (name, ths) =>
   495       if Facts.is_concealed facts name orelse already_seen thy name then I
   496       else cons (name, ths));
   497     val new_thms = (new_facts, []) |-> fold (fn (name, ths) =>
   498       if member (op =) multi_base_blacklist (Long_Name.base_name name) then
   499         I
   500       else
   501         fold_index (fn (i, th) =>
   502           if is_theorem_bad_for_atps th orelse
   503              is_some (lookup_cache thy th) then
   504             I
   505           else
   506             cons (name ^ "_" ^ string_of_int (i + 1), Thm.transfer thy th)) ths)
   507   in
   508     if null new_facts then
   509       NONE
   510     else
   511       let
   512         val (defs, thy') = thy
   513           |> fold (mark_seen o #1) new_facts
   514           |> fold_map skolem_def (sort_distinct (Thm.thm_ord o pairself snd) new_thms)
   515           |>> map_filter I;
   516         val cache_entries = Par_List.map skolem_cnfs defs;
   517       in SOME (fold update_cache cache_entries thy') end
   518   end;
   519 
   520 end;
   521 
   522 val auto_saturate_skolem_cache = Unsynchronized.ref true
   523 
   524 fun conditionally_saturate_skolem_cache thy =
   525   if !auto_saturate_skolem_cache then saturate_skolem_cache thy else NONE
   526 
   527 
   528 (*** Converting a subgoal into negated conjecture clauses. ***)
   529 
   530 fun neg_skolemize_tac ctxt =
   531   EVERY' [rtac ccontr, Object_Logic.atomize_prems_tac, Meson.skolemize_tac ctxt]
   532 
   533 val neg_clausify =
   534   single
   535   #> Meson.make_clauses_unsorted
   536   #> map introduce_combinators
   537   #> Meson.finish_cnf
   538 
   539 fun neg_conjecture_clauses ctxt st0 n =
   540   let
   541     (* "Option" is thrown if the assumptions contain schematic variables. *)
   542     val st = Seq.hd (neg_skolemize_tac ctxt n st0) handle Option.Option => st0
   543     val ({params, prems, ...}, _) =
   544       Subgoal.focus (Variable.set_body false ctxt) n st
   545   in (map neg_clausify prems, map (dest_Free o term_of o #2) params) end
   546 
   547 (*Conversion of a subgoal to conjecture clauses. Each clause has
   548   leading !!-bound universal variables, to express generality. *)
   549 fun neg_clausify_tac ctxt =
   550   neg_skolemize_tac ctxt THEN'
   551   SUBGOAL (fn (prop, i) =>
   552     let val ts = Logic.strip_assums_hyp prop in
   553       EVERY'
   554        [Subgoal.FOCUS
   555          (fn {prems, ...} =>
   556            (Method.insert_tac
   557              (map forall_intr_vars (maps neg_clausify prems)) i)) ctxt,
   558         REPEAT_DETERM_N (length ts) o etac thin_rl] i
   559      end);
   560 
   561 
   562 (** setup **)
   563 
   564 val setup =
   565   perhaps conditionally_saturate_skolem_cache
   566   #> Theory.at_end conditionally_saturate_skolem_cache
   567 
   568 end;