src/HOL/Tools/Meson/meson.ML
author wenzelm
Sun Nov 26 21:08:32 2017 +0100 (19 months ago)
changeset 67091 1393c2340eec
parent 61268 abe08fb15a12
child 67149 e61557884799
permissions -rw-r--r--
more symbols;
     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 first_order_resolve : Proof.context -> thm -> thm -> thm
    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 presimplified_consts : string list
    19   val presimplify: Proof.context -> thm -> thm
    20   val make_nnf: Proof.context -> thm -> thm
    21   val choice_theorems : theory -> thm list
    22   val skolemize_with_choice_theorems : Proof.context -> thm list -> thm -> thm
    23   val skolemize : Proof.context -> thm -> thm
    24   val cong_extensionalize_thm : Proof.context -> thm -> thm
    25   val abs_extensionalize_conv : Proof.context -> conv
    26   val abs_extensionalize_thm : Proof.context -> thm -> thm
    27   val make_clauses_unsorted: Proof.context -> thm list -> thm list
    28   val make_clauses: Proof.context -> thm list -> thm list
    29   val make_horns: thm list -> thm list
    30   val best_prolog_tac: Proof.context -> (thm -> int) -> thm list -> tactic
    31   val depth_prolog_tac: Proof.context -> thm list -> tactic
    32   val gocls: thm list -> thm list
    33   val skolemize_prems_tac : Proof.context -> thm list -> int -> tactic
    34   val MESON:
    35     tactic -> (thm list -> thm list) -> (thm list -> tactic) -> Proof.context
    36     -> int -> tactic
    37   val best_meson_tac: (thm -> int) -> Proof.context -> int -> tactic
    38   val safe_best_meson_tac: Proof.context -> int -> tactic
    39   val depth_meson_tac: Proof.context -> int -> tactic
    40   val prolog_step_tac': Proof.context -> thm list -> int -> tactic
    41   val iter_deepen_prolog_tac: Proof.context -> thm list -> tactic
    42   val iter_deepen_meson_tac: Proof.context -> thm list -> int -> tactic
    43   val make_meta_clause: Proof.context -> thm -> thm
    44   val make_meta_clauses: Proof.context -> thm list -> thm list
    45   val meson_tac: Proof.context -> thm list -> int -> tactic
    46 end
    47 
    48 structure Meson : MESON =
    49 struct
    50 
    51 val trace = Attrib.setup_config_bool @{binding meson_trace} (K false)
    52 
    53 fun trace_msg ctxt msg = if Config.get ctxt trace then tracing (msg ()) else ()
    54 
    55 val max_clauses = Attrib.setup_config_int @{binding meson_max_clauses} (K 60)
    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 (*FIXME: currently does not "rename variables apart"*)
    98 fun first_order_resolve ctxt thA thB =
    99   (case
   100     try (fn () =>
   101       let val thy = Proof_Context.theory_of ctxt
   102           val tmA = Thm.concl_of thA
   103           val Const(@{const_name Pure.imp},_) $ tmB $ _ = Thm.prop_of thB
   104           val tenv =
   105             Pattern.first_order_match thy (tmB, tmA)
   106                                           (Vartab.empty, Vartab.empty) |> snd
   107           val insts = Vartab.fold (fn (xi, (_, t)) => cons (xi, Thm.cterm_of ctxt t)) tenv [];
   108       in  thA RS (infer_instantiate ctxt insts 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 = Thm.concl_of th
   153     val r = Thm.concl_of rl
   154     val th' = th RS Thm.rename_boundvars r (protect_bound_var_names r) rl
   155     val t' = Thm.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 (* Special version of "resolve_tac" that works around an explosion in the unifier.
   166    If the goal has the form "?P c", the danger is that resolving it against a
   167    property of the form "... c ... c ... c ..." will lead to a huge unification
   168    problem, due to the (spurious) choices between projection and imitation. The
   169    workaround is to instantiate "?P := (%c. ... c ... c ... c ...)" manually. *)
   170 fun quant_resolve_tac ctxt th i st =
   171   case (Thm.concl_of st, Thm.prop_of th) of
   172     (@{const Trueprop} $ (Var _ $ (c as Free _)), @{const Trueprop} $ _) =>
   173     let
   174       val cc = Thm.cterm_of ctxt c
   175       val ct = Thm.dest_arg (Thm.cprop_of th)
   176     in resolve_tac ctxt [th] i (Thm.instantiate' [] [SOME (Thm.lambda cc ct)] st) end
   177   | _ => resolve_tac ctxt [th] i st
   178 
   179 (*Permits forward proof from rules that discharge assumptions. The supplied proof state st,
   180   e.g. from conj_forward, should have the form
   181     "[| P' ==> ?P; Q' ==> ?Q |] ==> ?P & ?Q"
   182   and the effect should be to instantiate ?P and ?Q with normalized versions of P' and Q'.*)
   183 fun forward_res ctxt nf st =
   184   let
   185     fun tacf [prem] = quant_resolve_tac ctxt (nf prem) 1
   186       | tacf prems =
   187         error (cat_lines
   188           ("Bad proof state in forward_res, please inform lcp@cl.cam.ac.uk:" ::
   189             Thm.string_of_thm ctxt st ::
   190             "Premises:" :: map (Thm.string_of_thm ctxt) prems))
   191   in
   192     case Seq.pull (ALLGOALS (Misc_Legacy.METAHYPS ctxt tacf) st) of
   193       SOME (th, _) => th
   194     | NONE => raise THM ("forward_res", 0, [st])
   195   end;
   196 
   197 (*Are any of the logical connectives in "bs" present in the term?*)
   198 fun has_conns bs =
   199   let fun has (Const _) = false
   200         | has (Const(@{const_name Trueprop},_) $ p) = has p
   201         | has (Const(@{const_name Not},_) $ p) = has p
   202         | has (Const(@{const_name HOL.disj},_) $ p $ q) = member (op =) bs @{const_name HOL.disj} orelse has p orelse has q
   203         | has (Const(@{const_name HOL.conj},_) $ p $ q) = member (op =) bs @{const_name HOL.conj} orelse has p orelse has q
   204         | has (Const(@{const_name All},_) $ Abs(_,_,p)) = member (op =) bs @{const_name All} orelse has p
   205         | has (Const(@{const_name Ex},_) $ Abs(_,_,p)) = member (op =) bs @{const_name Ex} orelse has p
   206         | has _ = false
   207   in  has  end;
   208 
   209 
   210 (**** Clause handling ****)
   211 
   212 fun literals (Const(@{const_name Trueprop},_) $ P) = literals P
   213   | literals (Const(@{const_name HOL.disj},_) $ P $ Q) = literals P @ literals Q
   214   | literals (Const(@{const_name Not},_) $ P) = [(false,P)]
   215   | literals P = [(true,P)];
   216 
   217 (*number of literals in a term*)
   218 val nliterals = length o literals;
   219 
   220 
   221 (*** Tautology Checking ***)
   222 
   223 fun signed_lits_aux (Const (@{const_name HOL.disj}, _) $ P $ Q) (poslits, neglits) =
   224       signed_lits_aux Q (signed_lits_aux P (poslits, neglits))
   225   | signed_lits_aux (Const(@{const_name Not},_) $ P) (poslits, neglits) = (poslits, P::neglits)
   226   | signed_lits_aux P (poslits, neglits) = (P::poslits, neglits);
   227 
   228 fun signed_lits th = signed_lits_aux (HOLogic.dest_Trueprop (Thm.concl_of th)) ([],[]);
   229 
   230 (*Literals like X=X are tautologous*)
   231 fun taut_poslit (Const(@{const_name HOL.eq},_) $ t $ u) = t aconv u
   232   | taut_poslit (Const(@{const_name True},_)) = true
   233   | taut_poslit _ = false;
   234 
   235 fun is_taut th =
   236   let val (poslits,neglits) = signed_lits th
   237   in  exists taut_poslit poslits
   238       orelse
   239       exists (member (op aconv) neglits) (@{term False} :: poslits)
   240   end
   241   handle TERM _ => false;       (*probably dest_Trueprop on a weird theorem*)
   242 
   243 
   244 (*** To remove trivial negated equality literals from clauses ***)
   245 
   246 (*They are typically functional reflexivity axioms and are the converses of
   247   injectivity equivalences*)
   248 
   249 val not_refl_disj_D = @{thm not_refl_disj_D};
   250 
   251 (*Is either term a Var that does not properly occur in the other term?*)
   252 fun eliminable (t as Var _, u) = t aconv u orelse not (Logic.occs(t,u))
   253   | eliminable (u, t as Var _) = t aconv u orelse not (Logic.occs(t,u))
   254   | eliminable _ = false;
   255 
   256 fun refl_clause_aux 0 th = th
   257   | refl_clause_aux n th =
   258        case HOLogic.dest_Trueprop (Thm.concl_of th) of
   259           (Const (@{const_name HOL.disj}, _) $ (Const (@{const_name HOL.disj}, _) $ _ $ _) $ _) =>
   260             refl_clause_aux n (th RS disj_assoc)    (*isolate an atom as first disjunct*)
   261         | (Const (@{const_name HOL.disj}, _) $ (Const(@{const_name Not},_) $ (Const(@{const_name HOL.eq},_) $ t $ u)) $ _) =>
   262             if eliminable(t,u)
   263             then refl_clause_aux (n-1) (th RS not_refl_disj_D)  (*Var inequation: delete*)
   264             else refl_clause_aux (n-1) (th RS disj_comm)  (*not between Vars: ignore*)
   265         | (Const (@{const_name HOL.disj}, _) $ _ $ _) => refl_clause_aux n (th RS disj_comm)
   266         | _ => (*not a disjunction*) th;
   267 
   268 fun notequal_lits_count (Const (@{const_name HOL.disj}, _) $ P $ Q) =
   269       notequal_lits_count P + notequal_lits_count Q
   270   | notequal_lits_count (Const(@{const_name Not},_) $ (Const(@{const_name HOL.eq},_) $ _ $ _)) = 1
   271   | notequal_lits_count _ = 0;
   272 
   273 (*Simplify a clause by applying reflexivity to its negated equality literals*)
   274 fun refl_clause th =
   275   let val neqs = notequal_lits_count (HOLogic.dest_Trueprop (Thm.concl_of th))
   276   in  zero_var_indexes (refl_clause_aux neqs th)  end
   277   handle TERM _ => th;  (*probably dest_Trueprop on a weird theorem*)
   278 
   279 
   280 (*** Removal of duplicate literals ***)
   281 
   282 (*Forward proof, passing extra assumptions as theorems to the tactic*)
   283 fun forward_res2 ctxt nf hyps st =
   284   case Seq.pull
   285         (REPEAT
   286          (Misc_Legacy.METAHYPS ctxt
   287            (fn major::minors => resolve_tac ctxt [nf (minors @ hyps) major] 1) 1)
   288          st)
   289   of SOME(th,_) => th
   290    | NONE => raise THM("forward_res2", 0, [st]);
   291 
   292 (*Remove duplicates in P|Q by assuming ~P in Q
   293   rls (initially []) accumulates assumptions of the form P==>False*)
   294 fun nodups_aux ctxt rls th = nodups_aux ctxt rls (th RS disj_assoc)
   295     handle THM _ => tryres(th,rls)
   296     handle THM _ => tryres(forward_res2 ctxt (nodups_aux ctxt) rls (th RS disj_forward2),
   297                            [disj_FalseD1, disj_FalseD2, asm_rl])
   298     handle THM _ => th;
   299 
   300 (*Remove duplicate literals, if there are any*)
   301 fun nodups ctxt th =
   302   if has_duplicates (op =) (literals (Thm.prop_of th))
   303     then nodups_aux ctxt [] th
   304     else th;
   305 
   306 
   307 (*** The basic CNF transformation ***)
   308 
   309 fun estimated_num_clauses bound t =
   310  let
   311   fun sum x y = if x < bound andalso y < bound then x+y else bound
   312   fun prod x y = if x < bound andalso y < bound then x*y else bound
   313   
   314   (*Estimate the number of clauses in order to detect infeasible theorems*)
   315   fun signed_nclauses b (Const(@{const_name Trueprop},_) $ t) = signed_nclauses b t
   316     | signed_nclauses b (Const(@{const_name Not},_) $ t) = signed_nclauses (not b) t
   317     | signed_nclauses b (Const(@{const_name HOL.conj},_) $ t $ u) =
   318         if b then sum (signed_nclauses b t) (signed_nclauses b u)
   319              else prod (signed_nclauses b t) (signed_nclauses b u)
   320     | signed_nclauses b (Const(@{const_name HOL.disj},_) $ t $ u) =
   321         if b then prod (signed_nclauses b t) (signed_nclauses b u)
   322              else sum (signed_nclauses b t) (signed_nclauses b u)
   323     | signed_nclauses b (Const(@{const_name HOL.implies},_) $ t $ u) =
   324         if b then prod (signed_nclauses (not b) t) (signed_nclauses b u)
   325              else sum (signed_nclauses (not b) t) (signed_nclauses b u)
   326     | signed_nclauses b (Const(@{const_name HOL.eq}, Type ("fun", [T, _])) $ t $ u) =
   327         if T = HOLogic.boolT then (*Boolean equality is if-and-only-if*)
   328             if b then sum (prod (signed_nclauses (not b) t) (signed_nclauses b u))
   329                           (prod (signed_nclauses (not b) u) (signed_nclauses b t))
   330                  else sum (prod (signed_nclauses b t) (signed_nclauses b u))
   331                           (prod (signed_nclauses (not b) t) (signed_nclauses (not b) u))
   332         else 1
   333     | signed_nclauses b (Const(@{const_name Ex}, _) $ Abs (_,_,t)) = signed_nclauses b t
   334     | signed_nclauses b (Const(@{const_name All},_) $ Abs (_,_,t)) = signed_nclauses b t
   335     | signed_nclauses _ _ = 1; (* literal *)
   336  in signed_nclauses true t end
   337 
   338 fun has_too_many_clauses ctxt t =
   339   let val max_cl = Config.get ctxt max_clauses in
   340     estimated_num_clauses (max_cl + 1) t > max_cl
   341   end
   342 
   343 (*Replaces universally quantified variables by FREE variables -- because
   344   assumptions may not contain scheme variables.  Later, generalize using Variable.export. *)
   345 local  
   346   val spec_var =
   347     Thm.dest_arg (Thm.dest_arg (#2 (Thm.dest_implies (Thm.cprop_of spec))))
   348     |> Thm.term_of |> dest_Var;
   349   fun name_of (Const (@{const_name All}, _) $ Abs(x, _, _)) = x | name_of _ = Name.uu;
   350 in  
   351   fun freeze_spec th ctxt =
   352     let
   353       val ([x], ctxt') =
   354         Variable.variant_fixes [name_of (HOLogic.dest_Trueprop (Thm.concl_of th))] ctxt;
   355       val spec' = spec
   356         |> Thm.instantiate ([], [(spec_var, Thm.cterm_of ctxt' (Free (x, snd spec_var)))]);
   357     in (th RS spec', ctxt') end
   358 end;
   359 
   360 fun apply_skolem_theorem ctxt (th, rls) =
   361   let
   362     fun tryall [] = raise THM ("apply_skolem_theorem", 0, th::rls)
   363       | tryall (rl :: rls) = first_order_resolve ctxt th rl handle THM _ => tryall rls
   364   in tryall rls end
   365 
   366 (* Conjunctive normal form, adding clauses from th in front of ths (for foldr).
   367    Strips universal quantifiers and breaks up conjunctions.
   368    Eliminates existential quantifiers using Skolemization theorems. *)
   369 fun cnf old_skolem_ths ctxt (th, ths) =
   370   let val ctxt_ref = Unsynchronized.ref ctxt   (* FIXME ??? *)
   371       fun cnf_aux (th,ths) =
   372         if not (can HOLogic.dest_Trueprop (Thm.prop_of th)) then ths (*meta-level: ignore*)
   373         else if not (has_conns [@{const_name All}, @{const_name Ex}, @{const_name HOL.conj}] (Thm.prop_of th))
   374         then nodups ctxt th :: ths (*no work to do, terminate*)
   375         else case head_of (HOLogic.dest_Trueprop (Thm.concl_of th)) of
   376             Const (@{const_name HOL.conj}, _) => (*conjunction*)
   377                 cnf_aux (th RS conjunct1, cnf_aux (th RS conjunct2, ths))
   378           | Const (@{const_name All}, _) => (*universal quantifier*)
   379                 let val (th', ctxt') = freeze_spec th (! ctxt_ref)
   380                 in  ctxt_ref := ctxt'; cnf_aux (th', ths) end
   381           | Const (@{const_name Ex}, _) =>
   382               (*existential quantifier: Insert Skolem functions*)
   383               cnf_aux (apply_skolem_theorem (! ctxt_ref) (th, old_skolem_ths), ths)
   384           | Const (@{const_name HOL.disj}, _) =>
   385               (*Disjunction of P, Q: Create new goal of proving ?P | ?Q and solve it using
   386                 all combinations of converting P, Q to CNF.*)
   387               (*There is one assumption, which gets bound to prem and then normalized via
   388                 cnf_nil. The normal form is given to resolve_tac, instantiate a Boolean
   389                 variable created by resolution with disj_forward. Since (cnf_nil prem)
   390                 returns a LIST of theorems, we can backtrack to get all combinations.*)
   391               let val tac = Misc_Legacy.METAHYPS ctxt (fn [prem] => resolve_tac ctxt (cnf_nil prem) 1) 1
   392               in  Seq.list_of ((tac THEN tac) (th RS disj_forward)) @ ths  end
   393           | _ => nodups ctxt th :: ths  (*no work to do*)
   394       and cnf_nil th = cnf_aux (th, [])
   395       val cls =
   396         if has_too_many_clauses ctxt (Thm.concl_of th) then
   397           (trace_msg ctxt (fn () =>
   398                "cnf is ignoring: " ^ Thm.string_of_thm ctxt th); ths)
   399         else
   400           cnf_aux (th, ths)
   401   in (cls, !ctxt_ref) end
   402 
   403 fun make_cnf old_skolem_ths th ctxt =
   404   cnf old_skolem_ths ctxt (th, [])
   405 
   406 (*Generalization, removal of redundant equalities, removal of tautologies.*)
   407 fun finish_cnf ths = filter (not o is_taut) (map refl_clause ths);
   408 
   409 
   410 (**** Generation of contrapositives ****)
   411 
   412 fun is_left (Const (@{const_name Trueprop}, _) $
   413                (Const (@{const_name HOL.disj}, _) $ (Const (@{const_name HOL.disj}, _) $ _ $ _) $ _)) = true
   414   | is_left _ = false;
   415 
   416 (*Associate disjuctions to right -- make leftmost disjunct a LITERAL*)
   417 fun assoc_right th =
   418   if is_left (Thm.prop_of th) then assoc_right (th RS disj_assoc)
   419   else th;
   420 
   421 (*Must check for negative literal first!*)
   422 val clause_rules = [disj_assoc, make_neg_rule, make_pos_rule];
   423 
   424 (*For ordinary resolution. *)
   425 val resolution_clause_rules = [disj_assoc, make_neg_rule', make_pos_rule'];
   426 
   427 (*Create a goal or support clause, conclusing False*)
   428 fun make_goal th =   (*Must check for negative literal first!*)
   429     make_goal (tryres(th, clause_rules))
   430   handle THM _ => tryres(th, [make_neg_goal, make_pos_goal]);
   431 
   432 fun rigid t = not (is_Var (head_of t));
   433 
   434 fun ok4horn (Const (@{const_name Trueprop},_) $ (Const (@{const_name HOL.disj}, _) $ t $ _)) = rigid t
   435   | ok4horn (Const (@{const_name Trueprop},_) $ t) = rigid t
   436   | ok4horn _ = false;
   437 
   438 (*Create a meta-level Horn clause*)
   439 fun make_horn crules th =
   440   if ok4horn (Thm.concl_of th)
   441   then make_horn crules (tryres(th,crules)) handle THM _ => th
   442   else th;
   443 
   444 (*Generate Horn clauses for all contrapositives of a clause. The input, th,
   445   is a HOL disjunction.*)
   446 fun add_contras crules th hcs =
   447   let fun rots (0,_) = hcs
   448         | rots (k,th) = zero_var_indexes (make_horn crules th) ::
   449                         rots(k-1, assoc_right (th RS disj_comm))
   450   in case nliterals(Thm.prop_of th) of
   451         1 => th::hcs
   452       | n => rots(n, assoc_right th)
   453   end;
   454 
   455 (*Use "theorem naming" to label the clauses*)
   456 fun name_thms label =
   457     let fun name1 th (k, ths) =
   458           (k-1, Thm.put_name_hint (label ^ string_of_int k) th :: ths)
   459     in  fn ths => #2 (fold_rev name1 ths (length ths, []))  end;
   460 
   461 (*Is the given disjunction an all-negative support clause?*)
   462 fun is_negative th = forall (not o #1) (literals (Thm.prop_of th));
   463 
   464 val neg_clauses = filter is_negative;
   465 
   466 
   467 (***** MESON PROOF PROCEDURE *****)
   468 
   469 fun rhyps (Const(@{const_name Pure.imp},_) $ (Const(@{const_name Trueprop},_) $ A) $ phi,
   470            As) = rhyps(phi, A::As)
   471   | rhyps (_, As) = As;
   472 
   473 (** Detecting repeated assumptions in a subgoal **)
   474 
   475 (*The stringtree detects repeated assumptions.*)
   476 fun ins_term t net = Net.insert_term (op aconv) (t, t) net;
   477 
   478 (*detects repetitions in a list of terms*)
   479 fun has_reps [] = false
   480   | has_reps [_] = false
   481   | has_reps [t,u] = (t aconv u)
   482   | has_reps ts = (fold ins_term ts Net.empty; false) handle Net.INSERT => true;
   483 
   484 (*Like TRYALL eq_assume_tac, but avoids expensive THEN calls*)
   485 fun TRYING_eq_assume_tac 0 st = Seq.single st
   486   | TRYING_eq_assume_tac i st =
   487        TRYING_eq_assume_tac (i-1) (Thm.eq_assumption i st)
   488        handle THM _ => TRYING_eq_assume_tac (i-1) st;
   489 
   490 fun TRYALL_eq_assume_tac st = TRYING_eq_assume_tac (Thm.nprems_of st) st;
   491 
   492 (*Loop checking: FAIL if trying to prove the same thing twice
   493   -- if *ANY* subgoal has repeated literals*)
   494 fun check_tac st =
   495   if exists (fn prem => has_reps (rhyps(prem,[]))) (Thm.prems_of st)
   496   then  Seq.empty  else  Seq.single st;
   497 
   498 
   499 (* resolve_from_net_tac actually made it slower... *)
   500 fun prolog_step_tac ctxt horns i =
   501     (assume_tac ctxt i APPEND resolve_tac ctxt horns i) THEN check_tac THEN
   502     TRYALL_eq_assume_tac;
   503 
   504 (*Sums the sizes of the subgoals, ignoring hypotheses (ancestors)*)
   505 fun addconcl prem sz = size_of_term (Logic.strip_assums_concl prem) + sz;
   506 
   507 fun size_of_subgoals st = fold_rev addconcl (Thm.prems_of st) 0;
   508 
   509 
   510 (*Negation Normal Form*)
   511 val nnf_rls = [imp_to_disjD, iff_to_disjD, not_conjD, not_disjD,
   512                not_impD, not_iffD, not_allD, not_exD, not_notD];
   513 
   514 fun ok4nnf (Const (@{const_name Trueprop},_) $ (Const (@{const_name Not}, _) $ t)) = rigid t
   515   | ok4nnf (Const (@{const_name Trueprop},_) $ t) = rigid t
   516   | ok4nnf _ = false;
   517 
   518 fun make_nnf1 ctxt th =
   519   if ok4nnf (Thm.concl_of th)
   520   then make_nnf1 ctxt (tryres(th, nnf_rls))
   521     handle THM ("tryres", _, _) =>
   522         forward_res ctxt (make_nnf1 ctxt)
   523            (tryres(th, [conj_forward,disj_forward,all_forward,ex_forward]))
   524     handle THM ("tryres", _, _) => th
   525   else th
   526 
   527 (*The simplification removes defined quantifiers and occurrences of True and False.
   528   nnf_ss also includes the one-point simprocs,
   529   which are needed to avoid the various one-point theorems from generating junk clauses.*)
   530 val nnf_simps =
   531   @{thms simp_implies_def Ex1_def Ball_def Bex_def if_True if_False if_cancel
   532          if_eq_cancel cases_simp}
   533 val nnf_extra_simps = @{thms split_ifs ex_simps all_simps simp_thms}
   534 
   535 (* FIXME: "let_simp" is probably redundant now that we also rewrite with
   536   "Let_def [abs_def]". *)
   537 val nnf_ss =
   538   simpset_of (put_simpset HOL_basic_ss @{context}
   539     addsimps nnf_extra_simps
   540     addsimprocs [@{simproc defined_All}, @{simproc defined_Ex}, @{simproc neq},
   541                  @{simproc let_simp}])
   542 
   543 val presimplified_consts =
   544   [@{const_name simp_implies}, @{const_name False}, @{const_name True},
   545    @{const_name Ex1}, @{const_name Ball}, @{const_name Bex}, @{const_name If},
   546    @{const_name Let}]
   547 
   548 fun presimplify ctxt =
   549   rewrite_rule ctxt (map safe_mk_meta_eq nnf_simps)
   550   #> simplify (put_simpset nnf_ss ctxt)
   551   #> rewrite_rule ctxt @{thms Let_def [abs_def]}
   552 
   553 fun make_nnf ctxt th =
   554   (case Thm.prems_of th of
   555     [] => th |> presimplify ctxt |> make_nnf1 ctxt
   556   | _ => raise THM ("make_nnf: premises in argument", 0, [th]));
   557 
   558 fun choice_theorems thy =
   559   try (Global_Theory.get_thm thy) "Hilbert_Choice.choice" |> the_list
   560 
   561 (* Pull existential quantifiers to front. This accomplishes Skolemization for
   562    clauses that arise from a subgoal. *)
   563 fun skolemize_with_choice_theorems ctxt choice_ths =
   564   let
   565     fun aux th =
   566       if not (has_conns [@{const_name Ex}] (Thm.prop_of th)) then
   567         th
   568       else
   569         tryres (th, choice_ths @
   570                     [conj_exD1, conj_exD2, disj_exD, disj_exD1, disj_exD2])
   571         |> aux
   572         handle THM ("tryres", _, _) =>
   573                tryres (th, [conj_forward, disj_forward, all_forward])
   574                |> forward_res ctxt aux
   575                |> aux
   576                handle THM ("tryres", _, _) =>
   577                       rename_bound_vars_RS th ex_forward
   578                       |> forward_res ctxt aux
   579   in aux o make_nnf ctxt end
   580 
   581 fun skolemize ctxt =
   582   let val thy = Proof_Context.theory_of ctxt in
   583     skolemize_with_choice_theorems ctxt (choice_theorems thy)
   584   end
   585 
   586 exception NO_F_PATTERN of unit
   587 
   588 fun get_F_pattern T t u =
   589   let
   590     fun pat t u =
   591       let
   592         val ((head1, args1), (head2, args2)) = (t, u) |> apply2 strip_comb
   593       in
   594         if head1 = head2 then
   595           let val pats = map2 pat args1 args2 in
   596             case filter (is_some o fst) pats of
   597               [(SOME T, _)] => (SOME T, list_comb (head1, map snd pats))
   598             | [] => (NONE, t)
   599             | _ => raise NO_F_PATTERN ()
   600           end
   601         else
   602           let val T = fastype_of t in
   603             if can dest_funT T then (SOME T, Bound 0) else raise NO_F_PATTERN ()
   604           end
   605       end
   606   in
   607     if T = @{typ bool} then
   608       NONE
   609     else case pat t u of
   610       (SOME T, p as _ $ _) => SOME (Abs (Name.uu, T, p))
   611     | _ => NONE
   612   end
   613   handle NO_F_PATTERN () => NONE
   614 
   615 val ext_cong_neq = @{thm ext_cong_neq}
   616 
   617 (* Strengthens "f g ~= f h" to "f g ~= f h & (EX x. g x ~= h x)". *)
   618 fun cong_extensionalize_thm ctxt th =
   619   (case Thm.concl_of th of
   620     @{const Trueprop} $ (@{const Not}
   621         $ (Const (@{const_name HOL.eq}, Type (_, [T, _]))
   622            $ (t as _ $ _) $ (u as _ $ _))) =>
   623     (case get_F_pattern T t u of
   624       SOME p => th RS infer_instantiate ctxt [(("F", 0), Thm.cterm_of ctxt p)] ext_cong_neq
   625     | NONE => th)
   626   | _ => th)
   627 
   628 (* Removes the lambdas from an equation of the form "t = (%x1 ... xn. u)". It
   629    would be desirable to do this symmetrically but there's at least one existing
   630    proof in "Tarski" that relies on the current behavior. *)
   631 fun abs_extensionalize_conv ctxt ct =
   632   (case Thm.term_of ct of
   633     Const (@{const_name HOL.eq}, _) $ _ $ Abs _ =>
   634     ct |> (Conv.rewr_conv @{thm fun_eq_iff [THEN eq_reflection]}
   635            then_conv abs_extensionalize_conv ctxt)
   636   | _ $ _ => Conv.comb_conv (abs_extensionalize_conv ctxt) ct
   637   | Abs _ => Conv.abs_conv (abs_extensionalize_conv o snd) ctxt ct
   638   | _ => Conv.all_conv ct)
   639 
   640 val abs_extensionalize_thm = Conv.fconv_rule o abs_extensionalize_conv
   641 
   642 fun try_skolemize_etc ctxt th =
   643   let
   644     val th = th |> cong_extensionalize_thm ctxt
   645   in
   646     [th]
   647     (* Extensionalize lambdas in "th", because that makes sense and that's what
   648        Sledgehammer does, but also keep an unextensionalized version of "th" for
   649        backward compatibility. *)
   650     |> insert Thm.eq_thm_prop (abs_extensionalize_thm ctxt th)
   651     |> map_filter (fn th => th |> try (skolemize ctxt)
   652                                |> tap (fn NONE =>
   653                                           trace_msg ctxt (fn () =>
   654                                               "Failed to skolemize " ^
   655                                                Thm.string_of_thm ctxt th)
   656                                         | _ => ()))
   657   end
   658 
   659 fun add_clauses ctxt th cls =
   660   let
   661     val (cnfs, ctxt') = ctxt
   662       |> Variable.declare_thm th
   663       |> make_cnf [] th;
   664   in Variable.export ctxt' ctxt cnfs @ cls end;
   665 
   666 (*Sort clauses by number of literals*)
   667 fun fewerlits (th1, th2) = nliterals (Thm.prop_of th1) < nliterals (Thm.prop_of th2)
   668 
   669 (*Make clauses from a list of theorems, previously Skolemized and put into nnf.
   670   The resulting clauses are HOL disjunctions.*)
   671 fun make_clauses_unsorted ctxt ths = fold_rev (add_clauses ctxt) ths [];
   672 val make_clauses = sort (make_ord fewerlits) oo make_clauses_unsorted;
   673 
   674 (*Convert a list of clauses (disjunctions) to Horn clauses (contrapositives)*)
   675 fun make_horns ths =
   676     name_thms "Horn#"
   677       (distinct Thm.eq_thm_prop (fold_rev (add_contras clause_rules) ths []));
   678 
   679 (*Could simply use nprems_of, which would count remaining subgoals -- no
   680   discrimination as to their size!  With BEST_FIRST, fails for problem 41.*)
   681 
   682 fun best_prolog_tac ctxt sizef horns =
   683     BEST_FIRST (has_fewer_prems 1, sizef) (prolog_step_tac ctxt horns 1);
   684 
   685 fun depth_prolog_tac ctxt horns =
   686     DEPTH_FIRST (has_fewer_prems 1) (prolog_step_tac ctxt horns 1);
   687 
   688 (*Return all negative clauses, as possible goal clauses*)
   689 fun gocls cls = name_thms "Goal#" (map make_goal (neg_clauses cls));
   690 
   691 fun skolemize_prems_tac ctxt prems =
   692   cut_facts_tac (maps (try_skolemize_etc ctxt) prems) THEN' REPEAT o eresolve_tac ctxt [exE]
   693 
   694 (*Basis of all meson-tactics.  Supplies cltac with clauses: HOL disjunctions.
   695   Function mkcl converts theorems to clauses.*)
   696 fun MESON preskolem_tac mkcl cltac ctxt i st =
   697   SELECT_GOAL
   698     (EVERY [Object_Logic.atomize_prems_tac ctxt 1,
   699             resolve_tac ctxt @{thms ccontr} 1,
   700             preskolem_tac,
   701             Subgoal.FOCUS (fn {context = ctxt', prems = negs, ...} =>
   702                       EVERY1 [skolemize_prems_tac ctxt' negs,
   703                               Subgoal.FOCUS (cltac o mkcl o #prems) ctxt']) ctxt 1]) i st
   704   handle THM _ => no_tac st;    (*probably from make_meta_clause, not first-order*)
   705 
   706 
   707 (** Best-first search versions **)
   708 
   709 (*ths is a list of additional clauses (HOL disjunctions) to use.*)
   710 fun best_meson_tac sizef ctxt =
   711   MESON all_tac (make_clauses ctxt)
   712     (fn cls =>
   713          THEN_BEST_FIRST (resolve_tac ctxt (gocls cls) 1)
   714                          (has_fewer_prems 1, sizef)
   715                          (prolog_step_tac ctxt (make_horns cls) 1))
   716     ctxt
   717 
   718 (*First, breaks the goal into independent units*)
   719 fun safe_best_meson_tac ctxt =
   720   SELECT_GOAL (TRY (safe_tac ctxt) THEN TRYALL (best_meson_tac size_of_subgoals ctxt));
   721 
   722 (** Depth-first search version **)
   723 
   724 fun depth_meson_tac ctxt =
   725   MESON all_tac (make_clauses ctxt)
   726     (fn cls => EVERY [resolve_tac ctxt (gocls cls) 1, depth_prolog_tac ctxt (make_horns cls)])
   727     ctxt
   728 
   729 (** Iterative deepening version **)
   730 
   731 (*This version does only one inference per call;
   732   having only one eq_assume_tac speeds it up!*)
   733 fun prolog_step_tac' ctxt horns =
   734     let val (horn0s, _) = (*0 subgoals vs 1 or more*)
   735             take_prefix Thm.no_prems horns
   736         val nrtac = resolve_from_net_tac ctxt (Tactic.build_net horns)
   737     in  fn i => eq_assume_tac i ORELSE
   738                 match_tac ctxt horn0s i ORELSE  (*no backtracking if unit MATCHES*)
   739                 ((assume_tac ctxt i APPEND nrtac i) THEN check_tac)
   740     end;
   741 
   742 fun iter_deepen_prolog_tac ctxt horns =
   743     ITER_DEEPEN iter_deepen_limit (has_fewer_prems 1) (prolog_step_tac' ctxt horns);
   744 
   745 fun iter_deepen_meson_tac ctxt ths = ctxt |> MESON all_tac (make_clauses ctxt)
   746   (fn cls =>
   747     (case (gocls (cls @ ths)) of
   748       [] => no_tac  (*no goal clauses*)
   749     | goes =>
   750         let
   751           val horns = make_horns (cls @ ths)
   752           val _ = trace_msg ctxt (fn () =>
   753             cat_lines ("meson method called:" ::
   754               map (Thm.string_of_thm ctxt) (cls @ ths) @
   755               ["clauses:"] @ map (Thm.string_of_thm ctxt) horns))
   756         in
   757           THEN_ITER_DEEPEN iter_deepen_limit
   758             (resolve_tac ctxt goes 1) (has_fewer_prems 1) (prolog_step_tac' ctxt horns)
   759         end));
   760 
   761 fun meson_tac ctxt ths =
   762   SELECT_GOAL (TRY (safe_tac ctxt) THEN TRYALL (iter_deepen_meson_tac ctxt ths));
   763 
   764 
   765 (**** Code to support ordinary resolution, rather than Model Elimination ****)
   766 
   767 (*Convert a list of clauses (disjunctions) to meta-level clauses (==>),
   768   with no contrapositives, for ordinary resolution.*)
   769 
   770 (*Rules to convert the head literal into a negated assumption. If the head
   771   literal is already negated, then using notEfalse instead of notEfalse'
   772   prevents a double negation.*)
   773 val notEfalse = @{lemma "\<not> P \<Longrightarrow> P \<Longrightarrow> False" by (rule notE)};
   774 val notEfalse' = @{lemma "P \<Longrightarrow> \<not> P \<Longrightarrow> False" by (rule notE)};
   775 
   776 fun negated_asm_of_head th =
   777     th RS notEfalse handle THM _ => th RS notEfalse';
   778 
   779 (*Converting one theorem from a disjunction to a meta-level clause*)
   780 fun make_meta_clause ctxt th =
   781   let val (fth, thaw) = Misc_Legacy.freeze_thaw_robust ctxt th
   782   in  
   783       (zero_var_indexes o Thm.varifyT_global o thaw 0 o 
   784        negated_asm_of_head o make_horn resolution_clause_rules) fth
   785   end;
   786 
   787 fun make_meta_clauses ctxt ths =
   788     name_thms "MClause#"
   789       (distinct Thm.eq_thm_prop (map (make_meta_clause ctxt) ths));
   790 
   791 end;