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