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