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