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