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