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