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