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