src/HOL/Tools/Meson/meson_clausify.ML
author blanchet
Mon Oct 04 21:49:07 2010 +0200 (2010-10-04)
changeset 39941 02fcd9cd1eac
parent 39940 1f01c9b2b76b
child 39948 317010af8972
permissions -rw-r--r--
move Meson to Plain
     1 (*  Title:      HOL/Tools/Meson/meson_clausify.ML
     2     Author:     Jia Meng, Cambridge University Computer Laboratory and NICTA
     3     Author:     Jasmin Blanchette, TU Muenchen
     4 
     5 Transformation of HOL theorems into CNF forms.
     6 The "meson" proof method for HOL.
     7 *)
     8 
     9 signature MESON_CLAUSIFY =
    10 sig
    11   val new_skolem_var_prefix : string
    12   val extensionalize_theorem : thm -> thm
    13   val introduce_combinators_in_cterm : cterm -> thm
    14   val introduce_combinators_in_theorem : thm -> thm
    15   val to_definitional_cnf_with_quantifiers : theory -> thm -> thm
    16   val cluster_of_zapped_var_name : string -> (int * (int * int)) * bool
    17   val cnf_axiom :
    18     Proof.context -> bool -> int -> thm -> (thm * term) option * thm list
    19   val meson_general_tac : Proof.context -> thm list -> int -> tactic
    20   val setup: theory -> theory
    21 end;
    22 
    23 structure Meson_Clausify : MESON_CLAUSIFY =
    24 struct
    25 
    26 (* the extra "?" helps prevent clashes *)
    27 val new_skolem_var_prefix = "?SK"
    28 val new_nonskolem_var_prefix = "?V"
    29 
    30 (**** Transformation of Elimination Rules into First-Order Formulas****)
    31 
    32 val cfalse = cterm_of @{theory HOL} HOLogic.false_const;
    33 val ctp_false = cterm_of @{theory HOL} (HOLogic.mk_Trueprop HOLogic.false_const);
    34 
    35 (* Converts an elim-rule into an equivalent theorem that does not have the
    36    predicate variable. Leaves other theorems unchanged. We simply instantiate
    37    the conclusion variable to False. (Cf. "transform_elim_term" in
    38    "Sledgehammer_Util".) *)
    39 fun transform_elim_theorem th =
    40   case concl_of th of    (*conclusion variable*)
    41        @{const Trueprop} $ (v as Var (_, @{typ bool})) =>
    42            Thm.instantiate ([], [(cterm_of @{theory HOL} v, cfalse)]) th
    43     | v as Var(_, @{typ prop}) =>
    44            Thm.instantiate ([], [(cterm_of @{theory HOL} v, ctp_false)]) th
    45     | _ => th
    46 
    47 
    48 (**** SKOLEMIZATION BY INFERENCE (lcp) ****)
    49 
    50 fun mk_old_skolem_term_wrapper t =
    51   let val T = fastype_of t in
    52     Const (@{const_name skolem}, T --> T) $ t
    53   end
    54 
    55 fun beta_eta_in_abs_body (Abs (s, T, t')) = Abs (s, T, beta_eta_in_abs_body t')
    56   | beta_eta_in_abs_body t = Envir.beta_eta_contract t
    57 
    58 (*Traverse a theorem, accumulating Skolem function definitions.*)
    59 fun old_skolem_defs th =
    60   let
    61     fun dec_sko (Const (@{const_name Ex}, _) $ (body as Abs (_, T, p))) rhss =
    62         (*Existential: declare a Skolem function, then insert into body and continue*)
    63         let
    64           val args = OldTerm.term_frees body
    65           (* Forms a lambda-abstraction over the formal parameters *)
    66           val rhs =
    67             list_abs_free (map dest_Free args,
    68                            HOLogic.choice_const T $ beta_eta_in_abs_body body)
    69             |> mk_old_skolem_term_wrapper
    70           val comb = list_comb (rhs, args)
    71         in dec_sko (subst_bound (comb, p)) (rhs :: rhss) end
    72       | dec_sko (Const (@{const_name All},_) $ Abs (a, T, p)) rhss =
    73         (*Universal quant: insert a free variable into body and continue*)
    74         let val fname = Name.variant (OldTerm.add_term_names (p,[])) a
    75         in dec_sko (subst_bound (Free(fname,T), p)) rhss end
    76       | dec_sko (@{const conj} $ p $ q) rhss = rhss |> dec_sko p |> dec_sko q
    77       | dec_sko (@{const disj} $ p $ q) rhss = rhss |> dec_sko p |> dec_sko q
    78       | dec_sko (@{const Trueprop} $ p) rhss = dec_sko p rhss
    79       | dec_sko _ rhss = rhss
    80   in  dec_sko (prop_of th) []  end;
    81 
    82 
    83 (**** REPLACING ABSTRACTIONS BY COMBINATORS ****)
    84 
    85 val fun_cong_all = @{thm fun_eq_iff [THEN iffD1]}
    86 
    87 (* Removes the lambdas from an equation of the form "t = (%x. u)".
    88    (Cf. "extensionalize_term" in "Sledgehammer_Translate".) *)
    89 fun extensionalize_theorem th =
    90   case prop_of th of
    91     _ $ (Const (@{const_name HOL.eq}, Type (_, [Type (@{type_name fun}, _), _]))
    92          $ _ $ Abs _) => extensionalize_theorem (th RS fun_cong_all)
    93   | _ => th
    94 
    95 fun is_quasi_lambda_free (Const (@{const_name skolem}, _) $ _) = true
    96   | is_quasi_lambda_free (t1 $ t2) =
    97     is_quasi_lambda_free t1 andalso is_quasi_lambda_free t2
    98   | is_quasi_lambda_free (Abs _) = false
    99   | is_quasi_lambda_free _ = true
   100 
   101 val [f_B,g_B] = map (cterm_of @{theory}) (OldTerm.term_vars (prop_of @{thm abs_B}));
   102 val [g_C,f_C] = map (cterm_of @{theory}) (OldTerm.term_vars (prop_of @{thm abs_C}));
   103 val [f_S,g_S] = map (cterm_of @{theory}) (OldTerm.term_vars (prop_of @{thm abs_S}));
   104 
   105 (* FIXME: Requires more use of cterm constructors. *)
   106 fun abstract ct =
   107   let
   108       val thy = theory_of_cterm ct
   109       val Abs(x,_,body) = term_of ct
   110       val Type(@{type_name fun}, [xT,bodyT]) = typ_of (ctyp_of_term ct)
   111       val cxT = ctyp_of thy xT
   112       val cbodyT = ctyp_of thy bodyT
   113       fun makeK () =
   114         instantiate' [SOME cxT, SOME cbodyT] [SOME (cterm_of thy body)]
   115                      @{thm abs_K}
   116   in
   117       case body of
   118           Const _ => makeK()
   119         | Free _ => makeK()
   120         | Var _ => makeK()  (*though Var isn't expected*)
   121         | Bound 0 => instantiate' [SOME cxT] [] @{thm abs_I} (*identity: I*)
   122         | rator$rand =>
   123             if loose_bvar1 (rator,0) then (*C or S*)
   124                if loose_bvar1 (rand,0) then (*S*)
   125                  let val crator = cterm_of thy (Abs(x,xT,rator))
   126                      val crand = cterm_of thy (Abs(x,xT,rand))
   127                      val abs_S' = cterm_instantiate [(f_S,crator),(g_S,crand)] @{thm abs_S}
   128                      val (_,rhs) = Thm.dest_equals (cprop_of abs_S')
   129                  in
   130                    Thm.transitive abs_S' (Conv.binop_conv abstract rhs)
   131                  end
   132                else (*C*)
   133                  let val crator = cterm_of thy (Abs(x,xT,rator))
   134                      val abs_C' = cterm_instantiate [(f_C,crator),(g_C,cterm_of thy rand)] @{thm abs_C}
   135                      val (_,rhs) = Thm.dest_equals (cprop_of abs_C')
   136                  in
   137                    Thm.transitive abs_C' (Conv.fun_conv (Conv.arg_conv abstract) rhs)
   138                  end
   139             else if loose_bvar1 (rand,0) then (*B or eta*)
   140                if rand = Bound 0 then Thm.eta_conversion ct
   141                else (*B*)
   142                  let val crand = cterm_of thy (Abs(x,xT,rand))
   143                      val crator = cterm_of thy rator
   144                      val abs_B' = cterm_instantiate [(f_B,crator),(g_B,crand)] @{thm abs_B}
   145                      val (_,rhs) = Thm.dest_equals (cprop_of abs_B')
   146                  in Thm.transitive abs_B' (Conv.arg_conv abstract rhs) end
   147             else makeK()
   148         | _ => raise Fail "abstract: Bad term"
   149   end;
   150 
   151 (* Traverse a theorem, remplacing lambda-abstractions with combinators. *)
   152 fun introduce_combinators_in_cterm ct =
   153   if is_quasi_lambda_free (term_of ct) then
   154     Thm.reflexive ct
   155   else case term_of ct of
   156     Abs _ =>
   157     let
   158       val (cv, cta) = Thm.dest_abs NONE ct
   159       val (v, _) = dest_Free (term_of cv)
   160       val u_th = introduce_combinators_in_cterm cta
   161       val cu = Thm.rhs_of u_th
   162       val comb_eq = abstract (Thm.cabs cv cu)
   163     in Thm.transitive (Thm.abstract_rule v cv u_th) comb_eq end
   164   | _ $ _ =>
   165     let val (ct1, ct2) = Thm.dest_comb ct in
   166         Thm.combination (introduce_combinators_in_cterm ct1)
   167                         (introduce_combinators_in_cterm ct2)
   168     end
   169 
   170 fun introduce_combinators_in_theorem th =
   171   if is_quasi_lambda_free (prop_of th) then
   172     th
   173   else
   174     let
   175       val th = Drule.eta_contraction_rule th
   176       val eqth = introduce_combinators_in_cterm (cprop_of th)
   177     in Thm.equal_elim eqth th end
   178     handle THM (msg, _, _) =>
   179            (warning ("Error in the combinator translation of " ^
   180                      Display.string_of_thm_without_context th ^
   181                      "\nException message: " ^ msg ^ ".");
   182             (* A type variable of sort "{}" will make abstraction fail. *)
   183             TrueI)
   184 
   185 (*cterms are used throughout for efficiency*)
   186 val cTrueprop = cterm_of @{theory HOL} HOLogic.Trueprop;
   187 
   188 (*Given an abstraction over n variables, replace the bound variables by free
   189   ones. Return the body, along with the list of free variables.*)
   190 fun c_variant_abs_multi (ct0, vars) =
   191       let val (cv,ct) = Thm.dest_abs NONE ct0
   192       in  c_variant_abs_multi (ct, cv::vars)  end
   193       handle CTERM _ => (ct0, rev vars);
   194 
   195 val skolem_def_raw = @{thms skolem_def_raw}
   196 
   197 (* Given the definition of a Skolem function, return a theorem to replace
   198    an existential formula by a use of that function.
   199    Example: "EX x. x : A & x ~: B ==> sko A B : A & sko A B ~: B"  [.] *)
   200 fun old_skolem_theorem_from_def thy rhs0 =
   201   let
   202     val rhs = rhs0 |> Type.legacy_freeze_thaw |> #1 |> cterm_of thy
   203     val rhs' = rhs |> Thm.dest_comb |> snd
   204     val (ch, frees) = c_variant_abs_multi (rhs', [])
   205     val (hilbert, cabs) = ch |> Thm.dest_comb |>> term_of
   206     val T =
   207       case hilbert of
   208         Const (_, Type (@{type_name fun}, [_, T])) => T
   209       | _ => raise TERM ("old_skolem_theorem_from_def: expected \"Eps\"",
   210                          [hilbert])
   211     val cex = cterm_of thy (HOLogic.exists_const T)
   212     val ex_tm = Thm.capply cTrueprop (Thm.capply cex cabs)
   213     val conc =
   214       Drule.list_comb (rhs, frees)
   215       |> Drule.beta_conv cabs |> Thm.capply cTrueprop
   216     fun tacf [prem] =
   217       rewrite_goals_tac skolem_def_raw
   218       THEN rtac ((prem |> rewrite_rule skolem_def_raw)
   219                  RS Global_Theory.get_thm thy "someI_ex") 1
   220   in
   221     Goal.prove_internal [ex_tm] conc tacf
   222     |> forall_intr_list frees
   223     |> Thm.forall_elim_vars 0  (*Introduce Vars, but don't discharge defs.*)
   224     |> Thm.varifyT_global
   225   end
   226 
   227 fun to_definitional_cnf_with_quantifiers thy th =
   228   let
   229     val eqth = cnf.make_cnfx_thm thy (HOLogic.dest_Trueprop (prop_of th))
   230     val eqth = eqth RS @{thm eq_reflection}
   231     val eqth = eqth RS @{thm TruepropI}
   232   in Thm.equal_elim eqth th end
   233 
   234 fun zapped_var_name ((ax_no, cluster_no), skolem) index_no s =
   235   (if skolem then new_skolem_var_prefix else new_nonskolem_var_prefix) ^
   236   "_" ^ string_of_int ax_no ^ "_" ^ string_of_int cluster_no ^ "_" ^
   237   string_of_int index_no ^ "_" ^ s
   238 
   239 fun cluster_of_zapped_var_name s =
   240   let val get_int = the o Int.fromString o nth (space_explode "_" s) in
   241     ((get_int 1, (get_int 2, get_int 3)),
   242      String.isPrefix new_skolem_var_prefix s)
   243   end
   244 
   245 fun zap (cluster as (cluster_no, cluster_skolem)) index_no pos ct =
   246   ct
   247   |> (case term_of ct of
   248         Const (s, _) $ Abs (s', _, _) =>
   249         if s = @{const_name all} orelse s = @{const_name All} orelse
   250            s = @{const_name Ex} then
   251           let
   252             val skolem = (pos = (s = @{const_name Ex}))
   253             val (cluster, index_no) =
   254               if skolem = cluster_skolem then (cluster, index_no)
   255               else ((cluster_no ||> cluster_skolem ? Integer.add 1, skolem), 0)
   256           in
   257             Thm.dest_comb #> snd
   258             #> Thm.dest_abs (SOME (zapped_var_name cluster index_no s'))
   259             #> snd #> zap cluster (index_no + 1) pos
   260           end
   261         else
   262           Conv.all_conv
   263       | Const (s, _) $ _ $ _ =>
   264         if s = @{const_name "==>"} orelse s = @{const_name implies} then
   265           Conv.combination_conv (Conv.arg_conv (zap cluster index_no (not pos)))
   266                                 (zap cluster index_no pos)
   267         else if s = @{const_name conj} orelse s = @{const_name disj} then
   268           Conv.combination_conv (Conv.arg_conv (zap cluster index_no pos))
   269                                 (zap cluster index_no pos)
   270         else
   271           Conv.all_conv
   272       | Const (s, _) $ _ =>
   273         if s = @{const_name Trueprop} then
   274           Conv.arg_conv (zap cluster index_no pos)
   275         else if s = @{const_name Not} then
   276           Conv.arg_conv (zap cluster index_no (not pos))
   277         else
   278           Conv.all_conv
   279       | _ => Conv.all_conv)
   280 
   281 fun ss_only ths = MetaSimplifier.clear_ss HOL_basic_ss addsimps ths
   282 
   283 val no_choice =
   284   @{prop "ALL x. EX y. Q x y ==> EX f. ALL x. Q x (f x)"}
   285   |> Logic.varify_global
   286   |> Skip_Proof.make_thm @{theory}
   287 
   288 (* Converts an Isabelle theorem into NNF. *)
   289 fun nnf_axiom choice_ths new_skolemizer ax_no th ctxt =
   290   let
   291     val thy = ProofContext.theory_of ctxt
   292     val th =
   293       th |> transform_elim_theorem
   294          |> zero_var_indexes
   295          |> new_skolemizer ? forall_intr_vars
   296     val (th, ctxt) = Variable.import true [th] ctxt |>> snd |>> the_single
   297     val th = th |> Conv.fconv_rule Object_Logic.atomize
   298                 |> extensionalize_theorem
   299                 |> Meson.make_nnf ctxt
   300   in
   301     if new_skolemizer then
   302       let
   303         fun skolemize choice_ths =
   304           Meson.skolemize_with_choice_thms ctxt choice_ths
   305           #> simplify (ss_only @{thms all_simps[symmetric]})
   306         val pull_out =
   307           simplify (ss_only @{thms all_simps[symmetric] ex_simps[symmetric]})
   308         val (discharger_th, fully_skolemized_th) =
   309           if null choice_ths then
   310             th |> `I |>> pull_out ||> skolemize [no_choice]
   311           else
   312             th |> skolemize choice_ths |> `I
   313         val t =
   314           fully_skolemized_th |> cprop_of
   315           |> zap ((ax_no, 0), true) 0 true |> Drule.export_without_context
   316           |> cprop_of |> Thm.dest_equals |> snd |> term_of
   317       in
   318         if exists_subterm (fn Var ((s, _), _) =>
   319                               String.isPrefix new_skolem_var_prefix s
   320                             | _ => false) t then
   321           let
   322             val (ct, ctxt) =
   323               Variable.import_terms true [t] ctxt
   324               |>> the_single |>> cterm_of thy
   325           in (SOME (discharger_th, ct), Thm.assume ct, ctxt) end
   326        else
   327          (NONE, th, ctxt)
   328       end
   329     else
   330       (NONE, th, ctxt)
   331   end
   332 
   333 (* Convert a theorem to CNF, with additional premises due to skolemization. *)
   334 fun cnf_axiom ctxt0 new_skolemizer ax_no th =
   335   let
   336     val thy = ProofContext.theory_of ctxt0
   337     val choice_ths = Meson_Choices.get ctxt0
   338     val (opt, nnf_th, ctxt) = nnf_axiom choice_ths new_skolemizer ax_no th ctxt0
   339     fun clausify th =
   340       Meson.make_cnf (if new_skolemizer then
   341                         []
   342                       else
   343                         map (old_skolem_theorem_from_def thy)
   344                             (old_skolem_defs th)) th ctxt
   345     val (cnf_ths, ctxt) =
   346       clausify nnf_th
   347       |> (fn ([], _) =>
   348              clausify (to_definitional_cnf_with_quantifiers thy nnf_th)
   349            | p => p)
   350     fun intr_imp ct th =
   351       Thm.instantiate ([], map (pairself (cterm_of @{theory}))
   352                                [(Var (("i", 1), @{typ nat}),
   353                                  HOLogic.mk_nat ax_no)])
   354                       @{thm skolem_COMBK_D}
   355       RS Thm.implies_intr ct th
   356   in
   357     (opt |> Option.map (I #>> singleton (Variable.export ctxt ctxt0)
   358                         ##> (term_of #> HOLogic.dest_Trueprop
   359                              #> singleton (Variable.export_terms ctxt ctxt0))),
   360      cnf_ths |> map (introduce_combinators_in_theorem
   361                      #> (case opt of SOME (_, ct) => intr_imp ct | NONE => I))
   362              |> Variable.export ctxt ctxt0
   363              |> Meson.finish_cnf
   364              |> map Thm.close_derivation)
   365   end
   366   handle THM _ => (NONE, [])
   367 
   368 fun meson_general_tac ctxt ths =
   369   let val ctxt = Classical.put_claset HOL_cs ctxt in
   370     Meson.meson_tac ctxt (maps (snd o cnf_axiom ctxt false 0) ths)
   371   end
   372 
   373 val setup =
   374   Method.setup @{binding meson} (Attrib.thms >> (fn ths => fn ctxt =>
   375      SIMPLE_METHOD' (CHANGED_PROP o meson_general_tac ctxt ths)))
   376      "MESON resolution proof procedure"
   377 
   378 end;