src/HOL/Tools/Meson/meson_clausify.ML
author blanchet
Tue Nov 15 22:13:39 2011 +0100 (2011-11-15)
changeset 45511 9b0f8ca4388e
parent 45508 b216dc1b3630
child 45740 132a3e1c0fe5
permissions -rw-r--r--
continued implementation of lambda-lifting in Metis
     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 : thm -> thm
    16   val cluster_of_zapped_var_name : string -> (int * (int * int)) * bool
    17   val ss_only : thm list -> simpset
    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 = cterm_of @{theory HOL} HOLogic.false_const;
    39 val ctp_false = cterm_of @{theory HOL} (HOLogic.mk_Trueprop HOLogic.false_const);
    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 concl_of th of    (*conclusion variable*)
    47        @{const Trueprop} $ (v as Var (_, @{typ bool})) =>
    48            Thm.instantiate ([], [(cterm_of @{theory HOL} v, cfalse)]) th
    49     | v as Var(_, @{typ prop}) =>
    50            Thm.instantiate ([], [(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 (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 (cterm_of @{theory}) (Misc_Legacy.term_vars (prop_of @{thm abs_B}));
    98 val [g_C,f_C] = map (cterm_of @{theory}) (Misc_Legacy.term_vars (prop_of @{thm abs_C}));
    99 val [f_S,g_S] = map (cterm_of @{theory}) (Misc_Legacy.term_vars (prop_of @{thm abs_S}));
   100 
   101 (* FIXME: Requires more use of cterm constructors. *)
   102 fun abstract ct =
   103   let
   104       val thy = theory_of_cterm ct
   105       val Abs(x,_,body) = term_of ct
   106       val Type(@{type_name fun}, [xT,bodyT]) = typ_of (ctyp_of_term ct)
   107       val cxT = ctyp_of thy xT
   108       val cbodyT = ctyp_of thy bodyT
   109       fun makeK () =
   110         instantiate' [SOME cxT, SOME cbodyT] [SOME (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 = cterm_of thy (Abs(x,xT,rator))
   122                      val crand = 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 (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 = cterm_of thy (Abs(x,xT,rator))
   130                      val abs_C' = cterm_instantiate [(f_C,crator),(g_C,cterm_of thy rand)] @{thm abs_C}
   131                      val (_,rhs) = Thm.dest_equals (cprop_of abs_C')
   132                  in
   133                    Thm.transitive abs_C' (Conv.fun_conv (Conv.arg_conv abstract) rhs)
   134                  end
   135             else if Term.is_dependent rand then (*B or eta*)
   136                if rand = Bound 0 then Thm.eta_conversion ct
   137                else (*B*)
   138                  let val crand = cterm_of thy (Abs(x,xT,rand))
   139                      val crator = cterm_of thy rator
   140                      val abs_B' = cterm_instantiate [(f_B,crator),(g_B,crand)] @{thm abs_B}
   141                      val (_,rhs) = Thm.dest_equals (cprop_of abs_B')
   142                  in Thm.transitive abs_B' (Conv.arg_conv abstract rhs) end
   143             else makeK()
   144         | _ => raise Fail "abstract: Bad term"
   145   end;
   146 
   147 (* Traverse a theorem, remplacing lambda-abstractions with combinators. *)
   148 fun introduce_combinators_in_cterm ct =
   149   if is_quasi_lambda_free (term_of ct) then
   150     Thm.reflexive ct
   151   else case term_of ct of
   152     Abs _ =>
   153     let
   154       val (cv, cta) = Thm.dest_abs NONE ct
   155       val (v, _) = dest_Free (term_of cv)
   156       val u_th = introduce_combinators_in_cterm cta
   157       val cu = Thm.rhs_of u_th
   158       val comb_eq = abstract (Thm.cabs cv cu)
   159     in Thm.transitive (Thm.abstract_rule v cv u_th) comb_eq end
   160   | _ $ _ =>
   161     let val (ct1, ct2) = Thm.dest_comb ct in
   162         Thm.combination (introduce_combinators_in_cterm ct1)
   163                         (introduce_combinators_in_cterm ct2)
   164     end
   165 
   166 fun introduce_combinators_in_theorem th =
   167   if is_quasi_lambda_free (prop_of th) then
   168     th
   169   else
   170     let
   171       val th = Drule.eta_contraction_rule th
   172       val eqth = introduce_combinators_in_cterm (cprop_of th)
   173     in Thm.equal_elim eqth th end
   174     handle THM (msg, _, _) =>
   175            (warning ("Error in the combinator translation of " ^
   176                      Display.string_of_thm_without_context 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 = 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 val skolem_def_raw = @{thms skolem_def_raw}
   192 
   193 (* Given the definition of a Skolem function, return a theorem to replace
   194    an existential formula by a use of that function.
   195    Example: "EX x. x : A & x ~: B ==> sko A B : A & sko A B ~: B"  [.] *)
   196 fun old_skolem_theorem_from_def thy rhs0 =
   197   let
   198     val rhs = rhs0 |> Type.legacy_freeze_thaw |> #1 |> cterm_of thy
   199     val rhs' = rhs |> Thm.dest_comb |> snd
   200     val (ch, frees) = c_variant_abs_multi (rhs', [])
   201     val (hilbert, cabs) = ch |> Thm.dest_comb |>> term_of
   202     val T =
   203       case hilbert of
   204         Const (_, Type (@{type_name fun}, [_, T])) => T
   205       | _ => raise TERM ("old_skolem_theorem_from_def: expected \"Eps\"",
   206                          [hilbert])
   207     val cex = cterm_of thy (HOLogic.exists_const T)
   208     val ex_tm = Thm.capply cTrueprop (Thm.capply cex cabs)
   209     val conc =
   210       Drule.list_comb (rhs, frees)
   211       |> Drule.beta_conv cabs |> Thm.capply cTrueprop
   212     fun tacf [prem] =
   213       rewrite_goals_tac skolem_def_raw
   214       THEN rtac ((prem |> rewrite_rule skolem_def_raw)
   215                  RS Global_Theory.get_thm thy "Hilbert_Choice.someI_ex") 1
   216   in
   217     Goal.prove_internal [ex_tm] conc tacf
   218     |> forall_intr_list frees
   219     |> Thm.forall_elim_vars 0  (*Introduce Vars, but don't discharge defs.*)
   220     |> Thm.varifyT_global
   221   end
   222 
   223 fun to_definitional_cnf_with_quantifiers ctxt th =
   224   let
   225     val eqth = cnf.make_cnfx_thm ctxt (HOLogic.dest_Trueprop (prop_of th))
   226     val eqth = eqth RS @{thm eq_reflection}
   227     val eqth = eqth RS @{thm TruepropI}
   228   in Thm.equal_elim eqth th end
   229 
   230 fun zapped_var_name ((ax_no, cluster_no), skolem) index_no s =
   231   (if skolem then new_skolem_var_prefix else new_nonskolem_var_prefix) ^
   232   "_" ^ string_of_int ax_no ^ "_" ^ string_of_int cluster_no ^ "_" ^
   233   string_of_int index_no ^ "_" ^ Name.desymbolize false s
   234 
   235 fun cluster_of_zapped_var_name s =
   236   let val get_int = the o Int.fromString o nth (space_explode "_" s) in
   237     ((get_int 1, (get_int 2, get_int 3)),
   238      String.isPrefix new_skolem_var_prefix s)
   239   end
   240 
   241 fun rename_bound_vars_to_be_zapped ax_no =
   242   let
   243     fun aux (cluster as (cluster_no, cluster_skolem)) index_no pos t =
   244       case t of
   245         (t1 as Const (s, _)) $ Abs (s', T, t') =>
   246         if s = @{const_name all} orelse s = @{const_name All} orelse
   247            s = @{const_name Ex} then
   248           let
   249             val skolem = (pos = (s = @{const_name Ex}))
   250             val (cluster, index_no) =
   251               if skolem = cluster_skolem then (cluster, index_no)
   252               else ((cluster_no ||> cluster_skolem ? Integer.add 1, skolem), 0)
   253             val s' = zapped_var_name cluster index_no s'
   254           in t1 $ Abs (s', T, aux cluster (index_no + 1) pos t') end
   255         else
   256           t
   257       | (t1 as Const (s, _)) $ t2 $ t3 =>
   258         if s = @{const_name "==>"} orelse s = @{const_name HOL.implies} then
   259           t1 $ aux cluster index_no (not pos) t2 $ aux cluster index_no pos t3
   260         else if s = @{const_name HOL.conj} orelse
   261                 s = @{const_name HOL.disj} then
   262           t1 $ aux cluster index_no pos t2 $ aux cluster index_no pos t3
   263         else
   264           t
   265       | (t1 as Const (s, _)) $ t2 =>
   266         if s = @{const_name Trueprop} then
   267           t1 $ aux cluster index_no pos t2
   268         else if s = @{const_name Not} then
   269           t1 $ aux cluster index_no (not pos) t2
   270         else
   271           t
   272       | _ => t
   273   in aux ((ax_no, 0), true) 0 true end
   274 
   275 fun zap pos ct =
   276   ct
   277   |> (case term_of ct of
   278         Const (s, _) $ Abs (s', _, _) =>
   279         if s = @{const_name all} orelse s = @{const_name All} orelse
   280            s = @{const_name Ex} then
   281           Thm.dest_comb #> snd #> Thm.dest_abs (SOME s') #> snd #> zap pos
   282         else
   283           Conv.all_conv
   284       | Const (s, _) $ _ $ _ =>
   285         if s = @{const_name "==>"} orelse s = @{const_name implies} then
   286           Conv.combination_conv (Conv.arg_conv (zap (not pos))) (zap pos)
   287         else if s = @{const_name conj} orelse s = @{const_name disj} then
   288           Conv.combination_conv (Conv.arg_conv (zap pos)) (zap pos)
   289         else
   290           Conv.all_conv
   291       | Const (s, _) $ _ =>
   292         if s = @{const_name Trueprop} then Conv.arg_conv (zap pos)
   293         else if s = @{const_name Not} then Conv.arg_conv (zap (not pos))
   294         else Conv.all_conv
   295       | _ => Conv.all_conv)
   296 
   297 fun ss_only ths = Simplifier.clear_ss HOL_basic_ss addsimps ths
   298 
   299 val cheat_choice =
   300   @{prop "ALL x. EX y. Q x y ==> EX f. ALL x. Q x (f x)"}
   301   |> Logic.varify_global
   302   |> Skip_Proof.make_thm @{theory}
   303 
   304 (* Converts an Isabelle theorem into NNF. *)
   305 fun nnf_axiom choice_ths new_skolemizer ax_no th ctxt =
   306   let
   307     val thy = Proof_Context.theory_of ctxt
   308     val th =
   309       th |> transform_elim_theorem
   310          |> zero_var_indexes
   311          |> new_skolemizer ? forall_intr_vars
   312     val (th, ctxt) = Variable.import true [th] ctxt |>> snd |>> the_single
   313     val th = th |> Conv.fconv_rule Object_Logic.atomize
   314                 |> Raw_Simplifier.rewrite_rule (unfold_set_const_simps ctxt)
   315                 |> extensionalize_theorem ctxt
   316                 |> make_nnf ctxt
   317   in
   318     if new_skolemizer then
   319       let
   320         fun skolemize choice_ths =
   321           skolemize_with_choice_theorems ctxt choice_ths
   322           #> simplify (ss_only @{thms all_simps[symmetric]})
   323         val no_choice = null choice_ths
   324         val pull_out =
   325           if no_choice then
   326             simplify (ss_only @{thms all_simps[symmetric] ex_simps[symmetric]})
   327           else
   328             skolemize choice_ths
   329         val discharger_th = th |> pull_out
   330         val discharger_th =
   331           discharger_th |> has_too_many_clauses ctxt (concl_of discharger_th)
   332                            ? (to_definitional_cnf_with_quantifiers ctxt
   333                               #> pull_out)
   334         val zapped_th =
   335           discharger_th |> prop_of |> rename_bound_vars_to_be_zapped ax_no
   336           |> (if no_choice then
   337                 Skip_Proof.make_thm thy #> skolemize [cheat_choice] #> cprop_of
   338               else
   339                 cterm_of thy)
   340           |> zap true
   341         val fixes =
   342           [] |> Term.add_free_names (prop_of zapped_th)
   343              |> filter is_zapped_var_name
   344         val ctxt' = ctxt |> Variable.add_fixes_direct fixes
   345         val fully_skolemized_t =
   346           zapped_th |> singleton (Variable.export ctxt' ctxt)
   347                     |> cprop_of |> Thm.dest_equals |> snd |> term_of
   348       in
   349         if exists_subterm (fn Var ((s, _), _) =>
   350                               String.isPrefix new_skolem_var_prefix s
   351                             | _ => false) fully_skolemized_t then
   352           let
   353             val (fully_skolemized_ct, ctxt) =
   354               Variable.import_terms true [fully_skolemized_t] ctxt
   355               |>> the_single |>> cterm_of thy
   356           in
   357             (SOME (discharger_th, fully_skolemized_ct),
   358              (Thm.assume fully_skolemized_ct, ctxt))
   359           end
   360        else
   361          (NONE, (th, ctxt))
   362       end
   363     else
   364       (NONE, (th |> has_too_many_clauses ctxt (concl_of th)
   365                     ? to_definitional_cnf_with_quantifiers ctxt, ctxt))
   366   end
   367 
   368 (* Convert a theorem to CNF, with additional premises due to skolemization. *)
   369 fun cnf_axiom ctxt0 new_skolemizer combinators ax_no th =
   370   let
   371     val thy = Proof_Context.theory_of ctxt0
   372     val choice_ths = choice_theorems thy
   373     val (opt, (nnf_th, ctxt)) =
   374       nnf_axiom choice_ths new_skolemizer ax_no th ctxt0
   375     fun clausify th =
   376       make_cnf (if new_skolemizer orelse null choice_ths then []
   377                 else map (old_skolem_theorem_from_def thy) (old_skolem_defs th))
   378                th ctxt ctxt
   379     val (cnf_ths, ctxt) = clausify nnf_th
   380     fun intr_imp ct th =
   381       Thm.instantiate ([], map (pairself (cterm_of thy))
   382                                [(Var (("i", 0), @{typ nat}),
   383                                  HOLogic.mk_nat ax_no)])
   384                       (zero_var_indexes @{thm skolem_COMBK_D})
   385       RS Thm.implies_intr ct th
   386   in
   387     (opt |> Option.map (I #>> singleton (Variable.export ctxt ctxt0)
   388                         ##> (term_of #> HOLogic.dest_Trueprop
   389                              #> singleton (Variable.export_terms ctxt ctxt0))),
   390      cnf_ths |> map (combinators ? introduce_combinators_in_theorem
   391                      #> (case opt of SOME (_, ct) => intr_imp ct | NONE => I))
   392              |> Variable.export ctxt ctxt0
   393              |> finish_cnf
   394              |> map Thm.close_derivation)
   395   end
   396   handle THM _ => (NONE, [])
   397 
   398 end;