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