src/HOL/Tools/Meson/meson.ML
author wenzelm
Sun Dec 21 15:03:45 2014 +0100 (2014-12-21)
changeset 59165 115965966e15
parent 59164 ff40c53d1af9
child 59171 75ec7271b426
permissions -rw-r--r--
proper context;
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
wenzelm@59165
    17
  val make_cnf: thm list -> thm -> Proof.context -> thm list * Proof.context
wenzelm@24300
    18
  val finish_cnf: thm list -> thm list
blanchet@46093
    19
  val presimplified_consts : string list
wenzelm@51717
    20
  val presimplify: Proof.context -> thm -> thm
wenzelm@32262
    21
  val make_nnf: Proof.context -> thm -> thm
blanchet@39950
    22
  val choice_theorems : theory -> thm list
blanchet@39950
    23
  val skolemize_with_choice_theorems : Proof.context -> thm list -> thm -> thm
blanchet@39904
    24
  val skolemize : Proof.context -> thm -> thm
blanchet@47954
    25
  val cong_extensionalize_thm : theory -> thm -> thm
blanchet@47953
    26
  val abs_extensionalize_conv : Proof.context -> conv
blanchet@47953
    27
  val abs_extensionalize_thm : Proof.context -> thm -> thm
blanchet@43964
    28
  val make_clauses_unsorted: Proof.context -> thm list -> thm list
blanchet@43964
    29
  val make_clauses: Proof.context -> thm list -> thm list
wenzelm@24300
    30
  val make_horns: thm list -> thm list
wenzelm@58963
    31
  val best_prolog_tac: Proof.context -> (thm -> int) -> thm list -> tactic
wenzelm@58963
    32
  val depth_prolog_tac: Proof.context -> thm list -> tactic
wenzelm@24300
    33
  val gocls: thm list -> thm list
blanchet@39900
    34
  val skolemize_prems_tac : Proof.context -> thm list -> int -> tactic
blanchet@39037
    35
  val MESON:
blanchet@39269
    36
    tactic -> (thm list -> thm list) -> (thm list -> tactic) -> Proof.context
blanchet@39269
    37
    -> int -> tactic
wenzelm@32262
    38
  val best_meson_tac: (thm -> int) -> Proof.context -> int -> tactic
wenzelm@32262
    39
  val safe_best_meson_tac: Proof.context -> int -> tactic
wenzelm@32262
    40
  val depth_meson_tac: Proof.context -> int -> tactic
wenzelm@58957
    41
  val prolog_step_tac': Proof.context -> thm list -> int -> tactic
wenzelm@58957
    42
  val iter_deepen_prolog_tac: Proof.context -> thm list -> tactic
wenzelm@32262
    43
  val iter_deepen_meson_tac: Proof.context -> thm list -> int -> tactic
wenzelm@24300
    44
  val make_meta_clause: thm -> thm
wenzelm@24300
    45
  val make_meta_clauses: thm list -> thm list
wenzelm@32262
    46
  val meson_tac: Proof.context -> thm list -> int -> tactic
paulson@15579
    47
end
paulson@9840
    48
blanchet@39901
    49
structure Meson : MESON =
paulson@15579
    50
struct
paulson@9840
    51
wenzelm@42616
    52
val trace = Attrib.setup_config_bool @{binding meson_trace} (K false)
blanchet@39979
    53
blanchet@39979
    54
fun trace_msg ctxt msg = if Config.get ctxt trace then tracing (msg ()) else ()
wenzelm@32955
    55
blanchet@42739
    56
val max_clauses = Attrib.setup_config_int @{binding meson_max_clauses} (K 60)
paulson@26562
    57
wenzelm@38802
    58
(*No known example (on 1-5-2007) needs even thirty*)
wenzelm@38802
    59
val iter_deepen_limit = 50;
wenzelm@38802
    60
haftmann@31454
    61
val disj_forward = @{thm disj_forward};
haftmann@31454
    62
val disj_forward2 = @{thm disj_forward2};
haftmann@31454
    63
val make_pos_rule = @{thm make_pos_rule};
haftmann@31454
    64
val make_pos_rule' = @{thm make_pos_rule'};
haftmann@31454
    65
val make_pos_goal = @{thm make_pos_goal};
haftmann@31454
    66
val make_neg_rule = @{thm make_neg_rule};
haftmann@31454
    67
val make_neg_rule' = @{thm make_neg_rule'};
haftmann@31454
    68
val make_neg_goal = @{thm make_neg_goal};
haftmann@31454
    69
val conj_forward = @{thm conj_forward};
haftmann@31454
    70
val all_forward = @{thm all_forward};
haftmann@31454
    71
val ex_forward = @{thm ex_forward};
haftmann@31454
    72
blanchet@39953
    73
val not_conjD = @{thm not_conjD};
blanchet@39953
    74
val not_disjD = @{thm not_disjD};
blanchet@39953
    75
val not_notD = @{thm not_notD};
blanchet@39953
    76
val not_allD = @{thm not_allD};
blanchet@39953
    77
val not_exD = @{thm not_exD};
blanchet@39953
    78
val imp_to_disjD = @{thm imp_to_disjD};
blanchet@39953
    79
val not_impD = @{thm not_impD};
blanchet@39953
    80
