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