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