val iff_to_disjD = @{thm iff_to_disjD};
blanchet@39953
    81
val not_iffD = @{thm not_iffD};
blanchet@39953
    82
val conj_exD1 = @{thm conj_exD1};
blanchet@39953
    83
val conj_exD2 = @{thm conj_exD2};
blanchet@39953
    84
val disj_exD = @{thm disj_exD};
blanchet@39953
    85
val disj_exD1 = @{thm disj_exD1};
blanchet@39953
    86
val disj_exD2 = @{thm disj_exD2};
blanchet@39953
    87
val disj_assoc = @{thm disj_assoc};
blanchet@39953
    88
val disj_comm = @{thm disj_comm};
blanchet@39953
    89
val disj_FalseD1 = @{thm disj_FalseD1};
blanchet@39953
    90
val disj_FalseD2 = @{thm disj_FalseD2};
paulson@9840
    91
paulson@9840
    92
paulson@15579
    93
(**** Operators for forward proof ****)
paulson@15579
    94
paulson@20417
    95
paulson@20417
    96
(** First-order Resolution **)
paulson@20417
    97
paulson@20417
    98
fun term_pair_of (ix, (ty,t)) = (Var (ix,ty), t);
paulson@20417
    99
paulson@20417
   100
(*FIXME: currently does not "rename variables apart"*)
paulson@20417
   101
fun first_order_resolve thA thB =
wenzelm@32262
   102
  (case
wenzelm@32262
   103
    try (fn () =>
wenzelm@32262
   104
      let val thy = theory_of_thm thA
wenzelm@32262
   105
          val tmA = concl_of thA
wenzelm@56245
   106
          val Const(@{const_name Pure.imp},_) $ tmB $ _ = prop_of thB
blanchet@37398
   107
          val tenv =
blanchet@37410
   108
            Pattern.first_order_match thy (tmB, tmA)
blanchet@37410
   109
                                          (Vartab.empty, Vartab.empty) |> snd
wenzelm@59058
   110
          val ct_pairs = map (apply2 (cterm_of thy) o term_pair_of) (Vartab.dest tenv)
wenzelm@32262
   111
      in  thA RS (cterm_instantiate ct_pairs thB)  end) () of
wenzelm@32262
   112
    SOME th => th
blanchet@37398
   113
  | NONE => raise THM ("first_order_resolve", 0, [thA, thB]))
paulson@18175
   114
blanchet@40262
   115
(* Hack to make it less likely that we lose our precious bound variable names in
blanchet@40262
   116
   "rename_bound_vars_RS" below, because of a clash. *)
blanchet@40262
   117
val protect_prefix = "Meson_xyzzy"
blanchet@40262
   118
blanchet@40262
   119
fun protect_bound_var_names (t $ u) =
blanchet@40262
   120
    protect_bound_var_names t $ protect_bound_var_names u
