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