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