src/HOL/Tools/Meson/meson.ML
author blanchet
Mon Jan 02 14:12:20 2012 +0100 (2012-01-02)
changeset 46071 1613933e412c
parent 45981 4c629115e3ab
child 46093 4bf24b90703c
permissions -rw-r--r--
killed unfold_set_const option that makes no sense now that set is a type constructor again
     1 (*  Title:      HOL/Tools/Meson/meson.ML
     2     Author:     Lawrence C Paulson, Cambridge University Computer Laboratory
     3     Author:     Jasmin Blanchette, TU Muenchen
     4 
     5 The MESON resolution proof procedure for HOL.
     6 When making clauses, avoids using the rewriter -- instead uses RS recursively.
     7 *)
     8 
     9 signature MESON =
    10 sig
    11   val trace : bool Config.T
    12   val max_clauses : int Config.T
    13   val term_pair_of: indexname * (typ * 'a) -> term * 'a
    14   val first_order_resolve : thm -> thm -> thm
    15   val size_of_subgoals: thm -> int
    16   val has_too_many_clauses: Proof.context -> term -> bool
    17   val make_cnf:
    18     thm list -> thm -> Proof.context
    19     -> Proof.context -> thm list * Proof.context
    20   val finish_cnf: thm list -> thm list
    21   val presimplified_consts : Proof.context -> string list
    22   val presimplify: Proof.context -> thm -> thm
    23   val make_nnf: Proof.context -> thm -> thm
    24   val choice_theorems : theory -> thm list
    25   val skolemize_with_choice_theorems : Proof.context -> thm list -> thm -> thm
    26   val skolemize : Proof.context -> thm -> thm
    27   val extensionalize_conv : Proof.context -> conv
    28   val extensionalize_theorem : Proof.context -> thm -> thm
    29   val is_fol_term: theory -> term -> bool
    30   val make_clauses_unsorted: Proof.context -> thm list -> thm list
    31   val make_clauses: Proof.context -> thm list -> thm list
    32   val make_horns: thm list -> thm list
    33   val best_prolog_tac: (thm -> int) -> thm list -> tactic
    34   val depth_prolog_tac: thm list -> tactic
    35   val gocls: thm list -> thm list
    36   val skolemize_prems_tac : Proof.context -> thm list -> int -> tactic
    37   val MESON:
    38     tactic -> (thm list -> thm list) -> (thm list -> tactic) -> Proof.context
    39     -> int -> tactic
    40   val best_meson_tac: (thm -> int) -> Proof.context -> int -> tactic
    41   val safe_best_meson_tac: Proof.context -> int -> tactic
    42   val depth_meson_tac: Proof.context -> int -> tactic
    43   val prolog_step_tac': thm list -> int -> tactic
    44   val iter_deepen_prolog_tac: thm list -> tactic
    45   val iter_deepen_meson_tac: Proof.context -> thm list -> int -> tactic
    46   val make_meta_clause: thm -> thm
    47   val make_meta_clauses: thm list -> thm list
    48   val meson_tac: Proof.context -> thm list -> int -> tactic
    49 end
    50 
    51 structure Meson : MESON =
    52 struct
    53 
    54 val trace = Attrib.setup_config_bool @{binding meson_trace} (K false)
    55 
    56 fun trace_msg ctxt msg = if Config.get ctxt trace then tracing (msg ()) else ()
    57 
    58 val max_clauses = Attrib.setup_config_int @{binding meson_max_clauses} (K 60)
    59 
    60 (*No known example (on 1-5-2007) needs even thirty*)
    61 val iter_deepen_limit = 50;
    62 
    63 val disj_forward = @{thm disj_forward};
    64 val disj_forward2 = @{thm disj_forward2};
    65 val make_pos_rule = @{thm make_pos_rule};
    66 val make_pos_rule' = @{thm make_pos_rule'};
    67 val make_pos_goal = @{thm make_pos_goal};
    68 val make_neg_rule = @{thm make_neg_rule};
    69 val make_neg_rule' = @{thm make_neg_rule'};
    70 val make_neg_goal = @{thm make_neg_goal};
    71 val conj_forward = @{thm conj_forward};
    72 val all_forward = @{thm all_forward};
    73 val ex_forward = @{thm ex_forward};
    74 
    75 val not_conjD = @{thm not_conjD};
    76 val not_disjD = @{thm not_disjD};
    77 val not_notD = @{thm not_notD};
    78 val not_allD = @{thm not_allD};
    79 val not_exD = @{thm not_exD};
    80 val imp_to_disjD = @{thm imp_to_disjD};
    81 val not_impD = @{thm not_impD};
    82 val iff_to_disjD = @{thm iff_to_disjD};
    83 val not_iffD = @{thm not_iffD};
    84 val conj_exD1 = @{thm conj_exD1};
    85 val conj_exD2 = @{thm conj_exD2};
    86 val disj_exD = @{thm disj_exD};
    87 val disj_exD1 = @{thm disj_exD1};
    88 val disj_exD2 = @{thm disj_exD2};
    89 val disj_assoc = @{thm disj_assoc};
    90 val disj_comm = @{thm disj_comm};
    91 val disj_FalseD1 = @{thm disj_FalseD1};
    92 val disj_FalseD2 = @{thm disj_FalseD2};
    93 
    94 
    95 (**** Operators for forward proof ****)
    96 
    97 
    98 (** First-order Resolution **)
    99 
   100 fun term_pair_of (ix, (ty,t)) = (Var (ix,ty), t);
   101 
   102 (*FIXME: currently does not "rename variables apart"*)
   103 fun first_order_resolve thA thB =
   104   (case
   105     try (fn () =>
   106       let val thy = theory_of_thm thA
   107           val tmA = concl_of thA
   108           val Const("==>",_) $ tmB $ _ = prop_of thB
   109           val tenv =
   110             Pattern.first_order_match thy (tmB, tmA)
   111                                           (Vartab.empty, Vartab.empty) |> snd
   112           val ct_pairs = map (pairself (cterm_of thy) o term_pair_of) (Vartab.dest tenv)
   113       in  thA RS (cterm_instantiate ct_pairs thB)  end) () of
   114     SOME th => th
   115   | NONE => raise THM ("first_order_resolve", 0, [thA, thB]))
   116 
   117 (* Hack to make it less likely that we lose our precious bound variable names in
   118    "rename_bound_vars_RS" below, because of a clash. *)
   119 val protect_prefix = "Meson_xyzzy"
   120 
   121 fun protect_bound_var_names (t $ u) =
   122     protect_bound_var_names t $ protect_bound_var_names u
   123   | protect_bound_var_names (Abs (s, T, t')) =
   124     Abs (protect_prefix ^ s, T, protect_bound_var_names t')
   125   | protect_bound_var_names t = t
   126 
   127 fun fix_bound_var_names old_t new_t =
   128   let
   129     fun quant_of @{const_name All} = SOME true
   130       | quant_of @{const_name Ball} = SOME true
   131       | quant_of @{const_name Ex} = SOME false
   132       | quant_of @{const_name Bex} = SOME false
   133       | quant_of _ = NONE
   134     val flip_quant = Option.map not
   135     fun some_eq (SOME x) (SOME y) = x = y
   136       | some_eq _ _ = false
   137     fun add_names quant (Const (quant_s, _) $ Abs (s, _, t')) =
   138         add_names quant t' #> some_eq quant (quant_of quant_s) ? cons s
   139       | add_names quant (@{const Not} $ t) = add_names (flip_quant quant) t
   140       | add_names quant (@{const implies} $ t1 $ t2) =
   141         add_names (flip_quant quant) t1 #> add_names quant t2
   142       | add_names quant (t1 $ t2) = fold (add_names quant) [t1, t2]
   143       | add_names _ _ = I
   144     fun lost_names quant =
   145       subtract (op =) (add_names quant new_t []) (add_names quant old_t [])
   146     fun aux ((t1 as Const (quant_s, _)) $ (Abs (s, T, t'))) =
   147       t1 $ Abs (s |> String.isPrefix protect_prefix s
   148                    ? perhaps (try (fn _ => hd (lost_names (quant_of quant_s)))),
   149                 T, aux t')
   150       | aux (t1 $ t2) = aux t1 $ aux t2
   151       | aux t = t
   152   in aux new_t end
   153 
   154 (* Forward proof while preserving bound variables names *)
   155 fun rename_bound_vars_RS th rl =
   156   let
   157     val t = concl_of th
   158     val r = concl_of rl
   159     val th' = th RS Thm.rename_boundvars r (protect_bound_var_names r) rl
   160     val t' = concl_of th'
   161   in Thm.rename_boundvars t' (fix_bound_var_names t t') th' end
   162 
   163 (*raises exception if no rules apply*)
   164 fun tryres (th, rls) =
   165   let fun tryall [] = raise THM("tryres", 0, th::rls)
   166         | tryall (rl::rls) =
   167           (rename_bound_vars_RS th rl handle THM _ => tryall rls)
   168   in  tryall rls  end;
   169 
   170 (*Permits forward proof from rules that discharge assumptions. The supplied proof state st,
   171   e.g. from conj_forward, should have the form
   172     "[| P' ==> ?P; Q' ==> ?Q |] ==> ?P & ?Q"
   173   and the effect should be to instantiate ?P and ?Q with normalized versions of P' and Q'.*)
   174 fun forward_res ctxt nf st =
   175   let fun forward_tacf [prem] = rtac (nf prem) 1
   176         | forward_tacf prems =
   177             error (cat_lines
   178               ("Bad proof state in forward_res, please inform lcp@cl.cam.ac.uk:" ::
   179                 Display.string_of_thm ctxt st ::
   180                 "Premises:" :: map (Display.string_of_thm ctxt) prems))
   181   in
   182     case Seq.pull (ALLGOALS (Misc_Legacy.METAHYPS forward_tacf) st)
   183     of SOME(th,_) => th
   184      | NONE => raise THM("forward_res", 0, [st])
   185   end;
   186 
   187 (*Are any of the logical connectives in "bs" present in the term?*)
   188 fun has_conns bs =
   189   let fun has (Const _) = false
   190         | has (Const(@{const_name Trueprop},_) $ p) = has p
   191         | has (Const(@{const_name Not},_) $ p) = has p
   192         | has (Const(@{const_name HOL.disj},_) $ p $ q) = member (op =) bs @{const_name HOL.disj} orelse has p orelse has q
   193         | has (Const(@{const_name HOL.conj},_) $ p $ q) = member (op =) bs @{const_name HOL.conj} orelse has p orelse has q
   194         | has (Const(@{const_name All},_) $ Abs(_,_,p)) = member (op =) bs @{const_name All} orelse has p
   195         | has (Const(@{const_name Ex},_) $ Abs(_,_,p)) = member (op =) bs @{const_name Ex} orelse has p
   196         | has _ = false
   197   in  has  end;
   198 
   199 
   200 (**** Clause handling ****)
   201 
   202 fun literals (Const(@{const_name Trueprop},_) $ P) = literals P
   203   | literals (Const(@{const_name HOL.disj},_) $ P $ Q) = literals P @ literals Q
   204   | literals (Const(@{const_name Not},_) $ P) = [(false,P)]
   205   | literals P = [(true,P)];
   206 
   207 (*number of literals in a term*)
   208 val nliterals = length o literals;
   209 
   210 
   211 (*** Tautology Checking ***)
   212 
   213 fun signed_lits_aux (Const (@{const_name HOL.disj}, _) $ P $ Q) (poslits, neglits) =
   214       signed_lits_aux Q (signed_lits_aux P (poslits, neglits))
   215   | signed_lits_aux (Const(@{const_name Not},_) $ P) (poslits, neglits) = (poslits, P::neglits)
   216   | signed_lits_aux P (poslits, neglits) = (P::poslits, neglits);
   217 
   218 fun signed_lits th = signed_lits_aux (HOLogic.dest_Trueprop (concl_of th)) ([],[]);
   219 
   220 (*Literals like X=X are tautologous*)
   221 fun taut_poslit (Const(@{const_name HOL.eq},_) $ t $ u) = t aconv u
   222   | taut_poslit (Const(@{const_name True},_)) = true
   223   | taut_poslit _ = false;
   224 
   225 fun is_taut th =
   226   let val (poslits,neglits) = signed_lits th
   227   in  exists taut_poslit poslits
   228       orelse
   229       exists (member (op aconv) neglits) (@{term False} :: poslits)
   230   end
   231   handle TERM _ => false;       (*probably dest_Trueprop on a weird theorem*)
   232 
   233 
   234 (*** To remove trivial negated equality literals from clauses ***)
   235 
   236 (*They are typically functional reflexivity axioms and are the converses of
   237   injectivity equivalences*)
   238 
   239 val not_refl_disj_D = @{thm not_refl_disj_D};
   240 
   241 (*Is either term a Var that does not properly occur in the other term?*)
   242 fun eliminable (t as Var _, u) = t aconv u orelse not (Logic.occs(t,u))
   243   | eliminable (u, t as Var _) = t aconv u orelse not (Logic.occs(t,u))
   244   | eliminable _ = false;
   245 
   246 fun refl_clause_aux 0 th = th
   247   | refl_clause_aux n th =
   248        case HOLogic.dest_Trueprop (concl_of th) of
   249           (Const (@{const_name HOL.disj}, _) $ (Const (@{const_name HOL.disj}, _) $ _ $ _) $ _) =>
   250             refl_clause_aux n (th RS disj_assoc)    (*isolate an atom as first disjunct*)
   251         | (Const (@{const_name HOL.disj}, _) $ (Const(@{const_name Not},_) $ (Const(@{const_name HOL.eq},_) $ t $ u)) $ _) =>
   252             if eliminable(t,u)
   253             then refl_clause_aux (n-1) (th RS not_refl_disj_D)  (*Var inequation: delete*)
   254             else refl_clause_aux (n-1) (th RS disj_comm)  (*not between Vars: ignore*)
   255         | (Const (@{const_name HOL.disj}, _) $ _ $ _) => refl_clause_aux n (th RS disj_comm)
   256         | _ => (*not a disjunction*) th;
   257 
   258 fun notequal_lits_count (Const (@{const_name HOL.disj}, _) $ P $ Q) =
   259       notequal_lits_count P + notequal_lits_count Q
   260   | notequal_lits_count (Const(@{const_name Not},_) $ (Const(@{const_name HOL.eq},_) $ _ $ _)) = 1
   261   | notequal_lits_count _ = 0;
   262 
   263 (*Simplify a clause by applying reflexivity to its negated equality literals*)
   264 fun refl_clause th =
   265   let val neqs = notequal_lits_count (HOLogic.dest_Trueprop (concl_of th))
   266   in  zero_var_indexes (refl_clause_aux neqs th)  end
   267   handle TERM _ => th;  (*probably dest_Trueprop on a weird theorem*)
   268 
   269 
   270 (*** Removal of duplicate literals ***)
   271 
   272 (*Forward proof, passing extra assumptions as theorems to the tactic*)
   273 fun forward_res2 nf hyps st =
   274   case Seq.pull
   275         (REPEAT
   276          (Misc_Legacy.METAHYPS (fn major::minors => rtac (nf (minors@hyps) major) 1) 1)
   277          st)
   278   of SOME(th,_) => th
   279    | NONE => raise THM("forward_res2", 0, [st]);
   280 
   281 (*Remove duplicates in P|Q by assuming ~P in Q
   282   rls (initially []) accumulates assumptions of the form P==>False*)
   283 fun nodups_aux ctxt rls th = nodups_aux ctxt rls (th RS disj_assoc)
   284     handle THM _ => tryres(th,rls)
   285     handle THM _ => tryres(forward_res2 (nodups_aux ctxt) rls (th RS disj_forward2),
   286                            [disj_FalseD1, disj_FalseD2, asm_rl])
   287     handle THM _ => th;
   288 
   289 (*Remove duplicate literals, if there are any*)
   290 fun nodups ctxt th =
   291   if has_duplicates (op =) (literals (prop_of th))
   292     then nodups_aux ctxt [] th
   293     else th;
   294 
   295 
   296 (*** The basic CNF transformation ***)
   297 
   298 fun estimated_num_clauses bound t =
   299  let
   300   fun sum x y = if x < bound andalso y < bound then x+y else bound
   301   fun prod x y = if x < bound andalso y < bound then x*y else bound
   302   
   303   (*Estimate the number of clauses in order to detect infeasible theorems*)
   304   fun signed_nclauses b (Const(@{const_name Trueprop},_) $ t) = signed_nclauses b t
   305     | signed_nclauses b (Const(@{const_name Not},_) $ t) = signed_nclauses (not b) t
   306     | signed_nclauses b (Const(@{const_name HOL.conj},_) $ t $ u) =
   307         if b then sum (signed_nclauses b t) (signed_nclauses b u)
   308              else prod (signed_nclauses b t) (signed_nclauses b u)
   309     | signed_nclauses b (Const(@{const_name HOL.disj},_) $ t $ u) =
   310         if b then prod (signed_nclauses b t) (signed_nclauses b u)
   311              else sum (signed_nclauses b t) (signed_nclauses b u)
   312     | signed_nclauses b (Const(@{const_name HOL.implies},_) $ t $ u) =
   313         if b then prod (signed_nclauses (not b) t) (signed_nclauses b u)
   314              else sum (signed_nclauses (not b) t) (signed_nclauses b u)
   315     | signed_nclauses b (Const(@{const_name HOL.eq}, Type ("fun", [T, _])) $ t $ u) =
   316         if T = HOLogic.boolT then (*Boolean equality is if-and-only-if*)
   317             if b then sum (prod (signed_nclauses (not b) t) (signed_nclauses b u))
   318                           (prod (signed_nclauses (not b) u) (signed_nclauses b t))
   319                  else sum (prod (signed_nclauses b t) (signed_nclauses b u))
   320                           (prod (signed_nclauses (not b) t) (signed_nclauses (not b) u))
   321         else 1
   322     | signed_nclauses b (Const(@{const_name Ex}, _) $ Abs (_,_,t)) = signed_nclauses b t
   323     | signed_nclauses b (Const(@{const_name All},_) $ Abs (_,_,t)) = signed_nclauses b t
   324     | signed_nclauses _ _ = 1; (* literal *)
   325  in signed_nclauses true t end
   326 
   327 fun has_too_many_clauses ctxt t =
   328   let val max_cl = Config.get ctxt max_clauses in
   329     estimated_num_clauses (max_cl + 1) t > max_cl
   330   end
   331 
   332 (*Replaces universally quantified variables by FREE variables -- because
   333   assumptions may not contain scheme variables.  Later, generalize using Variable.export. *)
   334 local  
   335   val spec_var = Thm.dest_arg (Thm.dest_arg (#2 (Thm.dest_implies (Thm.cprop_of spec))));
   336   val spec_varT = #T (Thm.rep_cterm spec_var);
   337   fun name_of (Const (@{const_name All}, _) $ Abs(x,_,_)) = x | name_of _ = Name.uu;
   338 in  
   339   fun freeze_spec th ctxt =
   340     let
   341       val cert = Thm.cterm_of (Proof_Context.theory_of ctxt);
   342       val ([x], ctxt') = Variable.variant_fixes [name_of (HOLogic.dest_Trueprop (concl_of th))] ctxt;
   343       val spec' = Thm.instantiate ([], [(spec_var, cert (Free (x, spec_varT)))]) spec;
   344     in (th RS spec', ctxt') end
   345 end;
   346 
   347 (*Used with METAHYPS below. There is one assumption, which gets bound to prem
   348   and then normalized via function nf. The normal form is given to resolve_tac,
   349   instantiate a Boolean variable created by resolution with disj_forward. Since
   350   (nf prem) returns a LIST of theorems, we can backtrack to get all combinations.*)
   351 fun resop nf [prem] = resolve_tac (nf prem) 1;
   352 
   353 (* Any need to extend this list with "HOL.type_class", "HOL.eq_class",
   354    and "Pure.term"? *)
   355 val has_meta_conn = exists_Const (member (op =) ["==", "==>", "=simp=>", "all", "prop"] o #1);
   356 
   357 fun apply_skolem_theorem (th, rls) =
   358   let
   359     fun tryall [] = raise THM ("apply_skolem_theorem", 0, th::rls)
   360       | tryall (rl :: rls) =
   361         first_order_resolve th rl handle THM _ => tryall rls
   362   in tryall rls end
   363 
   364 (* Conjunctive normal form, adding clauses from th in front of ths (for foldr).
   365    Strips universal quantifiers and breaks up conjunctions.
   366    Eliminates existential quantifiers using Skolemization theorems. *)
   367 fun cnf old_skolem_ths ctxt ctxt0 (th, ths) =
   368   let val ctxt0r = Unsynchronized.ref ctxt0   (* FIXME ??? *)
   369       fun cnf_aux (th,ths) =
   370         if not (can HOLogic.dest_Trueprop (prop_of th)) then ths (*meta-level: ignore*)
   371         else if not (has_conns [@{const_name All}, @{const_name Ex}, @{const_name HOL.conj}] (prop_of th))
   372         then nodups ctxt0 th :: ths (*no work to do, terminate*)
   373         else case head_of (HOLogic.dest_Trueprop (concl_of th)) of
   374             Const (@{const_name HOL.conj}, _) => (*conjunction*)
   375                 cnf_aux (th RS conjunct1, cnf_aux (th RS conjunct2, ths))
   376           | Const (@{const_name All}, _) => (*universal quantifier*)
   377                 let val (th',ctxt0') = freeze_spec th (!ctxt0r)
   378                 in  ctxt0r := ctxt0'; cnf_aux (th', ths) end
   379           | Const (@{const_name Ex}, _) =>
   380               (*existential quantifier: Insert Skolem functions*)
   381               cnf_aux (apply_skolem_theorem (th, old_skolem_ths), ths)
   382           | Const (@{const_name HOL.disj}, _) =>
   383               (*Disjunction of P, Q: Create new goal of proving ?P | ?Q and solve it using
   384                 all combinations of converting P, Q to CNF.*)
   385               let val tac =
   386                   Misc_Legacy.METAHYPS (resop cnf_nil) 1 THEN
   387                    (fn st' => st' |> Misc_Legacy.METAHYPS (resop cnf_nil) 1)
   388               in  Seq.list_of (tac (th RS disj_forward)) @ ths  end
   389           | _ => nodups ctxt0 th :: ths  (*no work to do*)
   390       and cnf_nil th = cnf_aux (th,[])
   391       val cls =
   392         if has_too_many_clauses ctxt (concl_of th) then
   393           (trace_msg ctxt (fn () =>
   394                "cnf is ignoring: " ^ Display.string_of_thm ctxt0 th); ths)
   395         else
   396           cnf_aux (th, ths)
   397   in (cls, !ctxt0r) end
   398 fun make_cnf old_skolem_ths th ctxt ctxt0 =
   399   cnf old_skolem_ths ctxt ctxt0 (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 (*The simplification removes defined quantifiers and occurrences of True and False.
   567   nnf_ss also includes the one-point simprocs,
   568   which are needed to avoid the various one-point theorems from generating junk clauses.*)
   569 val nnf_simps =
   570   @{thms simp_implies_def Ex1_def Ball_def Bex_def if_True if_False if_cancel
   571          if_eq_cancel cases_simp}
   572 val nnf_extra_simps = @{thms split_ifs ex_simps all_simps simp_thms}
   573 
   574 (* FIXME: "let_simp" is probably redundant now that we also rewrite with
   575   "Let_def_raw". *)
   576 val nnf_ss =
   577   HOL_basic_ss addsimps nnf_extra_simps
   578     addsimprocs [@{simproc defined_All}, @{simproc defined_Ex}, @{simproc neq},
   579                  @{simproc let_simp}]
   580 
   581 fun presimplified_consts ctxt =
   582   [@{const_name simp_implies}, @{const_name False}, @{const_name True},
   583    @{const_name Ex1}, @{const_name Ball}, @{const_name Bex}, @{const_name If},
   584    @{const_name Let}]
   585 
   586 fun presimplify ctxt =
   587   rewrite_rule (map safe_mk_meta_eq nnf_simps)
   588   #> simplify nnf_ss
   589   #> Raw_Simplifier.rewrite_rule @{thms Let_def_raw}
   590 
   591 fun make_nnf ctxt th = case prems_of th of
   592     [] => th |> presimplify ctxt |> make_nnf1 ctxt
   593   | _ => raise THM ("make_nnf: premises in argument", 0, [th]);
   594 
   595 fun choice_theorems thy =
   596   try (Global_Theory.get_thm thy) "Hilbert_Choice.choice" |> the_list
   597 
   598 (* Pull existential quantifiers to front. This accomplishes Skolemization for
   599    clauses that arise from a subgoal. *)
   600 fun skolemize_with_choice_theorems ctxt choice_ths =
   601   let
   602     fun aux th =
   603       if not (has_conns [@{const_name Ex}] (prop_of th)) then
   604         th
   605       else
   606         tryres (th, choice_ths @
   607                     [conj_exD1, conj_exD2, disj_exD, disj_exD1, disj_exD2])
   608         |> aux
   609         handle THM ("tryres", _, _) =>
   610                tryres (th, [conj_forward, disj_forward, all_forward])
   611                |> forward_res ctxt aux
   612                |> aux
   613                handle THM ("tryres", _, _) =>
   614                       rename_bound_vars_RS th ex_forward
   615                       |> forward_res ctxt aux
   616   in aux o make_nnf ctxt end
   617 
   618 fun skolemize ctxt =
   619   let val thy = Proof_Context.theory_of ctxt in
   620     skolemize_with_choice_theorems ctxt (choice_theorems thy)
   621   end
   622 
   623 (* Removes the lambdas from an equation of the form "t = (%x1 ... xn. u)". It
   624    would be desirable to do this symmetrically but there's at least one existing
   625    proof in "Tarski" that relies on the current behavior. *)
   626 fun extensionalize_conv ctxt ct =
   627   case term_of ct of
   628     Const (@{const_name HOL.eq}, _) $ _ $ Abs _ =>
   629     ct |> (Conv.rewr_conv @{thm fun_eq_iff [THEN eq_reflection]}
   630            then_conv extensionalize_conv ctxt)
   631   | _ $ _ => Conv.comb_conv (extensionalize_conv ctxt) ct
   632   | Abs _ => Conv.abs_conv (extensionalize_conv o snd) ctxt ct
   633   | _ => Conv.all_conv ct
   634 
   635 val extensionalize_theorem = Conv.fconv_rule o extensionalize_conv
   636 
   637 (* "RS" can fail if "unify_search_bound" is too small. *)
   638 fun try_skolemize_etc ctxt th =
   639   (* Extensionalize "th", because that makes sense and that's what Sledgehammer
   640      does, but also keep an unextensionalized version of "th" for backward
   641      compatibility. *)
   642   [th] |> insert Thm.eq_thm_prop (extensionalize_theorem ctxt th)
   643        |> map_filter (fn th => th |> try (skolemize ctxt)
   644                                   |> tap (fn NONE =>
   645                                              trace_msg ctxt (fn () =>
   646                                                  "Failed to skolemize " ^
   647                                                   Display.string_of_thm ctxt th)
   648                                            | _ => ()))
   649 
   650 fun add_clauses ctxt th cls =
   651   let val ctxt0 = Variable.global_thm_context th
   652       val (cnfs, ctxt) = make_cnf [] th ctxt ctxt0
   653   in Variable.export ctxt ctxt0 cnfs @ cls end;
   654 
   655 (*Make clauses from a list of theorems, previously Skolemized and put into nnf.
   656   The resulting clauses are HOL disjunctions.*)
   657 fun make_clauses_unsorted ctxt ths = fold_rev (add_clauses ctxt) ths [];
   658 val make_clauses = sort_clauses oo make_clauses_unsorted;
   659 
   660 (*Convert a list of clauses (disjunctions) to Horn clauses (contrapositives)*)
   661 fun make_horns ths =
   662     name_thms "Horn#"
   663       (distinct Thm.eq_thm_prop (fold_rev (add_contras clause_rules) ths []));
   664 
   665 (*Could simply use nprems_of, which would count remaining subgoals -- no
   666   discrimination as to their size!  With BEST_FIRST, fails for problem 41.*)
   667 
   668 fun best_prolog_tac sizef horns =
   669     BEST_FIRST (has_fewer_prems 1, sizef) (prolog_step_tac horns 1);
   670 
   671 fun depth_prolog_tac horns =
   672     DEPTH_FIRST (has_fewer_prems 1) (prolog_step_tac horns 1);
   673 
   674 (*Return all negative clauses, as possible goal clauses*)
   675 fun gocls cls = name_thms "Goal#" (map make_goal (neg_clauses cls));
   676 
   677 fun skolemize_prems_tac ctxt prems =
   678   cut_facts_tac (maps (try_skolemize_etc ctxt) prems) THEN' REPEAT o etac exE
   679 
   680 (*Basis of all meson-tactics.  Supplies cltac with clauses: HOL disjunctions.
   681   Function mkcl converts theorems to clauses.*)
   682 fun MESON preskolem_tac mkcl cltac ctxt i st =
   683   SELECT_GOAL
   684     (EVERY [Object_Logic.atomize_prems_tac 1,
   685             rtac ccontr 1,
   686             preskolem_tac,
   687             Subgoal.FOCUS (fn {context = ctxt', prems = negs, ...} =>
   688                       EVERY1 [skolemize_prems_tac ctxt negs,
   689                               Subgoal.FOCUS (cltac o mkcl o #prems) ctxt']) ctxt 1]) i st
   690   handle THM _ => no_tac st;    (*probably from make_meta_clause, not first-order*)
   691 
   692 
   693 (** Best-first search versions **)
   694 
   695 (*ths is a list of additional clauses (HOL disjunctions) to use.*)
   696 fun best_meson_tac sizef ctxt =
   697   MESON all_tac (make_clauses ctxt)
   698     (fn cls =>
   699          THEN_BEST_FIRST (resolve_tac (gocls cls) 1)
   700                          (has_fewer_prems 1, sizef)
   701                          (prolog_step_tac (make_horns cls) 1))
   702     ctxt
   703 
   704 (*First, breaks the goal into independent units*)
   705 fun safe_best_meson_tac ctxt =
   706   SELECT_GOAL (TRY (safe_tac ctxt) THEN TRYALL (best_meson_tac size_of_subgoals ctxt));
   707 
   708 (** Depth-first search version **)
   709 
   710 fun depth_meson_tac ctxt =
   711   MESON all_tac (make_clauses ctxt)
   712     (fn cls => EVERY [resolve_tac (gocls cls) 1, depth_prolog_tac (make_horns cls)])
   713     ctxt
   714 
   715 (** Iterative deepening version **)
   716 
   717 (*This version does only one inference per call;
   718   having only one eq_assume_tac speeds it up!*)
   719 fun prolog_step_tac' horns =
   720     let val (horn0s, _) = (*0 subgoals vs 1 or more*)
   721             take_prefix Thm.no_prems horns
   722         val nrtac = net_resolve_tac horns
   723     in  fn i => eq_assume_tac i ORELSE
   724                 match_tac horn0s i ORELSE  (*no backtracking if unit MATCHES*)
   725                 ((assume_tac i APPEND nrtac i) THEN check_tac)
   726     end;
   727 
   728 fun iter_deepen_prolog_tac horns =
   729     ITER_DEEPEN iter_deepen_limit (has_fewer_prems 1) (prolog_step_tac' horns);
   730 
   731 fun iter_deepen_meson_tac ctxt ths = ctxt |> MESON all_tac (make_clauses ctxt)
   732   (fn cls =>
   733     (case (gocls (cls @ ths)) of
   734       [] => no_tac  (*no goal clauses*)
   735     | goes =>
   736         let
   737           val horns = make_horns (cls @ ths)
   738           val _ = trace_msg ctxt (fn () =>
   739             cat_lines ("meson method called:" ::
   740               map (Display.string_of_thm ctxt) (cls @ ths) @
   741               ["clauses:"] @ map (Display.string_of_thm ctxt) horns))
   742         in
   743           THEN_ITER_DEEPEN iter_deepen_limit
   744             (resolve_tac goes 1) (has_fewer_prems 1) (prolog_step_tac' horns)
   745         end));
   746 
   747 fun meson_tac ctxt ths =
   748   SELECT_GOAL (TRY (safe_tac ctxt) THEN TRYALL (iter_deepen_meson_tac ctxt ths));
   749 
   750 
   751 (**** Code to support ordinary resolution, rather than Model Elimination ****)
   752 
   753 (*Convert a list of clauses (disjunctions) to meta-level clauses (==>),
   754   with no contrapositives, for ordinary resolution.*)
   755 
   756 (*Rules to convert the head literal into a negated assumption. If the head
   757   literal is already negated, then using notEfalse instead of notEfalse'
   758   prevents a double negation.*)
   759 val notEfalse = read_instantiate @{context} [(("R", 0), "False")] notE;
   760 val notEfalse' = rotate_prems 1 notEfalse;
   761 
   762 fun negated_asm_of_head th =
   763     th RS notEfalse handle THM _ => th RS notEfalse';
   764 
   765 (*Converting one theorem from a disjunction to a meta-level clause*)
   766 fun make_meta_clause th =
   767   let val (fth,thaw) = Drule.legacy_freeze_thaw_robust th
   768   in  
   769       (zero_var_indexes o Thm.varifyT_global o thaw 0 o 
   770        negated_asm_of_head o make_horn resolution_clause_rules) fth
   771   end;
   772 
   773 fun make_meta_clauses ths =
   774     name_thms "MClause#"
   775       (distinct Thm.eq_thm_prop (map make_meta_clause ths));
   776 
   777 end;