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