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