blanchet@40262
   121
  | protect_bound_var_names (Abs (s, T, t')) =
blanchet@40262
   122
    Abs (protect_prefix ^ s, T, protect_bound_var_names t')
blanchet@40262
   123
  | protect_bound_var_names t = t
blanchet@39930
   124
blanchet@40262
   125
fun fix_bound_var_names old_t new_t =
blanchet@40262
   126
  let
blanchet@40262
   127
    fun quant_of @{const_name All} = SOME true
blanchet@40262
   128
      | quant_of @{const_name Ball} = SOME true
blanchet@40262
   129
      | quant_of @{const_name Ex} = SOME false
blanchet@40262
   130
      | quant_of @{const_name Bex} = SOME false
blanchet@40262
   131
      | quant_of _ = NONE
blanchet@40262
   132
    val flip_quant = Option.map not
blanchet@40262
   133
    fun some_eq (SOME x) (SOME y) = x = y
blanchet@40262
   134
      | some_eq _ _ = false
blanchet@40262
   135
    fun add_names quant (Const (quant_s, _) $ Abs (s, _, t')) =
blanchet@40262
   136
        add_names quant t' #> some_eq quant (quant_of quant_s) ? cons s
blanchet@40262
   137
      | add_names quant (@{const Not} $ t) = add_names (flip_quant quant) t
blanchet@40262
   138
      | add_names quant (@{const implies} $ t1 $ t2) =
blanchet@40262
   139
        add_names (flip_quant quant) t1 #> add_names quant t2
blanchet@40262
   140
      | add_names quant (t1 $ t2) = fold (add_names quant) [t1, t2]
blanchet@40262
   141
      | add_names _ _ = I
blanchet@40262
   142
    fun lost_names quant =
blanchet@40262
   143
      subtract (op =) (add_names quant new_t []) (add_names quant old_t [])
blanchet@40262
   144
    fun aux ((t1 as Const (quant_s, _)) $ (Abs (s, T, t'))) =
blanchet@40262
   145
      t1 $ Abs (s |> String.isPrefix protect_prefix s
blanchet@40262
   146
                   ? perhaps (try (fn _ => hd (lost_names (quant_of quant_s)))),
blanchet@40262
   147
                T, aux t')
blanchet@40262
   148
      | aux (t1 $ t2) = aux t1 $ aux t2
blanchet@40262
   149
      | aux t = t
blanchet@40262
   150
  in aux new_t end
blanchet@39930
   151
blanchet@40262
   152
(* Forward proof while preserving bound variables names *)
blanchet@40262
   153
fun rename_bound_vars_RS th rl =
blanchet@39904
   154
  let
blanchet@39904
   155
    val t = concl_of th
blanchet@39930
   156
    val r = concl_of rl
blanchet@40262
   157
    val th' = th RS Thm.rename_boundvars r (protect_bound_var_names r) rl
blanchet@39904
   158
    val t' = concl_of th'
blanchet@40262
   159
  in Thm.rename_boundvars t' (fix_bound_var_names t t') th' end
paulson@24937
   160
paulson@24937
   161
(*raises exception if no rules apply*)
wenzelm@24300
   162
fun tryres (th, rls) =
paulson@18141
   163
  let fun tryall [] = raise THM("tryres", 0, th::rls)
blanchet@40262
   164
        | tryall (rl::rls) =
blanchet@40262
   165
          (rename_bound_vars_RS th rl handle THM _ => tryall rls)
paulson@18141
   166
  in  tryall rls  end;
wenzelm@24300
   167
wenzelm@58839
   168
(* Special version of "resolve_tac" that works around an explosion in the unifier.
blanchet@50702
   169
   If the goal has the form "?P c", the danger is that resolving it against a
blanchet@50702
   170
   property of the form "... c ... c ... c ..." will lead to a huge unification
blanchet@50695
   171
   problem, due to the (spurious) choices between projection and imitation. The
blanchet@50695
   172
   workaround is to instantiate "?P := (%c. ... c ... c ... c ...)" manually. *)
wenzelm@58839
   173
fun quant_resolve_tac th i st =
blanchet@50695
   174
  case (concl_of st, prop_of th) of
blanchet@50695
   175
    (@{const Trueprop} $ (Var _ $ (c as Free _)), @{const Trueprop} $ _) =>
blanchet@50695
   176
    let
blanchet@50695
   177
      val cc = cterm_of (theory_of_thm th) c
blanchet@50695
   178
      val ct = Thm.dest_arg (cprop_of th)
wenzelm@58839
   179
    in resolve_tac [th] i (Drule.instantiate' [] [SOME (Thm.lambda cc ct)] st) end
wenzelm@58839
   180
  | _ => resolve_tac [th] i st
blanchet@50695
   181
paulson@21050
   182
(*Permits forward proof from rules that discharge assumptions. The supplied proof state st,
paulson@21050
   183
  e.g. from conj_forward, should have the form
paulson@21050
   184
    "[| P' ==> ?P; Q' ==> ?Q |] ==> ?P & ?Q"
paulson@21050
   185
  and the effect should be to instantiate ?P and ?Q with normalized versions of P' and Q'.*)
wenzelm@32262
   186
fun forward_res ctxt nf st =
blanchet@50695
   187
  let
wenzelm@58839
   188
    fun tacf [prem] = quant_resolve_tac (nf prem) 1
blanchet@50695
   189
      | tacf prems =
blanchet@50695
   190
        error (cat_lines
blanchet@50695
   191
          ("Bad proof state in forward_res, please inform lcp@cl.cam.ac.uk:" ::
blanchet@50695
   192
            Display.string_of_thm ctxt st ::
blanchet@50695
   193
            "Premises:" :: map (Display.string_of_thm ctxt) prems))
paulson@21050
   194
  in
wenzelm@59165
   195
    case Seq.pull (ALLGOALS (Misc_Legacy.METAHYPS ctxt tacf) st) of
blanchet@50695
   196
      SOME (th, _) => th
blanchet@50695
   197
    | NONE => raise THM ("forward_res", 0, [st])
paulson@21050
   198
  end;
paulson@15579
   199
paulson@20134
   200
(*Are any of the logical connectives in "bs" present in the term?*)
paulson@20134
   201
fun has_conns bs =
blanchet@39328
   202
  let fun has (Const _) = false
haftmann@38557
   203
        | has (Const(@{const_name Trueprop},_) $ p) = has p
haftmann@38557
   204
        | has (Const(@{const_name Not},_) $ p) = has p
haftmann@38795
   205
        | has (Const(@{const_name HOL.disj},_) $ p $ q) = member (op =) bs @{const_name HOL.disj} orelse has p orelse has q
haftmann@38795
   206
        | has (Const(@{const_name HOL.conj},_) $ p $ q) = member (op =) bs @{const_name HOL.conj} orelse has p orelse has q
haftmann@38557
   207
        | has (Const(@{const_name All},_) $ Abs(_,_,p)) = member (op =) bs @{const_name All} orelse has p
haftmann@38557
   208
        | has (Const(@{const_name Ex},_) $ Abs(_,_,p)) = member (op =) bs @{const_name Ex} orelse has p
wenzelm@24300
   209
        | has _ = false
paulson@15579
   210
  in  has  end;
wenzelm@24300
   211
paulson@9840
   212
paulson@15579
   213
(**** Clause handling ****)
paulson@9840
   214
haftmann@38557
   215
fun literals (Const(@{const_name Trueprop},_) $ P) = literals P
haftmann@38795
   216
  | literals (Const(@{const_name HOL.disj},_) $ P $ Q) = literals P @ literals Q
haftmann@38557
   217
  | literals (Const(@{const_name Not},_) $ P) = [(false,P)]
paulson@15579
   218
  | literals P = [(true,P)];
paulson@9840
   219
paulson@15579
   220
(*number of literals in a term*)
paulson@15579
   221
val nliterals = length o literals;
paulson@9840
   222
paulson@18389
   223
paulson@18389
   224
(*** Tautology Checking ***)
paulson@18389
   225
haftmann@38795
   226
fun signed_lits_aux (Const (@{const_name HOL.disj}, _) $ P $ Q) (poslits, neglits) =
paulson@18389
   227
      signed_lits_aux Q (signed_lits_aux P (poslits, neglits))
haftmann@38557
   228
  | signed_lits_aux (Const(@{const_name Not},_) $ P) (poslits, neglits) = (poslits, P::neglits)
paulson@18389
   229
  | signed_lits_aux P (poslits, neglits) = (P::poslits, neglits);
wenzelm@24300
   230
paulson@18389
   231
fun signed_lits th = signed_lits_aux (HOLogic.dest_Trueprop (concl_of th)) ([],[]);
paulson@18389
   232
paulson@18389
   233
(*Literals like X=X are tautologous*)
haftmann@38864
   234
fun taut_poslit (Const(@{const_name HOL.eq},_) $ t $ u) = t aconv u
haftmann@38557
   235
  | taut_poslit (Const(@{const_name True},_)) = true
paulson@18389
   236
  | taut_poslit _ = false;
paulson@18389
   237
paulson@18389
   238
fun is_taut th =
paulson@18389
   239
  let val (poslits,neglits) = signed_lits th
paulson@18389
   240
  in  exists taut_poslit poslits
paulson@18389
   241
      orelse
wenzelm@45740
   242
      exists (member (op aconv) neglits) (@{term False} :: poslits)
paulson@19894
   243
  end
wenzelm@24300
   244
  handle TERM _ => false;       (*probably dest_Trueprop on a weird theorem*)
paulson@18389
   245
paulson@18389
   246
paulson@18389
   247
(*** To remove trivial negated equality literals from clauses ***)
paulson@18389
   248
paulson@18389
   249
(*They are typically functional reflexivity axioms and are the converses of
paulson@18389
   250
  injectivity equivalences*)
wenzelm@24300
   251
blanchet@39953
   252
val not_refl_disj_D = @{thm not_refl_disj_D};
paulson@18389
   253
paulson@20119
   254
(*Is either term a Var that does not properly occur in the other term?*)
paulson@20119
   255
fun eliminable (t as Var _, u) = t aconv u orelse not (Logic.occs(t,u))
paulson@20119
   256
  | eliminable (u, t as Var _) = t aconv u orelse not (Logic.occs(t,u))
paulson@20119
   257
  | eliminable _ = false;
paulson@20119
   258
paulson@18389
   259
fun refl_clause_aux 0 th = th
paulson@18389
   260
  | refl_clause_aux n th =
paulson@18389
   261
       case HOLogic.dest_Trueprop (concl_of th) of
haftmann@38795
   262
          (Const (@{const_name HOL.disj}, _) $ (Const (@{const_name HOL.disj}, _) $ _ $ _) $ _) =>
paulson@18389
   263
            refl_clause_aux n (th RS disj_assoc)    (*isolate an atom as first disjunct*)
haftmann@38864
   264
        | (Const (@{const_name HOL.disj}, _) $ (Const(@{const_name Not},_) $ (Const(@{const_name HOL.eq},_) $ t $ u)) $ _) =>
wenzelm@24300
   265
            if eliminable(t,u)
wenzelm@24300
   266
            then refl_clause_aux (n-1) (th RS not_refl_disj_D)  (*Var inequation: delete*)
wenzelm@24300
   267
            else refl_clause_aux (n-1) (th RS disj_comm)  (*not between Vars: ignore*)
haftmann@38795
   268
        | (Const (@{const_name HOL.disj}, _) $ _ $ _) => refl_clause_aux n (th RS disj_comm)
wenzelm@24300
   269
        | _ => (*not a disjunction*) th;
paulson@18389
   270
haftmann@38795
   271
fun notequal_lits_count (Const (@{const_name HOL.disj}, _) $ P $ Q) =
paulson@18389
   272
      notequal_lits_count P + notequal_lits_count Q
haftmann@38864
   273
  | notequal_lits_count (Const(@{const_name Not},_) $ (Const(@{const_name HOL.eq},_) $ _ $ _)) = 1
paulson@18389
   274
  | notequal_lits_count _ = 0;
paulson@18389
   275
paulson@18389
   276
(*Simplify a clause by applying reflexivity to its negated equality literals*)
wenzelm@24300
   277
fun refl_clause th =
paulson@18389
   278
  let val neqs = notequal_lits_count (HOLogic.dest_Trueprop (concl_of th))
paulson@19894
   279
  in  zero_var_indexes (refl_clause_aux neqs th)  end
wenzelm@24300
   280
  handle TERM _ => th;  (*probably dest_Trueprop on a weird theorem*)
paulson@18389
   281
paulson@18389
   282
paulson@24937
   283
(*** Removal of duplicate literals ***)
paulson@24937
   284
paulson@24937
   285
(*Forward proof, passing extra assumptions as theorems to the tactic*)
wenzelm@59165
   286
fun forward_res2 ctxt nf hyps st =
paulson@24937
   287
  case Seq.pull
paulson@24937
   288
        (REPEAT
wenzelm@59165
   289
         (Misc_Legacy.METAHYPS ctxt
wenzelm@59165
   290
           (fn major::minors => resolve_tac [nf (minors @ hyps) major] 1) 1)
paulson@24937
   291
         st)
paulson@24937
   292
  of SOME(th,_) => th
paulson@24937
   293
   | NONE => raise THM("forward_res2", 0, [st]);
paulson@24937
   294
paulson@24937
   295
(*Remove duplicates in P|Q by assuming ~P in Q
paulson@24937
   296
  rls (initially []) accumulates assumptions of the form P==>False*)
wenzelm@32262
   297
fun nodups_aux ctxt rls th = nodups_aux ctxt rls (th RS disj_assoc)
paulson@24937
   298
    handle THM _ => tryres(th,rls)
wenzelm@59165
   299
    handle THM _ => tryres(forward_res2 ctxt (nodups_aux ctxt) rls (th RS disj_forward2),
paulson@24937
   300
                           [disj_FalseD1, disj_FalseD2, asm_rl])
paulson@24937
   301
    handle THM _ => th;
paulson@24937
   302
paulson@24937
   303
(*Remove duplicate literals, if there are any*)
wenzelm@32262
   304
fun nodups ctxt th =
paulson@24937
   305
  if has_duplicates (op =) (literals (prop_of th))
wenzelm@32262
   306
    then nodups_aux ctxt [] th
paulson@24937
   307
    else th;
paulson@24937
   308
paulson@24937
   309
paulson@18389
   310
(*** The basic CNF transformation ***)
paulson@18389
   311
blanchet@39328
   312
fun estimated_num_clauses bound t =
paulson@26562
   313
 let
blanchet@39269
   314
  fun sum x y = if x < bound andalso y < bound then x+y else bound
blanchet@39269
   315
  fun prod x y = if x < bound andalso y < bound then x*y else bound
paulson@26562
   316
  
paulson@26562
   317
  (*Estimate the number of clauses in order to detect infeasible theorems*)
haftmann@38557
   318
  fun signed_nclauses b (Const(@{const_name Trueprop},_) $ t) = signed_nclauses b t
haftmann@38557
   319
    | signed_nclauses b (Const(@{const_name Not},_) $ t) = signed_nclauses (not b) t
haftmann@38795
   320
    | signed_nclauses b (Const(@{const_name HOL.conj},_) $ t $ u) =
wenzelm@32960
   321
        if b then sum (signed_nclauses b t) (signed_nclauses b u)
wenzelm@32960
   322
             else prod (signed_nclauses b t) (signed_nclauses b u)
haftmann@38795
   323
    | signed_nclauses b (Const(@{const_name HOL.disj},_) $ t $ u) =
wenzelm@32960
   324
        if b then prod (signed_nclauses b t) (signed_nclauses b u)
wenzelm@32960
   325
             else sum (signed_nclauses b t) (signed_nclauses b u)
haftmann@38786
   326
    | signed_nclauses b (Const(@{const_name HOL.implies},_) $ t $ u) =
wenzelm@32960
   327
        if b then prod (signed_nclauses (not b) t) (signed_nclauses b u)
wenzelm@32960
   328
             else sum (signed_nclauses (not b) t) (signed_nclauses b u)
haftmann@38864
   329
    | signed_nclauses b (Const(@{const_name HOL.eq}, Type ("fun", [T, _])) $ t $ u) =
wenzelm@32960
   330
        if T = HOLogic.boolT then (*Boolean equality is if-and-only-if*)
wenzelm@32960
   331
            if b then sum (prod (signed_nclauses (not b) t) (signed_nclauses b u))
wenzelm@32960
   332
                          (prod (signed_nclauses (not b) u) (signed_nclauses b t))
wenzelm@32960
   333
                 else sum (prod (signed_nclauses b t) (signed_nclauses b u))
wenzelm@32960
   334
                          (prod (signed_nclauses (not b) t) (signed_nclauses (not b) u))
wenzelm@32960
   335
        else 1
haftmann@38557
   336
    | signed_nclauses b (Const(@{const_name Ex}, _) $ Abs (_,_,t)) = signed_nclauses b t
haftmann@38557
   337
    | signed_nclauses b (Const(@{const_name All},_) $ Abs (_,_,t)) = signed_nclauses b t
paulson@26562
   338
    | signed_nclauses _ _ = 1; (* literal *)
blanchet@39269
   339
 in signed_nclauses true t end
blanchet@39269
   340
blanchet@39269
   341
fun has_too_many_clauses ctxt t =
blanchet@39269
   342
  let val max_cl = Config.get ctxt max_clauses in
blanchet@39328
   343
    estimated_num_clauses (max_cl + 1) t > max_cl
blanchet@39269
   344
  end
paulson@19894
   345
paulson@15579
   346
(*Replaces universally quantified variables by FREE variables -- because
paulson@24937
   347
  assumptions may not contain scheme variables.  Later, generalize using Variable.export. *)
paulson@24937
   348
local  
paulson@24937
   349
  val spec_var = Thm.dest_arg (Thm.dest_arg (#2 (Thm.dest_implies (Thm.cprop_of spec))));
paulson@24937
   350
  val spec_varT = #T (Thm.rep_cterm spec_var);
haftmann@38557
   351
  fun name_of (Const (@{const_name All}, _) $ Abs(x,_,_)) = x | name_of _ = Name.uu;
paulson@24937
   352
in  
paulson@24937
   353
  fun freeze_spec th ctxt =
paulson@24937
   354
    let
wenzelm@42361
   355
      val cert = Thm.cterm_of (Proof_Context.theory_of ctxt);
paulson@24937
   356
      val ([x], ctxt') = Variable.variant_fixes [name_of (HOLogic.dest_Trueprop (concl_of th))] ctxt;
paulson@24937
   357
      val spec' = Thm.instantiate ([], [(spec_var, cert (Free (x, spec_varT)))]) spec;
paulson@24937
   358
    in (th RS spec', ctxt') end
paulson@24937
   359
end;
paulson@9840
   360
paulson@15998
   361
(*Used with METAHYPS below. There is one assumption, which gets bound to prem
paulson@15998
   362
  and then normalized via function nf. The normal form is given to resolve_tac,
paulson@22515
   363
  instantiate a Boolean variable created by resolution with disj_forward. Since
paulson@22515
   364
  (nf prem) returns a LIST of theorems, we can backtrack to get all combinations.*)
paulson@15579
   365
fun resop nf [prem] = resolve_tac (nf prem) 1;
paulson@9840
   366
blanchet@37410
   367
fun apply_skolem_theorem (th, rls) =
blanchet@37398
   368
  let
blanchet@37410
   369
    fun tryall [] = raise THM ("apply_skolem_theorem", 0, th::rls)
blanchet@37398
   370
      | tryall (rl :: rls) =
blanchet@37398
   371
        first_order_resolve th rl handle THM _ => tryall rls
blanchet@37398
   372
  in tryall rls end
paulson@22515
   373
blanchet@37410
   374
(* Conjunctive normal form, adding clauses from th in front of ths (for foldr).
blanchet@37410
   375
   Strips universal quantifiers and breaks up conjunctions.
blanchet@37410
   376
   Eliminates existential quantifiers using Skolemization theorems. *)
wenzelm@59165
   377
fun cnf old_skolem_ths ctxt (th, ths) =
wenzelm@59165
   378
  let val ctxt_ref = Unsynchronized.ref ctxt   (* FIXME ??? *)
paulson@24937
   379
      fun cnf_aux (th,ths) =
wenzelm@24300
   380
        if not (can HOLogic.dest_Trueprop (prop_of th)) then ths (*meta-level: ignore*)
haftmann@38795
   381
        else if not (has_conns [@{const_name All}, @{const_name Ex}, @{const_name HOL.conj}] (prop_of th))
wenzelm@59165
   382
        then nodups ctxt th :: ths (*no work to do, terminate*)
wenzelm@24300
   383
        else case head_of (HOLogic.dest_Trueprop (concl_of th)) of
haftmann@38795
   384
            Const (@{const_name HOL.conj}, _) => (*conjunction*)
wenzelm@24300
   385
                cnf_aux (th RS conjunct1, cnf_aux (th RS conjunct2, ths))
haftmann@38557
   386
          | Const (@{const_name All}, _) => (*universal quantifier*)
wenzelm@59165
   387
                let val (th', ctxt') = freeze_spec th (! ctxt_ref)
wenzelm@59165
   388
                in  ctxt_ref := ctxt'; cnf_aux (th', ths) end
haftmann@38557
   389
          | Const (@{const_name Ex}, _) =>
wenzelm@24300
   390
              (*existential quantifier: Insert Skolem functions*)
blanchet@39886
   391
              cnf_aux (apply_skolem_theorem (th, old_skolem_ths), ths)
haftmann@38795
   392
          | Const (@{const_name HOL.disj}, _) =>
wenzelm@24300
   393
              (*Disjunction of P, Q: Create new goal of proving ?P | ?Q and solve it using
wenzelm@24300
   394
                all combinations of converting P, Q to CNF.*)
wenzelm@24300
   395
              let val tac =
wenzelm@59165
   396
                  Misc_Legacy.METAHYPS ctxt (resop cnf_nil) 1 THEN
wenzelm@59165
   397
                   (fn st' => st' |> Misc_Legacy.METAHYPS ctxt (resop cnf_nil) 1)
wenzelm@24300
   398
              in  Seq.list_of (tac (th RS disj_forward)) @ ths  end
wenzelm@59165
   399
          | _ => nodups ctxt th :: ths  (*no work to do*)
wenzelm@59165
   400
      and cnf_nil th = cnf_aux (th, [])
blanchet@39269
   401
      val cls =
blanchet@43964
   402
        if has_too_many_clauses ctxt (concl_of th) then
blanchet@43964
   403
          (trace_msg ctxt (fn () =>
wenzelm@59165
   404
               "cnf is ignoring: " ^ Display.string_of_thm ctxt th); ths)
blanchet@43964
   405
        else
blanchet@43964
   406
          cnf_aux (th, ths)
wenzelm@59165
   407
  in (cls, !ctxt_ref) end
wenzelm@59165
   408
wenzelm@59165
   409
fun make_cnf old_skolem_ths th ctxt =
wenzelm@59165
   410
  cnf old_skolem_ths ctxt (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
wenzelm@56245
   475
fun rhyps (Const(@{const_name Pure.imp},_) $ (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
wenzelm@59164
   505
(* resolve_from_net_tac actually made it slower... *)
wenzelm@58963
   506
fun prolog_step_tac ctxt horns i =
wenzelm@58963
   507
    (assume_tac ctxt 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 =
wenzelm@54742
   555
  rewrite_rule ctxt (map safe_mk_meta_eq nnf_simps)
wenzelm@51717
   556
  #> simplify (put_simpset nnf_ss ctxt)
wenzelm@54742
   557
  #> rewrite_rule ctxt @{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
wenzelm@59058
   597
        val ((head1, args1), (head2, args2)) = (t, u) |> apply2 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 =>
wenzelm@59058
   634
       let val inst = [apply2 (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@59165
   673
  let
wenzelm@59165
   674
    val (cnfs, ctxt') = ctxt
wenzelm@59165
   675
      |> Variable.declare_thm th
wenzelm@59165
   676
      |> make_cnf [] th;
wenzelm@59165
   677
  in Variable.export ctxt' ctxt cnfs @ cls end;
paulson@9840
   678
blanchet@47035
   679
(*Sort clauses by number of literals*)
blanchet@47035
   680
fun fewerlits (th1, th2) = nliterals (prop_of th1) < nliterals (prop_of th2)
blanchet@47035
   681
paulson@9840
   682
(*Make clauses from a list of theorems, previously Skolemized and put into nnf.
paulson@9840
   683
  The resulting clauses are HOL disjunctions.*)
blanchet@43964
   684
fun make_clauses_unsorted ctxt ths = fold_rev (add_clauses ctxt) ths [];
blanchet@47035
   685
val make_clauses = sort (make_ord fewerlits) oo make_clauses_unsorted;
quigley@15773
   686
paulson@16563
   687
(*Convert a list of clauses (disjunctions) to Horn clauses (contrapositives)*)
wenzelm@9869
   688
fun make_horns ths =
paulson@9840
   689
    name_thms "Horn#"
wenzelm@33339
   690
      (distinct Thm.eq_thm_prop (fold_rev (add_contras clause_rules) ths []));
paulson@9840
   691
paulson@9840
   692
(*Could simply use nprems_of, which would count remaining subgoals -- no
paulson@9840
   693
  discrimination as to their size!  With BEST_FIRST, fails for problem 41.*)
paulson@9840
   694
wenzelm@58963
   695
fun best_prolog_tac ctxt sizef horns =
wenzelm@58963
   696
    BEST_FIRST (has_fewer_prems 1, sizef) (prolog_step_tac ctxt horns 1);
paulson@9840
   697
wenzelm@58963
   698
fun depth_prolog_tac ctxt horns =
wenzelm@58963
   699
    DEPTH_FIRST (has_fewer_prems 1) (prolog_step_tac ctxt horns 1);
paulson@9840
   700
paulson@9840
   701
(*Return all negative clauses, as possible goal clauses*)
paulson@9840
   702
fun gocls cls = name_thms "Goal#" (map make_goal (neg_clauses cls));
paulson@9840
   703
wenzelm@32262
   704
fun skolemize_prems_tac ctxt prems =
wenzelm@58839
   705
  cut_facts_tac (maps (try_skolemize_etc ctxt) prems) THEN' REPEAT o eresolve_tac [exE]
paulson@9840
   706
paulson@22546
   707
(*Basis of all meson-tactics.  Supplies cltac with clauses: HOL disjunctions.
paulson@22546
   708
  Function mkcl converts theorems to clauses.*)
blanchet@39037
   709
fun MESON preskolem_tac mkcl cltac ctxt i st =
paulson@16588
   710
  SELECT_GOAL
wenzelm@54742
   711
    (EVERY [Object_Logic.atomize_prems_tac ctxt 1,
wenzelm@58839
   712
            resolve_tac @{thms ccontr} 1,
blanchet@39269
   713
            preskolem_tac,
wenzelm@32283
   714
            Subgoal.FOCUS (fn {context = ctxt', prems = negs, ...} =>
blanchet@39269
   715
                      EVERY1 [skolemize_prems_tac ctxt negs,
wenzelm@32283
   716
                              Subgoal.FOCUS (cltac o mkcl o #prems) ctxt']) ctxt 1]) i st
wenzelm@24300
   717
  handle THM _ => no_tac st;    (*probably from make_meta_clause, not first-order*)
paulson@9840
   718
blanchet@39037
   719
paulson@9840
   720
(** Best-first search versions **)
paulson@9840
   721
paulson@16563
   722
(*ths is a list of additional clauses (HOL disjunctions) to use.*)
blanchet@43964
   723
fun best_meson_tac sizef ctxt =
blanchet@43964
   724
  MESON all_tac (make_clauses ctxt)
paulson@22546
   725
    (fn cls =>
paulson@9840
   726
         THEN_BEST_FIRST (resolve_tac (gocls cls) 1)
paulson@9840
   727
                         (has_fewer_prems 1, sizef)
wenzelm@58963
   728
                         (prolog_step_tac ctxt (make_horns cls) 1))
blanchet@43964
   729
    ctxt
paulson@9840
   730
paulson@9840
   731
(*First, breaks the goal into independent units*)
wenzelm@32262
   732
fun safe_best_meson_tac ctxt =
wenzelm@42793
   733
  SELECT_GOAL (TRY (safe_tac ctxt) THEN TRYALL (best_meson_tac size_of_subgoals ctxt));
paulson@9840
   734
paulson@9840
   735
(** Depth-first search version **)
paulson@9840
   736
blanchet@43964
   737
fun depth_meson_tac ctxt =
blanchet@43964
   738
  MESON all_tac (make_clauses ctxt)
wenzelm@58963
   739
    (fn cls => EVERY [resolve_tac (gocls cls) 1, depth_prolog_tac ctxt (make_horns cls)])
blanchet@43964
   740
    ctxt
paulson@9840
   741
paulson@9840
   742
(** Iterative deepening version **)
paulson@9840
   743
paulson@9840
   744
(*This version does only one inference per call;
paulson@9840
   745
  having only one eq_assume_tac speeds it up!*)
wenzelm@58957
   746
fun prolog_step_tac' ctxt horns =
blanchet@39328
   747
    let val (horn0s, _) = (*0 subgoals vs 1 or more*)
paulson@9840
   748
            take_prefix Thm.no_prems horns
wenzelm@59164
   749
        val nrtac = resolve_from_net_tac ctxt (Tactic.build_net horns)
paulson@9840
   750
    in  fn i => eq_assume_tac i ORELSE
wenzelm@58957
   751
                match_tac ctxt horn0s i ORELSE  (*no backtracking if unit MATCHES*)
wenzelm@58963
   752
                ((assume_tac ctxt i APPEND nrtac i) THEN check_tac)
paulson@9840
   753
    end;
paulson@9840
   754
wenzelm@58957
   755
fun iter_deepen_prolog_tac ctxt horns =
wenzelm@58957
   756
    ITER_DEEPEN iter_deepen_limit (has_fewer_prems 1) (prolog_step_tac' ctxt horns);
paulson@9840
   757
blanchet@43964
   758
fun iter_deepen_meson_tac ctxt ths = ctxt |> MESON all_tac (make_clauses ctxt)
wenzelm@32091
   759
  (fn cls =>
wenzelm@32091
   760
    (case (gocls (cls @ ths)) of
wenzelm@32091
   761
      [] => no_tac  (*no goal clauses*)
wenzelm@32091
   762
    | goes =>
wenzelm@32091
   763
        let
wenzelm@32091
   764
          val horns = make_horns (cls @ ths)
blanchet@39979
   765
          val _ = trace_msg ctxt (fn () =>
wenzelm@32091
   766
            cat_lines ("meson method called:" ::
wenzelm@32262
   767
              map (Display.string_of_thm ctxt) (cls @ ths) @
wenzelm@32262
   768
              ["clauses:"] @ map (Display.string_of_thm ctxt) horns))
wenzelm@38802
   769
        in
wenzelm@38802
   770
          THEN_ITER_DEEPEN iter_deepen_limit
wenzelm@58957
   771
            (resolve_tac goes 1) (has_fewer_prems 1) (prolog_step_tac' ctxt horns)
wenzelm@38802
   772
        end));
paulson@9840
   773
wenzelm@32262
   774
fun meson_tac ctxt ths =
wenzelm@42793
   775
  SELECT_GOAL (TRY (safe_tac ctxt) THEN TRYALL (iter_deepen_meson_tac ctxt ths));
wenzelm@9869
   776
wenzelm@9869
   777
paulson@14813
   778
(**** Code to support ordinary resolution, rather than Model Elimination ****)
paulson@14744
   779
wenzelm@24300
   780
(*Convert a list of clauses (disjunctions) to meta-level clauses (==>),
paulson@15008
   781
  with no contrapositives, for ordinary resolution.*)
paulson@14744
   782
paulson@14744
   783
(*Rules to convert the head literal into a negated assumption. If the head
paulson@14744
   784
  literal is already negated, then using notEfalse instead of notEfalse'
paulson@14744
   785
  prevents a double negation.*)
wenzelm@46503
   786
val notEfalse = @{lemma "~ P ==> P ==> False" by (rule notE)};
wenzelm@46503
   787
val notEfalse' = @{lemma "P ==> ~ P ==> False" by (rule notE)};
paulson@14744
   788
wenzelm@24300
   789
fun negated_asm_of_head th =
paulson@14744
   790
    th RS notEfalse handle THM _ => th RS notEfalse';
paulson@14744
   791
paulson@26066
   792
(*Converting one theorem from a disjunction to a meta-level clause*)
paulson@26066
   793
fun make_meta_clause th =
wenzelm@47022
   794
  let val (fth,thaw) = Misc_Legacy.freeze_thaw_robust th
paulson@26066
   795
  in  
wenzelm@35845
   796
      (zero_var_indexes o Thm.varifyT_global o thaw 0 o 
paulson@26066
   797
       negated_asm_of_head o make_horn resolution_clause_rules) fth
paulson@26066
   798
  end;
wenzelm@24300
   799
paulson@14744
   800
fun make_meta_clauses ths =
paulson@14744
   801
    name_thms "MClause#"
wenzelm@22360
   802
      (distinct Thm.eq_thm_prop (map make_meta_clause ths));
paulson@14744
   803
paulson@9840
   804
end;