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