src/HOL/Tools/Meson/meson.ML
author blanchet
Mon Jul 25 14:10:12 2011 +0200 (2011-07-25)
changeset 43964 9338aa218f09
parent 43821 048619bb1dc3
child 45567 8e3891309a8e
permissions -rw-r--r--
thread proper context through, to make sure that "using [[meson_max_clauses = 200]]" is not ignored when clausifying the conjecture
     1 (*  Title:      HOL/Tools/Meson/meson.ML
     2     Author:     Lawrence C Paulson, Cambridge University Computer Laboratory
     3     Author:     Jasmin Blanchette, TU Muenchen
     4 
     5 The MESON resolution proof procedure for HOL.
     6 When making clauses, avoids using the rewriter -- instead uses RS recursively.
     7 *)
     8 
     9 signature MESON =
    10 sig
    11   val trace : bool Config.T
    12   val unfold_set_consts : bool Config.T
    13   val max_clauses : int Config.T
    14   val term_pair_of: indexname * (typ * 'a) -> term * 'a
    15   val size_of_subgoals: thm -> int
    16   val has_too_many_clauses: Proof.context -> term -> bool
    17   val make_cnf:
    18     thm list -> thm -> Proof.context
    19     -> Proof.context -> thm list * Proof.context
    20   val finish_cnf: thm list -> thm list
    21   val unfold_set_const_simps : Proof.context -> thm list
    22   val presimplified_consts : Proof.context -> string list
    23   val presimplify: Proof.context -> thm -> thm
    24   val make_nnf: Proof.context -> thm -> thm
    25   val choice_theorems : theory -> thm list
    26   val skolemize_with_choice_theorems : Proof.context -> thm list -> thm -> thm
    27   val skolemize : Proof.context -> thm -> thm
    28   val extensionalize_conv : Proof.context -> conv
    29   val extensionalize_theorem : Proof.context -> thm -> thm
    30   val is_fol_term: theory -> term -> bool
    31   val make_clauses_unsorted: Proof.context -> thm list -> thm list
    32   val make_clauses: Proof.context -> thm list -> thm list
    33   val make_horns: thm list -> thm list
    34   val best_prolog_tac: (thm -> int) -> thm list -> tactic
    35   val depth_prolog_tac: thm list -> tactic
    36   val gocls: thm list -> thm list
    37   val skolemize_prems_tac : Proof.context -> thm list -> int -> tactic
    38   val MESON:
    39     tactic -> (thm list -> thm list) -> (thm list -> tactic) -> Proof.context
    40     -> int -> tactic
    41   val best_meson_tac: (thm -> int) -> Proof.context -> int -> tactic
    42   val safe_best_meson_tac: Proof.context -> int -> tactic
    43   val depth_meson_tac: Proof.context -> int -> tactic
    44   val prolog_step_tac': thm list -> int -> tactic
    45   val iter_deepen_prolog_tac: thm list -> tactic
    46   val iter_deepen_meson_tac: Proof.context -> thm list -> int -> tactic
    47   val make_meta_clause: thm -> thm
    48   val make_meta_clauses: thm list -> thm list
    49   val meson_tac: Proof.context -> thm list -> int -> tactic
    50 end
    51 
    52 structure Meson : MESON =
    53 struct
    54 
    55 val trace = Attrib.setup_config_bool @{binding meson_trace} (K false)
    56 
    57 fun trace_msg ctxt msg = if Config.get ctxt trace then tracing (msg ()) else ()
    58 
    59 val unfold_set_consts =
    60   Attrib.setup_config_bool @{binding meson_unfold_set_consts} (K false)
    61 
    62 val max_clauses = Attrib.setup_config_int @{binding meson_max_clauses} (K 60)
    63 
    64 (*No known example (on 1-5-2007) needs even thirty*)
    65 val iter_deepen_limit = 50;
    66 
    67 val disj_forward = @{thm disj_forward};
    68 val disj_forward2 = @{thm disj_forward2};
    69 val make_pos_rule = @{thm make_pos_rule};
    70 val make_pos_rule' = @{thm make_pos_rule'};
    71 val make_pos_goal = @{thm make_pos_goal};
    72 val make_neg_rule = @{thm make_neg_rule};
    73 val make_neg_rule' = @{thm make_neg_rule'};
    74 val make_neg_goal = @{thm make_neg_goal};
    75 val conj_forward = @{thm conj_forward};
    76 val all_forward = @{thm all_forward};
    77 val ex_forward = @{thm ex_forward};
    78 
    79 val not_conjD = @{thm not_conjD};
    80 val not_disjD = @{thm not_disjD};
    81 val not_notD = @{thm not_notD};
    82 val not_allD = @{thm not_allD};
    83 val not_exD = @{thm not_exD};
    84 val imp_to_disjD = @{thm imp_to_disjD};
    85 val not_impD = @{thm not_impD};
    86 val iff_to_disjD = @{thm iff_to_disjD};
    87 val not_iffD = @{thm not_iffD};
    88 val conj_exD1 = @{thm conj_exD1};
    89 val conj_exD2 = @{thm conj_exD2};
    90 val disj_exD = @{thm disj_exD};
    91 val disj_exD1 = @{thm disj_exD1};
    92 val disj_exD2 = @{thm disj_exD2};
    93 val disj_assoc = @{thm disj_assoc};
    94 val disj_comm = @{thm disj_comm};
    95 val disj_FalseD1 = @{thm disj_FalseD1};
    96 val disj_FalseD2 = @{thm disj_FalseD2};
    97 
    98 
    99 (**** Operators for forward proof ****)
   100 
   101 
   102 (** First-order Resolution **)
   103 
   104 fun term_pair_of (ix, (ty,t)) = (Var (ix,ty), t);
   105 
   106 (*FIXME: currently does not "rename variables apart"*)
   107 fun first_order_resolve thA thB =
   108   (case
   109     try (fn () =>
   110       let val thy = theory_of_thm thA
   111           val tmA = concl_of thA
   112           val Const("==>",_) $ tmB $ _ = prop_of thB
   113           val tenv =
   114             Pattern.first_order_match thy (tmB, tmA)
   115                                           (Vartab.empty, Vartab.empty) |> snd
   116           val ct_pairs = map (pairself (cterm_of thy) o term_pair_of) (Vartab.dest tenv)
   117       in  thA RS (cterm_instantiate ct_pairs thB)  end) () of
   118     SOME th => th
   119   | NONE => raise THM ("first_order_resolve", 0, [thA, thB]))
   120 
   121 (* Hack to make it less likely that we lose our precious bound variable names in
   122    "rename_bound_vars_RS" below, because of a clash. *)
   123 val protect_prefix = "Meson_xyzzy"
   124 
   125 fun protect_bound_var_names (t $ u) =
   126     protect_bound_var_names t $ protect_bound_var_names u
   127   | protect_bound_var_names (Abs (s, T, t')) =
   128     Abs (protect_prefix ^ s, T, protect_bound_var_names t')
   129   | protect_bound_var_names t = t
   130 
   131 fun fix_bound_var_names old_t new_t =
   132   let
   133     fun quant_of @{const_name All} = SOME true
   134       | quant_of @{const_name Ball} = SOME true
   135       | quant_of @{const_name Ex} = SOME false
   136       | quant_of @{const_name Bex} = SOME false
   137       | quant_of _ = NONE
   138     val flip_quant = Option.map not
   139     fun some_eq (SOME x) (SOME y) = x = y
   140       | some_eq _ _ = false
   141     fun add_names quant (Const (quant_s, _) $ Abs (s, _, t')) =
   142         add_names quant t' #> some_eq quant (quant_of quant_s) ? cons s
   143       | add_names quant (@{const Not} $ t) = add_names (flip_quant quant) t
   144       | add_names quant (@{const implies} $ t1 $ t2) =
   145         add_names (flip_quant quant) t1 #> add_names quant t2
   146       | add_names quant (t1 $ t2) = fold (add_names quant) [t1, t2]
   147       | add_names _ _ = I
   148     fun lost_names quant =
   149       subtract (op =) (add_names quant new_t []) (add_names quant old_t [])
   150     fun aux ((t1 as Const (quant_s, _)) $ (Abs (s, T, t'))) =
   151       t1 $ Abs (s |> String.isPrefix protect_prefix s
   152                    ? perhaps (try (fn _ => hd (lost_names (quant_of quant_s)))),
   153                 T, aux t')
   154       | aux (t1 $ t2) = aux t1 $ aux t2
   155       | aux t = t
   156   in aux new_t end
   157 
   158 (* Forward proof while preserving bound variables names *)
   159 fun rename_bound_vars_RS th rl =
   160   let
   161     val t = concl_of th
   162     val r = concl_of rl
   163     val th' = th RS Thm.rename_boundvars r (protect_bound_var_names r) rl
   164     val t' = concl_of th'
   165   in Thm.rename_boundvars t' (fix_bound_var_names t t') th' end
   166 
   167 (*raises exception if no rules apply*)
   168 fun tryres (th, rls) =
   169   let fun tryall [] = raise THM("tryres", 0, th::rls)
   170         | tryall (rl::rls) =
   171           (rename_bound_vars_RS th rl handle THM _ => tryall rls)
   172   in  tryall rls  end;
   173 
   174 (*Permits forward proof from rules that discharge assumptions. The supplied proof state st,
   175   e.g. from conj_forward, should have the form
   176     "[| P' ==> ?P; Q' ==> ?Q |] ==> ?P & ?Q"
   177   and the effect should be to instantiate ?P and ?Q with normalized versions of P' and Q'.*)
   178 fun forward_res ctxt nf st =
   179   let fun forward_tacf [prem] = rtac (nf prem) 1
   180         | forward_tacf prems =
   181             error (cat_lines
   182               ("Bad proof state in forward_res, please inform lcp@cl.cam.ac.uk:" ::
   183                 Display.string_of_thm ctxt st ::
   184                 "Premises:" :: map (Display.string_of_thm ctxt) prems))
   185   in
   186     case Seq.pull (ALLGOALS (Misc_Legacy.METAHYPS forward_tacf) st)
   187     of SOME(th,_) => th
   188      | NONE => raise THM("forward_res", 0, [st])
   189   end;
   190 
   191 (*Are any of the logical connectives in "bs" present in the term?*)
   192 fun has_conns bs =
   193   let fun has (Const _) = false
   194         | has (Const(@{const_name Trueprop},_) $ p) = has p
   195         | has (Const(@{const_name Not},_) $ p) = has p
   196         | has (Const(@{const_name HOL.disj},_) $ p $ q) = member (op =) bs @{const_name HOL.disj} orelse has p orelse has q
   197         | has (Const(@{const_name HOL.conj},_) $ p $ q) = member (op =) bs @{const_name HOL.conj} orelse has p orelse has q
   198         | has (Const(@{const_name All},_) $ Abs(_,_,p)) = member (op =) bs @{const_name All} orelse has p
   199         | has (Const(@{const_name Ex},_) $ Abs(_,_,p)) = member (op =) bs @{const_name Ex} orelse has p
   200         | has _ = false
   201   in  has  end;
   202 
   203 
   204 (**** Clause handling ****)
   205 
   206 fun literals (Const(@{const_name Trueprop},_) $ P) = literals P
   207   | literals (Const(@{const_name HOL.disj},_) $ P $ Q) = literals P @ literals Q
   208   | literals (Const(@{const_name Not},_) $ P) = [(false,P)]
   209   | literals P = [(true,P)];
   210 
   211 (*number of literals in a term*)
   212 val nliterals = length o literals;
   213 
   214 
   215 (*** Tautology Checking ***)
   216 
   217 fun signed_lits_aux (Const (@{const_name HOL.disj}, _) $ P $ Q) (poslits, neglits) =
   218       signed_lits_aux Q (signed_lits_aux P (poslits, neglits))
   219   | signed_lits_aux (Const(@{const_name Not},_) $ P) (poslits, neglits) = (poslits, P::neglits)
   220   | signed_lits_aux P (poslits, neglits) = (P::poslits, neglits);
   221 
   222 fun signed_lits th = signed_lits_aux (HOLogic.dest_Trueprop (concl_of th)) ([],[]);
   223 
   224 (*Literals like X=X are tautologous*)
   225 fun taut_poslit (Const(@{const_name HOL.eq},_) $ t $ u) = t aconv u
   226   | taut_poslit (Const(@{const_name True},_)) = true
   227   | taut_poslit _ = false;
   228 
   229 fun is_taut th =
   230   let val (poslits,neglits) = signed_lits th
   231   in  exists taut_poslit poslits
   232       orelse
   233       exists (member (op aconv) neglits) (HOLogic.false_const :: poslits)
   234   end
   235   handle TERM _ => false;       (*probably dest_Trueprop on a weird theorem*)
   236 
   237 
   238 (*** To remove trivial negated equality literals from clauses ***)
   239 
   240 (*They are typically functional reflexivity axioms and are the converses of
   241   injectivity equivalences*)
   242 
   243 val not_refl_disj_D = @{thm not_refl_disj_D};
   244 
   245 (*Is either term a Var that does not properly occur in the other term?*)
   246 fun eliminable (t as Var _, u) = t aconv u orelse not (Logic.occs(t,u))
   247   | eliminable (u, t as Var _) = t aconv u orelse not (Logic.occs(t,u))
   248   | eliminable _ = false;
   249 
   250 fun refl_clause_aux 0 th = th
   251   | refl_clause_aux n th =
   252        case HOLogic.dest_Trueprop (concl_of th) of
   253           (Const (@{const_name HOL.disj}, _) $ (Const (@{const_name HOL.disj}, _) $ _ $ _) $ _) =>
   254             refl_clause_aux n (th RS disj_assoc)    (*isolate an atom as first disjunct*)
   255         | (Const (@{const_name HOL.disj}, _) $ (Const(@{const_name Not},_) $ (Const(@{const_name HOL.eq},_) $ t $ u)) $ _) =>
   256             if eliminable(t,u)
   257             then refl_clause_aux (n-1) (th RS not_refl_disj_D)  (*Var inequation: delete*)
   258             else refl_clause_aux (n-1) (th RS disj_comm)  (*not between Vars: ignore*)
   259         | (Const (@{const_name HOL.disj}, _) $ _ $ _) => refl_clause_aux n (th RS disj_comm)
   260         | _ => (*not a disjunction*) th;
   261 
   262 fun notequal_lits_count (Const (@{const_name HOL.disj}, _) $ P $ Q) =
   263       notequal_lits_count P + notequal_lits_count Q
   264   | notequal_lits_count (Const(@{const_name Not},_) $ (Const(@{const_name HOL.eq},_) $ _ $ _)) = 1
   265   | notequal_lits_count _ = 0;
   266 
   267 (*Simplify a clause by applying reflexivity to its negated equality literals*)
   268 fun refl_clause th =
   269   let val neqs = notequal_lits_count (HOLogic.dest_Trueprop (concl_of th))
   270   in  zero_var_indexes (refl_clause_aux neqs th)  end
   271   handle TERM _ => th;  (*probably dest_Trueprop on a weird theorem*)
   272 
   273 
   274 (*** Removal of duplicate literals ***)
   275 
   276 (*Forward proof, passing extra assumptions as theorems to the tactic*)
   277 fun forward_res2 nf hyps st =
   278   case Seq.pull
   279         (REPEAT
   280          (Misc_Legacy.METAHYPS (fn major::minors => rtac (nf (minors@hyps) major) 1) 1)
   281          st)
   282   of SOME(th,_) => th
   283    | NONE => raise THM("forward_res2", 0, [st]);
   284 
   285 (*Remove duplicates in P|Q by assuming ~P in Q
   286   rls (initially []) accumulates assumptions of the form P==>False*)
   287 fun nodups_aux ctxt rls th = nodups_aux ctxt rls (th RS disj_assoc)
   288     handle THM _ => tryres(th,rls)
   289     handle THM _ => tryres(forward_res2 (nodups_aux ctxt) rls (th RS disj_forward2),
   290                            [disj_FalseD1, disj_FalseD2, asm_rl])
   291     handle THM _ => th;
   292 
   293 (*Remove duplicate literals, if there are any*)
   294 fun nodups ctxt th =
   295   if has_duplicates (op =) (literals (prop_of th))
   296     then nodups_aux ctxt [] th
   297     else th;
   298 
   299 
   300 (*** The basic CNF transformation ***)
   301 
   302 fun estimated_num_clauses bound t =
   303  let
   304   fun sum x y = if x < bound andalso y < bound then x+y else bound
   305   fun prod x y = if x < bound andalso y < bound then x*y else bound
   306   
   307   (*Estimate the number of clauses in order to detect infeasible theorems*)
   308   fun signed_nclauses b (Const(@{const_name Trueprop},_) $ t) = signed_nclauses b t
   309     | signed_nclauses b (Const(@{const_name Not},_) $ t) = signed_nclauses (not b) t
   310     | signed_nclauses b (Const(@{const_name HOL.conj},_) $ t $ u) =
   311         if b then sum (signed_nclauses b t) (signed_nclauses b u)
   312              else prod (signed_nclauses b t) (signed_nclauses b u)
   313     | signed_nclauses b (Const(@{const_name HOL.disj},_) $ t $ u) =
   314         if b then prod (signed_nclauses b t) (signed_nclauses b u)
   315              else sum (signed_nclauses b t) (signed_nclauses b u)
   316     | signed_nclauses b (Const(@{const_name HOL.implies},_) $ t $ u) =
   317         if b then prod (signed_nclauses (not b) t) (signed_nclauses b u)
   318              else sum (signed_nclauses (not b) t) (signed_nclauses b u)
   319     | signed_nclauses b (Const(@{const_name HOL.eq}, Type ("fun", [T, _])) $ t $ u) =
   320         if T = HOLogic.boolT then (*Boolean equality is if-and-only-if*)
   321             if b then sum (prod (signed_nclauses (not b) t) (signed_nclauses b u))
   322                           (prod (signed_nclauses (not b) u) (signed_nclauses b t))
   323                  else sum (prod (signed_nclauses b t) (signed_nclauses b u))
   324                           (prod (signed_nclauses (not b) t) (signed_nclauses (not b) u))
   325         else 1
   326     | signed_nclauses b (Const(@{const_name Ex}, _) $ Abs (_,_,t)) = signed_nclauses b t
   327     | signed_nclauses b (Const(@{const_name All},_) $ Abs (_,_,t)) = signed_nclauses b t
   328     | signed_nclauses _ _ = 1; (* literal *)
   329  in signed_nclauses true t end
   330 
   331 fun has_too_many_clauses ctxt t =
   332   let val max_cl = Config.get ctxt max_clauses in
   333     estimated_num_clauses (max_cl + 1) t > max_cl
   334   end
   335 
   336 (*Replaces universally quantified variables by FREE variables -- because
   337   assumptions may not contain scheme variables.  Later, generalize using Variable.export. *)
   338 local  
   339   val spec_var = Thm.dest_arg (Thm.dest_arg (#2 (Thm.dest_implies (Thm.cprop_of spec))));
   340   val spec_varT = #T (Thm.rep_cterm spec_var);
   341   fun name_of (Const (@{const_name All}, _) $ Abs(x,_,_)) = x | name_of _ = Name.uu;
   342 in  
   343   fun freeze_spec th ctxt =
   344     let
   345       val cert = Thm.cterm_of (Proof_Context.theory_of ctxt);
   346       val ([x], ctxt') = Variable.variant_fixes [name_of (HOLogic.dest_Trueprop (concl_of th))] ctxt;
   347       val spec' = Thm.instantiate ([], [(spec_var, cert (Free (x, spec_varT)))]) spec;
   348     in (th RS spec', ctxt') end
   349 end;
   350 
   351 (*Used with METAHYPS below. There is one assumption, which gets bound to prem
   352   and then normalized via function nf. The normal form is given to resolve_tac,
   353   instantiate a Boolean variable created by resolution with disj_forward. Since
   354   (nf prem) returns a LIST of theorems, we can backtrack to get all combinations.*)
   355 fun resop nf [prem] = resolve_tac (nf prem) 1;
   356 
   357 (* Any need to extend this list with "HOL.type_class", "HOL.eq_class",
   358    and "Pure.term"? *)
   359 val has_meta_conn = exists_Const (member (op =) ["==", "==>", "=simp=>", "all", "prop"] o #1);
   360 
   361 fun apply_skolem_theorem (th, rls) =
   362   let
   363     fun tryall [] = raise THM ("apply_skolem_theorem", 0, th::rls)
   364       | tryall (rl :: rls) =
   365         first_order_resolve th rl handle THM _ => tryall rls
   366   in tryall rls end
   367 
   368 (* Conjunctive normal form, adding clauses from th in front of ths (for foldr).
   369    Strips universal quantifiers and breaks up conjunctions.
   370    Eliminates existential quantifiers using Skolemization theorems. *)
   371 fun cnf old_skolem_ths ctxt ctxt0 (th, ths) =
   372   let val ctxt0r = Unsynchronized.ref ctxt0   (* FIXME ??? *)
   373       fun cnf_aux (th,ths) =
   374         if not (can HOLogic.dest_Trueprop (prop_of th)) then ths (*meta-level: ignore*)
   375         else if not (has_conns [@{const_name All}, @{const_name Ex}, @{const_name HOL.conj}] (prop_of th))
   376         then nodups ctxt0 th :: ths (*no work to do, terminate*)
   377         else case head_of (HOLogic.dest_Trueprop (concl_of th)) of
   378             Const (@{const_name HOL.conj}, _) => (*conjunction*)
   379                 cnf_aux (th RS conjunct1, cnf_aux (th RS conjunct2, ths))
   380           | Const (@{const_name All}, _) => (*universal quantifier*)
   381                 let val (th',ctxt0') = freeze_spec th (!ctxt0r)
   382                 in  ctxt0r := ctxt0'; cnf_aux (th', ths) end
   383           | Const (@{const_name Ex}, _) =>
   384               (*existential quantifier: Insert Skolem functions*)
   385               cnf_aux (apply_skolem_theorem (th, old_skolem_ths), ths)
   386           | Const (@{const_name HOL.disj}, _) =>
   387               (*Disjunction of P, Q: Create new goal of proving ?P | ?Q and solve it using
   388                 all combinations of converting P, Q to CNF.*)
   389               let val tac =
   390                   Misc_Legacy.METAHYPS (resop cnf_nil) 1 THEN
   391                    (fn st' => st' |> Misc_Legacy.METAHYPS (resop cnf_nil) 1)
   392               in  Seq.list_of (tac (th RS disj_forward)) @ ths  end
   393           | _ => nodups ctxt0 th :: ths  (*no work to do*)
   394       and cnf_nil th = cnf_aux (th,[])
   395       val cls =
   396         if has_too_many_clauses ctxt (concl_of th) then
   397           (trace_msg ctxt (fn () =>
   398                "cnf is ignoring: " ^ Display.string_of_thm ctxt0 th); ths)
   399         else
   400           cnf_aux (th, ths)
   401   in (cls, !ctxt0r) end
   402 fun make_cnf old_skolem_ths th ctxt ctxt0 =
   403   cnf old_skolem_ths ctxt ctxt0 (th, [])
   404 
   405 (*Generalization, removal of redundant equalities, removal of tautologies.*)
   406 fun finish_cnf ths = filter (not o is_taut) (map refl_clause ths);
   407 
   408 
   409 (**** Generation of contrapositives ****)
   410 
   411 fun is_left (Const (@{const_name Trueprop}, _) $
   412                (Const (@{const_name HOL.disj}, _) $ (Const (@{const_name HOL.disj}, _) $ _ $ _) $ _)) = true
   413   | is_left _ = false;
   414 
   415 (*Associate disjuctions to right -- make leftmost disjunct a LITERAL*)
   416 fun assoc_right th =
   417   if is_left (prop_of th) then assoc_right (th RS disj_assoc)
   418   else th;
   419 
   420 (*Must check for negative literal first!*)
   421 val clause_rules = [disj_assoc, make_neg_rule, make_pos_rule];
   422 
   423 (*For ordinary resolution. *)
   424 val resolution_clause_rules = [disj_assoc, make_neg_rule', make_pos_rule'];
   425 
   426 (*Create a goal or support clause, conclusing False*)
   427 fun make_goal th =   (*Must check for negative literal first!*)
   428     make_goal (tryres(th, clause_rules))
   429   handle THM _ => tryres(th, [make_neg_goal, make_pos_goal]);
   430 
   431 (*Sort clauses by number of literals*)
   432 fun fewerlits(th1,th2) = nliterals(prop_of th1) < nliterals(prop_of th2);
   433 
   434 fun sort_clauses ths = sort (make_ord fewerlits) ths;
   435 
   436 fun has_bool @{typ bool} = true
   437   | has_bool (Type (_, Ts)) = exists has_bool Ts
   438   | has_bool _ = false
   439 
   440 fun has_fun (Type (@{type_name fun}, _)) = true
   441   | has_fun (Type (_, Ts)) = exists has_fun Ts
   442   | has_fun _ = false
   443 
   444 (*Is the string the name of a connective? Really only | and Not can remain,
   445   since this code expects to be called on a clause form.*)
   446 val is_conn = member (op =)
   447     [@{const_name Trueprop}, @{const_name HOL.conj}, @{const_name HOL.disj},
   448      @{const_name HOL.implies}, @{const_name Not},
   449      @{const_name All}, @{const_name Ex}, @{const_name Ball}, @{const_name Bex}];
   450 
   451 (*True if the term contains a function--not a logical connective--where the type
   452   of any argument contains bool.*)
   453 val has_bool_arg_const =
   454     exists_Const
   455       (fn (c,T) => not(is_conn c) andalso exists has_bool (binder_types T));
   456 
   457 (*A higher-order instance of a first-order constant? Example is the definition of
   458   one, 1, at a function type in theory Function_Algebras.*)
   459 fun higher_inst_const thy (c,T) =
   460   case binder_types T of
   461       [] => false (*not a function type, OK*)
   462     | Ts => length (binder_types (Sign.the_const_type thy c)) <> length Ts;
   463 
   464 (* Returns false if any Vars in the theorem mention type bool.
   465    Also rejects functions whose arguments are Booleans or other functions. *)
   466 fun is_fol_term thy t =
   467     Term.is_first_order [@{const_name all}, @{const_name All},
   468                          @{const_name Ex}] t andalso
   469     not (exists_subterm (fn Var (_, T) => has_bool T orelse has_fun T
   470                           | _ => false) t orelse
   471          has_bool_arg_const t orelse
   472          exists_Const (higher_inst_const thy) t orelse
   473          has_meta_conn t);
   474 
   475 fun rigid t = not (is_Var (head_of t));
   476 
   477 fun ok4horn (Const (@{const_name Trueprop},_) $ (Const (@{const_name HOL.disj}, _) $ t $ _)) = rigid t
   478   | ok4horn (Const (@{const_name Trueprop},_) $ t) = rigid t
   479   | ok4horn _ = false;
   480 
   481 (*Create a meta-level Horn clause*)
   482 fun make_horn crules th =
   483   if ok4horn (concl_of th)
   484   then make_horn crules (tryres(th,crules)) handle THM _ => th
   485   else th;
   486 
   487 (*Generate Horn clauses for all contrapositives of a clause. The input, th,
   488   is a HOL disjunction.*)
   489 fun add_contras crules th hcs =
   490   let fun rots (0,_) = hcs
   491         | rots (k,th) = zero_var_indexes (make_horn crules th) ::
   492                         rots(k-1, assoc_right (th RS disj_comm))
   493   in case nliterals(prop_of th) of
   494         1 => th::hcs
   495       | n => rots(n, assoc_right th)
   496   end;
   497 
   498 (*Use "theorem naming" to label the clauses*)
   499 fun name_thms label =
   500     let fun name1 th (k, ths) =
   501           (k-1, Thm.put_name_hint (label ^ string_of_int k) th :: ths)
   502     in  fn ths => #2 (fold_rev name1 ths (length ths, []))  end;
   503 
   504 (*Is the given disjunction an all-negative support clause?*)
   505 fun is_negative th = forall (not o #1) (literals (prop_of th));
   506 
   507 val neg_clauses = filter is_negative;
   508 
   509 
   510 (***** MESON PROOF PROCEDURE *****)
   511 
   512 fun rhyps (Const("==>",_) $ (Const(@{const_name Trueprop},_) $ A) $ phi,
   513            As) = rhyps(phi, A::As)
   514   | rhyps (_, As) = As;
   515 
   516 (** Detecting repeated assumptions in a subgoal **)
   517 
   518 (*The stringtree detects repeated assumptions.*)
   519 fun ins_term t net = Net.insert_term (op aconv) (t, t) net;
   520 
   521 (*detects repetitions in a list of terms*)
   522 fun has_reps [] = false
   523   | has_reps [_] = false
   524   | has_reps [t,u] = (t aconv u)
   525   | has_reps ts = (fold ins_term ts Net.empty; false) handle Net.INSERT => true;
   526 
   527 (*Like TRYALL eq_assume_tac, but avoids expensive THEN calls*)
   528 fun TRYING_eq_assume_tac 0 st = Seq.single st
   529   | TRYING_eq_assume_tac i st =
   530        TRYING_eq_assume_tac (i-1) (Thm.eq_assumption i st)
   531        handle THM _ => TRYING_eq_assume_tac (i-1) st;
   532 
   533 fun TRYALL_eq_assume_tac st = TRYING_eq_assume_tac (nprems_of st) st;
   534 
   535 (*Loop checking: FAIL if trying to prove the same thing twice
   536   -- if *ANY* subgoal has repeated literals*)
   537 fun check_tac st =
   538   if exists (fn prem => has_reps (rhyps(prem,[]))) (prems_of st)
   539   then  Seq.empty  else  Seq.single st;
   540 
   541 
   542 (* net_resolve_tac actually made it slower... *)
   543 fun prolog_step_tac horns i =
   544     (assume_tac i APPEND resolve_tac horns i) THEN check_tac THEN
   545     TRYALL_eq_assume_tac;
   546 
   547 (*Sums the sizes of the subgoals, ignoring hypotheses (ancestors)*)
   548 fun addconcl prem sz = size_of_term (Logic.strip_assums_concl prem) + sz;
   549 
   550 fun size_of_subgoals st = fold_rev addconcl (prems_of st) 0;
   551 
   552 
   553 (*Negation Normal Form*)
   554 val nnf_rls = [imp_to_disjD, iff_to_disjD, not_conjD, not_disjD,
   555                not_impD, not_iffD, not_allD, not_exD, not_notD];
   556 
   557 fun ok4nnf (Const (@{const_name Trueprop},_) $ (Const (@{const_name Not}, _) $ t)) = rigid t
   558   | ok4nnf (Const (@{const_name Trueprop},_) $ t) = rigid t
   559   | ok4nnf _ = false;
   560 
   561 fun make_nnf1 ctxt th =
   562   if ok4nnf (concl_of th)
   563   then make_nnf1 ctxt (tryres(th, nnf_rls))
   564     handle THM ("tryres", _, _) =>
   565         forward_res ctxt (make_nnf1 ctxt)
   566            (tryres(th, [conj_forward,disj_forward,all_forward,ex_forward]))
   567     handle THM ("tryres", _, _) => th
   568   else th
   569 
   570 fun unfold_set_const_simps ctxt =
   571   if Config.get ctxt unfold_set_consts then @{thms Collect_def_raw mem_def_raw}
   572   else []
   573 
   574 (*The simplification removes defined quantifiers and occurrences of True and False.
   575   nnf_ss also includes the one-point simprocs,
   576   which are needed to avoid the various one-point theorems from generating junk clauses.*)
   577 val nnf_simps =
   578   @{thms simp_implies_def Ex1_def Ball_def Bex_def if_True if_False if_cancel
   579          if_eq_cancel cases_simp}
   580 val nnf_extra_simps = @{thms split_ifs ex_simps all_simps simp_thms}
   581 
   582 (* FIXME: "let_simp" is probably redundant now that we also rewrite with
   583   "Let_def_raw". *)
   584 val nnf_ss =
   585   HOL_basic_ss addsimps nnf_extra_simps
   586     addsimprocs [@{simproc defined_All}, @{simproc defined_Ex}, @{simproc neq},
   587                  @{simproc let_simp}]
   588 
   589 fun presimplified_consts ctxt =
   590   [@{const_name simp_implies}, @{const_name False}, @{const_name True},
   591    @{const_name Ex1}, @{const_name Ball}, @{const_name Bex}, @{const_name If},
   592    @{const_name Let}]
   593   |> Config.get ctxt unfold_set_consts
   594      ? append ([@{const_name Collect}, @{const_name Set.member}])
   595 
   596 fun presimplify ctxt =
   597   rewrite_rule (map safe_mk_meta_eq nnf_simps)
   598   #> simplify nnf_ss
   599   (* TODO: avoid introducing "Set.member" in "Ball_def" "Bex_def" above if and
   600      when "metis_unfold_set_consts" becomes the only mode of operation. *)
   601   #> Raw_Simplifier.rewrite_rule
   602          (@{thm Let_def_raw} :: unfold_set_const_simps ctxt)
   603 
   604 fun make_nnf ctxt th = case prems_of th of
   605     [] => th |> presimplify ctxt |> make_nnf1 ctxt
   606   | _ => raise THM ("make_nnf: premises in argument", 0, [th]);
   607 
   608 fun choice_theorems thy =
   609   try (Global_Theory.get_thm thy) "Hilbert_Choice.choice" |> the_list
   610 
   611 (* Pull existential quantifiers to front. This accomplishes Skolemization for
   612    clauses that arise from a subgoal. *)
   613 fun skolemize_with_choice_theorems ctxt choice_ths =
   614   let
   615     fun aux th =
   616       if not (has_conns [@{const_name Ex}] (prop_of th)) then
   617         th
   618       else
   619         tryres (th, choice_ths @
   620                     [conj_exD1, conj_exD2, disj_exD, disj_exD1, disj_exD2])
   621         |> aux
   622         handle THM ("tryres", _, _) =>
   623                tryres (th, [conj_forward, disj_forward, all_forward])
   624                |> forward_res ctxt aux
   625                |> aux
   626                handle THM ("tryres", _, _) =>
   627                       rename_bound_vars_RS th ex_forward
   628                       |> forward_res ctxt aux
   629   in aux o make_nnf ctxt end
   630 
   631 fun skolemize ctxt =
   632   let val thy = Proof_Context.theory_of ctxt in
   633     skolemize_with_choice_theorems ctxt (choice_theorems thy)
   634   end
   635 
   636 (* Removes the lambdas from an equation of the form "t = (%x1 ... xn. u)". It
   637    would be desirable to do this symmetrically but there's at least one existing
   638    proof in "Tarski" that relies on the current behavior. *)
   639 fun extensionalize_conv ctxt ct =
   640   case term_of ct of
   641     Const (@{const_name HOL.eq}, _) $ _ $ Abs _ =>
   642     ct |> (Conv.rewr_conv @{thm fun_eq_iff [THEN eq_reflection]}
   643            then_conv extensionalize_conv ctxt)
   644   | _ $ _ => Conv.comb_conv (extensionalize_conv ctxt) ct
   645   | Abs _ => Conv.abs_conv (extensionalize_conv o snd) ctxt ct
   646   | _ => Conv.all_conv ct
   647 
   648 val extensionalize_theorem = Conv.fconv_rule o extensionalize_conv
   649 
   650 (* "RS" can fail if "unify_search_bound" is too small. *)
   651 fun try_skolemize_etc ctxt =
   652   Raw_Simplifier.rewrite_rule (unfold_set_const_simps ctxt)
   653   (* Extensionalize "th", because that makes sense and that's what Sledgehammer
   654      does, but also keep an unextensionalized version of "th" for backward
   655      compatibility. *)
   656   #> (fn th => insert Thm.eq_thm_prop (extensionalize_theorem ctxt th) [th])
   657   #> map_filter (fn th => try (skolemize ctxt) th
   658                           |> tap (fn NONE =>
   659                                      trace_msg ctxt (fn () =>
   660                                          "Failed to skolemize " ^
   661                                           Display.string_of_thm ctxt th)
   662                                    | _ => ()))
   663 
   664 fun add_clauses ctxt th cls =
   665   let val ctxt0 = Variable.global_thm_context th
   666       val (cnfs, ctxt) = make_cnf [] th ctxt ctxt0
   667   in Variable.export ctxt ctxt0 cnfs @ cls end;
   668 
   669 (*Make clauses from a list of theorems, previously Skolemized and put into nnf.
   670   The resulting clauses are HOL disjunctions.*)
   671 fun make_clauses_unsorted ctxt ths = fold_rev (add_clauses ctxt) ths [];
   672 val make_clauses = sort_clauses oo make_clauses_unsorted;
   673 
   674 (*Convert a list of clauses (disjunctions) to Horn clauses (contrapositives)*)
   675 fun make_horns ths =
   676     name_thms "Horn#"
   677       (distinct Thm.eq_thm_prop (fold_rev (add_contras clause_rules) ths []));
   678 
   679 (*Could simply use nprems_of, which would count remaining subgoals -- no
   680   discrimination as to their size!  With BEST_FIRST, fails for problem 41.*)
   681 
   682 fun best_prolog_tac sizef horns =
   683     BEST_FIRST (has_fewer_prems 1, sizef) (prolog_step_tac horns 1);
   684 
   685 fun depth_prolog_tac horns =
   686     DEPTH_FIRST (has_fewer_prems 1) (prolog_step_tac horns 1);
   687 
   688 (*Return all negative clauses, as possible goal clauses*)
   689 fun gocls cls = name_thms "Goal#" (map make_goal (neg_clauses cls));
   690 
   691 fun skolemize_prems_tac ctxt prems =
   692   cut_facts_tac (maps (try_skolemize_etc ctxt) prems) THEN' REPEAT o etac exE
   693 
   694 (*Basis of all meson-tactics.  Supplies cltac with clauses: HOL disjunctions.
   695   Function mkcl converts theorems to clauses.*)
   696 fun MESON preskolem_tac mkcl cltac ctxt i st =
   697   SELECT_GOAL
   698     (EVERY [Object_Logic.atomize_prems_tac 1,
   699             rtac ccontr 1,
   700             preskolem_tac,
   701             Subgoal.FOCUS (fn {context = ctxt', prems = negs, ...} =>
   702                       EVERY1 [skolemize_prems_tac ctxt negs,
   703                               Subgoal.FOCUS (cltac o mkcl o #prems) ctxt']) ctxt 1]) i st
   704   handle THM _ => no_tac st;    (*probably from make_meta_clause, not first-order*)
   705 
   706 
   707 (** Best-first search versions **)
   708 
   709 (*ths is a list of additional clauses (HOL disjunctions) to use.*)
   710 fun best_meson_tac sizef ctxt =
   711   MESON all_tac (make_clauses ctxt)
   712     (fn cls =>
   713          THEN_BEST_FIRST (resolve_tac (gocls cls) 1)
   714                          (has_fewer_prems 1, sizef)
   715                          (prolog_step_tac (make_horns cls) 1))
   716     ctxt
   717 
   718 (*First, breaks the goal into independent units*)
   719 fun safe_best_meson_tac ctxt =
   720   SELECT_GOAL (TRY (safe_tac ctxt) THEN TRYALL (best_meson_tac size_of_subgoals ctxt));
   721 
   722 (** Depth-first search version **)
   723 
   724 fun depth_meson_tac ctxt =
   725   MESON all_tac (make_clauses ctxt)
   726     (fn cls => EVERY [resolve_tac (gocls cls) 1, depth_prolog_tac (make_horns cls)])
   727     ctxt
   728 
   729 (** Iterative deepening version **)
   730 
   731 (*This version does only one inference per call;
   732   having only one eq_assume_tac speeds it up!*)
   733 fun prolog_step_tac' horns =
   734     let val (horn0s, _) = (*0 subgoals vs 1 or more*)
   735             take_prefix Thm.no_prems horns
   736         val nrtac = net_resolve_tac horns
   737     in  fn i => eq_assume_tac i ORELSE
   738                 match_tac horn0s i ORELSE  (*no backtracking if unit MATCHES*)
   739                 ((assume_tac i APPEND nrtac i) THEN check_tac)
   740     end;
   741 
   742 fun iter_deepen_prolog_tac horns =
   743     ITER_DEEPEN iter_deepen_limit (has_fewer_prems 1) (prolog_step_tac' horns);
   744 
   745 fun iter_deepen_meson_tac ctxt ths = ctxt |> MESON all_tac (make_clauses ctxt)
   746   (fn cls =>
   747     (case (gocls (cls @ ths)) of
   748       [] => no_tac  (*no goal clauses*)
   749     | goes =>
   750         let
   751           val horns = make_horns (cls @ ths)
   752           val _ = trace_msg ctxt (fn () =>
   753             cat_lines ("meson method called:" ::
   754               map (Display.string_of_thm ctxt) (cls @ ths) @
   755               ["clauses:"] @ map (Display.string_of_thm ctxt) horns))
   756         in
   757           THEN_ITER_DEEPEN iter_deepen_limit
   758             (resolve_tac goes 1) (has_fewer_prems 1) (prolog_step_tac' horns)
   759         end));
   760 
   761 fun meson_tac ctxt ths =
   762   SELECT_GOAL (TRY (safe_tac ctxt) THEN TRYALL (iter_deepen_meson_tac ctxt ths));
   763 
   764 
   765 (**** Code to support ordinary resolution, rather than Model Elimination ****)
   766 
   767 (*Convert a list of clauses (disjunctions) to meta-level clauses (==>),
   768   with no contrapositives, for ordinary resolution.*)
   769 
   770 (*Rules to convert the head literal into a negated assumption. If the head
   771   literal is already negated, then using notEfalse instead of notEfalse'
   772   prevents a double negation.*)
   773 val notEfalse = read_instantiate @{context} [(("R", 0), "False")] notE;
   774 val notEfalse' = rotate_prems 1 notEfalse;
   775 
   776 fun negated_asm_of_head th =
   777     th RS notEfalse handle THM _ => th RS notEfalse';
   778 
   779 (*Converting one theorem from a disjunction to a meta-level clause*)
   780 fun make_meta_clause th =
   781   let val (fth,thaw) = Drule.legacy_freeze_thaw_robust th
   782   in  
   783       (zero_var_indexes o Thm.varifyT_global o thaw 0 o 
   784        negated_asm_of_head o make_horn resolution_clause_rules) fth
   785   end;
   786 
   787 fun make_meta_clauses ths =
   788     name_thms "MClause#"
   789       (distinct Thm.eq_thm_prop (map make_meta_clause ths));
   790 
   791 end;