src/HOL/Tools/Meson/meson.ML
author wenzelm
Wed Jul 08 21:33:00 2015 +0200 (2015-07-08)
changeset 60696 8304fb4fb823
parent 60642 48dd1cefb4ae
child 60781 2da59cdf531c
permissions -rw-r--r--
clarified 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
wenzelm@60362
    14
  val first_order_resolve : Proof.context -> 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
wenzelm@59632
    25
  val cong_extensionalize_thm : Proof.context -> 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@60358
    44
  val make_meta_clause: Proof.context -> thm -> thm
wenzelm@60358
    45
  val make_meta_clauses: Proof.context -> 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"*)
wenzelm@60362
   101
fun first_order_resolve ctxt thA thB =
wenzelm@32262
   102
  (case
wenzelm@32262
   103
    try (fn () =>
wenzelm@60362
   104
      let val thy = Proof_Context.theory_of ctxt
wenzelm@59582
   105
          val tmA = Thm.concl_of thA
wenzelm@59582
   106
          val Const(@{const_name Pure.imp},_) $ tmB $ _ = Thm.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@60362
   110
          val ct_pairs = map (apply2 (Thm.cterm_of ctxt) 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
wenzelm@59582
   155
    val t = Thm.concl_of th
wenzelm@59582
   156
    val r = Thm.concl_of rl
blanchet@40262
   157
    val th' = th RS Thm.rename_boundvars r (protect_bound_var_names r) rl
wenzelm@59582
   158
    val t' = Thm.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@59498
   173
fun quant_resolve_tac ctxt th i st =
wenzelm@59582
   174
  case (Thm.concl_of st, Thm.prop_of th) of
blanchet@50695
   175
    (@{const Trueprop} $ (Var _ $ (c as Free _)), @{const Trueprop} $ _) =>
blanchet@50695
   176
    let
wenzelm@59632
   177
      val cc = Thm.cterm_of ctxt c
wenzelm@59582
   178
      val ct = Thm.dest_arg (Thm.cprop_of th)
wenzelm@59498
   179
    in resolve_tac ctxt [th] i (Drule.instantiate' [] [SOME (Thm.lambda cc ct)] st) end
wenzelm@59498
   180
  | _ => resolve_tac ctxt [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@59498
   188
    fun tacf [prem] = quant_resolve_tac ctxt (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
wenzelm@59582
   231
fun signed_lits th = signed_lits_aux (HOLogic.dest_Trueprop (Thm.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 =
wenzelm@59582
   261
       case HOLogic.dest_Trueprop (Thm.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 =
wenzelm@59582
   278
  let val neqs = notequal_lits_count (HOLogic.dest_Trueprop (Thm.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@59498
   290
           (fn major::minors => resolve_tac ctxt [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 =
wenzelm@59582
   305
  if has_duplicates (op =) (literals (Thm.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  
wenzelm@60642
   349
  val spec_var =
wenzelm@60642
   350
    Thm.dest_arg (Thm.dest_arg (#2 (Thm.dest_implies (Thm.cprop_of spec))))
wenzelm@60642
   351
    |> Thm.term_of |> dest_Var;
wenzelm@60642
   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@59582
   356
      val ([x], ctxt') =
wenzelm@59582
   357
        Variable.variant_fixes [name_of (HOLogic.dest_Trueprop (Thm.concl_of th))] ctxt;
wenzelm@59617
   358
      val spec' = spec
wenzelm@60642
   359
        |> Thm.instantiate ([], [(spec_var, Thm.cterm_of ctxt' (Free (x, snd spec_var)))]);
paulson@24937
   360
    in (th RS spec', ctxt') end
paulson@24937
   361
end;
paulson@9840
   362
wenzelm@60362
   363
fun apply_skolem_theorem ctxt (th, rls) =
blanchet@37398
   364
  let
blanchet@37410
   365
    fun tryall [] = raise THM ("apply_skolem_theorem", 0, th::rls)
wenzelm@60362
   366
      | tryall (rl :: rls) = first_order_resolve ctxt th rl handle THM _ => tryall rls
blanchet@37398
   367
  in tryall rls end
paulson@22515
   368
blanchet@37410
   369
(* Conjunctive normal form, adding clauses from th in front of ths (for foldr).
blanchet@37410
   370
   Strips universal quantifiers and breaks up conjunctions.
blanchet@37410
   371
   Eliminates existential quantifiers using Skolemization theorems. *)
wenzelm@59165
   372
fun cnf old_skolem_ths ctxt (th, ths) =
wenzelm@59165
   373
  let val ctxt_ref = Unsynchronized.ref ctxt   (* FIXME ??? *)
paulson@24937
   374
      fun cnf_aux (th,ths) =
wenzelm@59582
   375
        if not (can HOLogic.dest_Trueprop (Thm.prop_of th)) then ths (*meta-level: ignore*)
wenzelm@59582
   376
        else if not (has_conns [@{const_name All}, @{const_name Ex}, @{const_name HOL.conj}] (Thm.prop_of th))
wenzelm@59165
   377
        then nodups ctxt th :: ths (*no work to do, terminate*)
wenzelm@59582
   378
        else case head_of (HOLogic.dest_Trueprop (Thm.concl_of th)) of
haftmann@38795
   379
            Const (@{const_name HOL.conj}, _) => (*conjunction*)
wenzelm@24300
   380
                cnf_aux (th RS conjunct1, cnf_aux (th RS conjunct2, ths))
haftmann@38557
   381
          | Const (@{const_name All}, _) => (*universal quantifier*)
wenzelm@59165
   382
                let val (th', ctxt') = freeze_spec th (! ctxt_ref)
wenzelm@59165
   383
                in  ctxt_ref := ctxt'; cnf_aux (th', ths) end
haftmann@38557
   384
          | Const (@{const_name Ex}, _) =>
wenzelm@24300
   385
              (*existential quantifier: Insert Skolem functions*)
wenzelm@60362
   386
              cnf_aux (apply_skolem_theorem (! ctxt_ref) (th, old_skolem_ths), ths)
haftmann@38795
   387
          | Const (@{const_name HOL.disj}, _) =>
wenzelm@24300
   388
              (*Disjunction of P, Q: Create new goal of proving ?P | ?Q and solve it using
wenzelm@24300
   389
                all combinations of converting P, Q to CNF.*)
wenzelm@59171
   390
              (*There is one assumption, which gets bound to prem and then normalized via
wenzelm@59171
   391
                cnf_nil. The normal form is given to resolve_tac, instantiate a Boolean
wenzelm@59171
   392
                variable created by resolution with disj_forward. Since (cnf_nil prem)
wenzelm@59171
   393
                returns a LIST of theorems, we can backtrack to get all combinations.*)
wenzelm@59498
   394
              let val tac = Misc_Legacy.METAHYPS ctxt (fn [prem] => resolve_tac ctxt (cnf_nil prem) 1) 1
wenzelm@59171
   395
              in  Seq.list_of ((tac THEN tac) (th RS disj_forward)) @ ths  end
wenzelm@59165
   396
          | _ => nodups ctxt th :: ths  (*no work to do*)
wenzelm@59165
   397
      and cnf_nil th = cnf_aux (th, [])
blanchet@39269
   398
      val cls =
wenzelm@59582
   399
        if has_too_many_clauses ctxt (Thm.concl_of th) then
blanchet@43964
   400
          (trace_msg ctxt (fn () =>
wenzelm@59165
   401
               "cnf is ignoring: " ^ Display.string_of_thm ctxt th); ths)
blanchet@43964
   402
        else
blanchet@43964
   403
          cnf_aux (th, ths)
wenzelm@59165
   404
  in (cls, !ctxt_ref) end
wenzelm@59165
   405
wenzelm@59165
   406
fun make_cnf old_skolem_ths th ctxt =
wenzelm@59165
   407
  cnf old_skolem_ths ctxt (th, [])
paulson@20417
   408
paulson@20417
   409
(*Generalization, removal of redundant equalities, removal of tautologies.*)
paulson@24937
   410
fun finish_cnf ths = filter (not o is_taut) (map refl_clause ths);
paulson@9840
   411
paulson@9840
   412
paulson@15579
   413
(**** Generation of contrapositives ****)
paulson@9840
   414
haftmann@38557
   415
fun is_left (Const (@{const_name Trueprop}, _) $
haftmann@38795
   416
               (Const (@{const_name HOL.disj}, _) $ (Const (@{const_name HOL.disj}, _) $ _ $ _) $ _)) = true
paulson@21102
   417
  | is_left _ = false;
wenzelm@24300
   418
paulson@15579
   419
(*Associate disjuctions to right -- make leftmost disjunct a LITERAL*)
wenzelm@24300
   420
fun assoc_right th =
wenzelm@59582
   421
  if is_left (Thm.prop_of th) then assoc_right (th RS disj_assoc)
paulson@21102
   422
  else th;
paulson@9840
   423
paulson@15579
   424
(*Must check for negative literal first!*)
paulson@15579
   425
val clause_rules = [disj_assoc, make_neg_rule, make_pos_rule];
paulson@9840
   426
paulson@15579
   427
(*For ordinary resolution. *)
paulson@15579
   428
val resolution_clause_rules = [disj_assoc, make_neg_rule', make_pos_rule'];
paulson@9840
   429
paulson@15579
   430
(*Create a goal or support clause, conclusing False*)
paulson@15579
   431
fun make_goal th =   (*Must check for negative literal first!*)
paulson@15579
   432
    make_goal (tryres(th, clause_rules))
paulson@15579
   433
  handle THM _ => tryres(th, [make_neg_goal, make_pos_goal]);
paulson@9840
   434
paulson@21102
   435
fun rigid t = not (is_Var (head_of t));
paulson@21102
   436
haftmann@38795
   437
fun ok4horn (Const (@{const_name Trueprop},_) $ (Const (@{const_name HOL.disj}, _) $ t $ _)) = rigid t
haftmann@38557
   438
  | ok4horn (Const (@{const_name Trueprop},_) $ t) = rigid t
paulson@21102
   439
  | ok4horn _ = false;
paulson@21102
   440
paulson@15579
   441
(*Create a meta-level Horn clause*)
wenzelm@24300
   442
fun make_horn crules th =
wenzelm@59582
   443
  if ok4horn (Thm.concl_of th)
paulson@21102
   444
  then make_horn crules (tryres(th,crules)) handle THM _ => th
paulson@21102
   445
  else th;
paulson@9840
   446
paulson@16563
   447
(*Generate Horn clauses for all contrapositives of a clause. The input, th,
paulson@16563
   448
  is a HOL disjunction.*)
wenzelm@33339
   449
fun add_contras crules th hcs =
blanchet@39328
   450
  let fun rots (0,_) = hcs
wenzelm@24300
   451
        | rots (k,th) = zero_var_indexes (make_horn crules th) ::
wenzelm@24300
   452
                        rots(k-1, assoc_right (th RS disj_comm))
wenzelm@59582
   453
  in case nliterals(Thm.prop_of th) of
wenzelm@24300
   454
        1 => th::hcs
paulson@15579
   455
      | n => rots(n, assoc_right th)
paulson@15579
   456
  end;
paulson@9840
   457
paulson@15579
   458
(*Use "theorem naming" to label the clauses*)
paulson@15579
   459
fun name_thms label =
wenzelm@33339
   460
    let fun name1 th (k, ths) =
wenzelm@27865
   461
          (k-1, Thm.put_name_hint (label ^ string_of_int k) th :: ths)
wenzelm@33339
   462
    in  fn ths => #2 (fold_rev name1 ths (length ths, []))  end;
paulson@9840
   463
paulson@16563
   464
(*Is the given disjunction an all-negative support clause?*)
wenzelm@59582
   465
fun is_negative th = forall (not o #1) (literals (Thm.prop_of th));
paulson@9840
   466
wenzelm@33317
   467
val neg_clauses = filter is_negative;
paulson@9840
   468
paulson@9840
   469
paulson@15579
   470
(***** MESON PROOF PROCEDURE *****)
paulson@9840
   471
wenzelm@56245
   472
fun rhyps (Const(@{const_name Pure.imp},_) $ (Const(@{const_name Trueprop},_) $ A) $ phi,
wenzelm@24300
   473
           As) = rhyps(phi, A::As)
paulson@15579
   474
  | rhyps (_, As) = As;
paulson@9840
   475
paulson@15579
   476
(** Detecting repeated assumptions in a subgoal **)
paulson@9840
   477
paulson@15579
   478
(*The stringtree detects repeated assumptions.*)
wenzelm@33245
   479
fun ins_term t net = Net.insert_term (op aconv) (t, t) net;
paulson@9840
   480
paulson@15579
   481
(*detects repetitions in a list of terms*)
paulson@15579
   482
fun has_reps [] = false
paulson@15579
   483
  | has_reps [_] = false
paulson@15579
   484
  | has_reps [t,u] = (t aconv u)
wenzelm@33245
   485
  | has_reps ts = (fold ins_term ts Net.empty; false) handle Net.INSERT => true;
paulson@9840
   486
paulson@15579
   487
(*Like TRYALL eq_assume_tac, but avoids expensive THEN calls*)
paulson@18508
   488
fun TRYING_eq_assume_tac 0 st = Seq.single st
paulson@18508
   489
  | TRYING_eq_assume_tac i st =
wenzelm@31945
   490
       TRYING_eq_assume_tac (i-1) (Thm.eq_assumption i st)
paulson@18508
   491
       handle THM _ => TRYING_eq_assume_tac (i-1) st;
paulson@18508
   492
wenzelm@59582
   493
fun TRYALL_eq_assume_tac st = TRYING_eq_assume_tac (Thm.nprems_of st) st;
paulson@9840
   494
paulson@15579
   495
(*Loop checking: FAIL if trying to prove the same thing twice
paulson@15579
   496
  -- if *ANY* subgoal has repeated literals*)
paulson@15579
   497
fun check_tac st =
wenzelm@59582
   498
  if exists (fn prem => has_reps (rhyps(prem,[]))) (Thm.prems_of st)
paulson@15579
   499
  then  Seq.empty  else  Seq.single st;
paulson@9840
   500
paulson@9840
   501
wenzelm@59164
   502
(* resolve_from_net_tac actually made it slower... *)
wenzelm@58963
   503
fun prolog_step_tac ctxt horns i =
wenzelm@59498
   504
    (assume_tac ctxt i APPEND resolve_tac ctxt horns i) THEN check_tac THEN
paulson@18508
   505
    TRYALL_eq_assume_tac;
paulson@9840
   506
paulson@9840
   507
(*Sums the sizes of the subgoals, ignoring hypotheses (ancestors)*)
wenzelm@33339
   508
fun addconcl prem sz = size_of_term (Logic.strip_assums_concl prem) + sz;
paulson@15579
   509
wenzelm@59582
   510
fun size_of_subgoals st = fold_rev addconcl (Thm.prems_of st) 0;
paulson@15579
   511
paulson@9840
   512
paulson@9840
   513
(*Negation Normal Form*)
paulson@9840
   514
val nnf_rls = [imp_to_disjD, iff_to_disjD, not_conjD, not_disjD,
wenzelm@9869
   515
               not_impD, not_iffD, not_allD, not_exD, not_notD];
paulson@15581
   516
haftmann@38557
   517
fun ok4nnf (Const (@{const_name Trueprop},_) $ (Const (@{const_name Not}, _) $ t)) = rigid t
haftmann@38557
   518
  | ok4nnf (Const (@{const_name Trueprop},_) $ t) = rigid t
paulson@21102
   519
  | ok4nnf _ = false;
paulson@21102
   520
wenzelm@32262
   521
fun make_nnf1 ctxt th =
wenzelm@59582
   522
  if ok4nnf (Thm.concl_of th)
wenzelm@32262
   523
  then make_nnf1 ctxt (tryres(th, nnf_rls))
paulson@28174
   524
    handle THM ("tryres", _, _) =>
wenzelm@32262
   525
        forward_res ctxt (make_nnf1 ctxt)
wenzelm@9869
   526
           (tryres(th, [conj_forward,disj_forward,all_forward,ex_forward]))
paulson@28174
   527
    handle THM ("tryres", _, _) => th
blanchet@38608
   528
  else th
paulson@9840
   529
wenzelm@24300
   530
(*The simplification removes defined quantifiers and occurrences of True and False.
paulson@20018
   531
  nnf_ss also includes the one-point simprocs,
paulson@18405
   532
  which are needed to avoid the various one-point theorems from generating junk clauses.*)
paulson@19894
   533
val nnf_simps =
blanchet@37539
   534
  @{thms simp_implies_def Ex1_def Ball_def Bex_def if_True if_False if_cancel
blanchet@37539
   535
         if_eq_cancel cases_simp}
blanchet@37539
   536
val nnf_extra_simps = @{thms split_ifs ex_simps all_simps simp_thms}
paulson@18405
   537
blanchet@43821
   538
(* FIXME: "let_simp" is probably redundant now that we also rewrite with
wenzelm@46904
   539
  "Let_def [abs_def]". *)
paulson@18405
   540
val nnf_ss =
wenzelm@51717
   541
  simpset_of (put_simpset HOL_basic_ss @{context}
wenzelm@51717
   542
    addsimps nnf_extra_simps
blanchet@43264
   543
    addsimprocs [@{simproc defined_All}, @{simproc defined_Ex}, @{simproc neq},
wenzelm@51717
   544
                 @{simproc let_simp}])
blanchet@43264
   545
blanchet@46093
   546
val presimplified_consts =
blanchet@43264
   547
  [@{const_name simp_implies}, @{const_name False}, @{const_name True},
blanchet@43264
   548
   @{const_name Ex1}, @{const_name Ball}, @{const_name Bex}, @{const_name If},
blanchet@43264
   549
   @{const_name Let}]
paulson@15872
   550
wenzelm@51717
   551
fun presimplify ctxt =
wenzelm@54742
   552
  rewrite_rule ctxt (map safe_mk_meta_eq nnf_simps)
wenzelm@51717
   553
  #> simplify (put_simpset nnf_ss ctxt)
wenzelm@54742
   554
  #> rewrite_rule ctxt @{thms Let_def [abs_def]}
blanchet@38089
   555
wenzelm@59582
   556
fun make_nnf ctxt th =
wenzelm@59582
   557
  (case Thm.prems_of th of
wenzelm@51717
   558
    [] => th |> presimplify ctxt |> make_nnf1 ctxt
wenzelm@59582
   559
  | _ => raise THM ("make_nnf: premises in argument", 0, [th]));
paulson@15581
   560
blanchet@39950
   561
fun choice_theorems thy =
blanchet@39950
   562
  try (Global_Theory.get_thm thy) "Hilbert_Choice.choice" |> the_list
blanchet@39950
   563
blanchet@39900
   564
(* Pull existential quantifiers to front. This accomplishes Skolemization for
blanchet@39900
   565
   clauses that arise from a subgoal. *)
blanchet@39950
   566
fun skolemize_with_choice_theorems ctxt choice_ths =
blanchet@39900
   567
  let
blanchet@39900
   568
    fun aux th =
wenzelm@59582
   569
      if not (has_conns [@{const_name Ex}] (Thm.prop_of th)) then
blanchet@39900
   570
        th
blanchet@39900
   571
      else
blanchet@39901
   572
        tryres (th, choice_ths @
blanchet@39900
   573
                    [conj_exD1, conj_exD2, disj_exD, disj_exD1, disj_exD2])
blanchet@39900
   574
        |> aux
blanchet@39900
   575
        handle THM ("tryres", _, _) =>
blanchet@39900
   576
               tryres (th, [conj_forward, disj_forward, all_forward])
blanchet@39900
   577
               |> forward_res ctxt aux
blanchet@39900
   578
               |> aux
blanchet@39900
   579
               handle THM ("tryres", _, _) =>
blanchet@40262
   580
                      rename_bound_vars_RS th ex_forward
blanchet@39900
   581
                      |> forward_res ctxt aux
blanchet@39900
   582
  in aux o make_nnf ctxt end
paulson@29684
   583
blanchet@39950
   584
fun skolemize ctxt =
wenzelm@42361
   585
  let val thy = Proof_Context.theory_of ctxt in
blanchet@39950
   586
    skolemize_with_choice_theorems ctxt (choice_theorems thy)
blanchet@39950
   587
  end
blanchet@39904
   588
blanchet@47954
   589
exception NO_F_PATTERN of unit
blanchet@47954
   590
blanchet@47956
   591
fun get_F_pattern T t u =
blanchet@47954
   592
  let
blanchet@47954
   593
    fun pat t u =
blanchet@47954
   594
      let
wenzelm@59058
   595
        val ((head1, args1), (head2, args2)) = (t, u) |> apply2 strip_comb
blanchet@47954
   596
      in
blanchet@47954
   597
        if head1 = head2 then
blanchet@47954
   598
          let val pats = map2 pat args1 args2 in
blanchet@47954
   599
            case filter (is_some o fst) pats of
blanchet@47954
   600
              [(SOME T, _)] => (SOME T, list_comb (head1, map snd pats))
blanchet@47954
   601
            | [] => (NONE, t)
blanchet@47954
   602
            | _ => raise NO_F_PATTERN ()
blanchet@47954
   603
          end
blanchet@47954
   604
        else
blanchet@47954
   605
          let val T = fastype_of t in
blanchet@47954
   606
            if can dest_funT T then (SOME T, Bound 0) else raise NO_F_PATTERN ()
blanchet@47954
   607
          end
blanchet@47954
   608
      end
blanchet@47954
   609
  in
blanchet@47956
   610
    if T = @{typ bool} then
blanchet@47956
   611
      NONE
blanchet@47956
   612
    else case pat t u of
blanchet@47956
   613
      (SOME T, p as _ $ _) => SOME (Abs (Name.uu, T, p))
blanchet@47956
   614
    | _ => NONE
blanchet@47954
   615
  end
blanchet@47956
   616
  handle NO_F_PATTERN () => NONE
blanchet@47954
   617
blanchet@47954
   618
val ext_cong_neq = @{thm ext_cong_neq}
blanchet@47954
   619
val F_ext_cong_neq =
wenzelm@59582
   620
  Term.add_vars (Thm.prop_of @{thm ext_cong_neq}) []
blanchet@47954
   621
  |> filter (fn ((s, _), _) => s = "F")
blanchet@47954
   622
  |> the_single |> Var
blanchet@47954
   623
blanchet@47954
   624
(* Strengthens "f g ~= f h" to "f g ~= f h & (EX x. g x ~= h x)". *)
wenzelm@59632
   625
fun cong_extensionalize_thm ctxt th =
wenzelm@59582
   626
  (case Thm.concl_of th of
blanchet@47956
   627
    @{const Trueprop} $ (@{const Not}
blanchet@47956
   628
        $ (Const (@{const_name HOL.eq}, Type (_, [T, _]))
blanchet@47956
   629
           $ (t as _ $ _) $ (u as _ $ _))) =>
blanchet@47956
   630
    (case get_F_pattern T t u of
blanchet@47954
   631
       SOME p =>
wenzelm@59632
   632
       let val inst = [apply2 (Thm.cterm_of ctxt) (F_ext_cong_neq, p)] in
blanchet@47954
   633
         th RS cterm_instantiate inst ext_cong_neq
blanchet@47954
   634
       end
blanchet@47954
   635
     | NONE => th)
wenzelm@59582
   636
  | _ => th)
blanchet@47954
   637
blanchet@42760
   638
(* Removes the lambdas from an equation of the form "t = (%x1 ... xn. u)". It
blanchet@42760
   639
   would be desirable to do this symmetrically but there's at least one existing
blanchet@42760
   640
   proof in "Tarski" that relies on the current behavior. *)
blanchet@47953
   641
fun abs_extensionalize_conv ctxt ct =
wenzelm@59582
   642
  (case Thm.term_of ct of
blanchet@42760
   643
    Const (@{const_name HOL.eq}, _) $ _ $ Abs _ =>
blanchet@42760
   644
    ct |> (Conv.rewr_conv @{thm fun_eq_iff [THEN eq_reflection]}
blanchet@47953
   645
           then_conv abs_extensionalize_conv ctxt)
blanchet@47953
   646
  | _ $ _ => Conv.comb_conv (abs_extensionalize_conv ctxt) ct
blanchet@47953
   647
  | Abs _ => Conv.abs_conv (abs_extensionalize_conv o snd) ctxt ct
wenzelm@59582
   648
  | _ => Conv.all_conv ct)
blanchet@42747
   649
blanchet@47953
   650
val abs_extensionalize_thm = Conv.fconv_rule o abs_extensionalize_conv
blanchet@47953
   651
blanchet@46071
   652
fun try_skolemize_etc ctxt th =
blanchet@47954
   653
  let
wenzelm@59632
   654
    val th = th |> cong_extensionalize_thm ctxt
blanchet@47954
   655
  in
blanchet@47954
   656
    [th]
blanchet@47954
   657
    (* Extensionalize lambdas in "th", because that makes sense and that's what
blanchet@47954
   658
       Sledgehammer does, but also keep an unextensionalized version of "th" for
blanchet@47954
   659
       backward compatibility. *)
blanchet@47954
   660
    |> insert Thm.eq_thm_prop (abs_extensionalize_thm ctxt th)
blanchet@47954
   661
    |> map_filter (fn th => th |> try (skolemize ctxt)
blanchet@47954
   662
                               |> tap (fn NONE =>
blanchet@47954
   663
                                          trace_msg ctxt (fn () =>
blanchet@47954
   664
                                              "Failed to skolemize " ^
blanchet@47954
   665
                                               Display.string_of_thm ctxt th)
blanchet@47954
   666
                                        | _ => ()))
blanchet@47954
   667
  end
paulson@25694
   668
blanchet@43964
   669
fun add_clauses ctxt th cls =
wenzelm@59165
   670
  let
wenzelm@59165
   671
    val (cnfs, ctxt') = ctxt
wenzelm@59165
   672
      |> Variable.declare_thm th
wenzelm@59165
   673
      |> make_cnf [] th;
wenzelm@59165
   674
  in Variable.export ctxt' ctxt cnfs @ cls end;
paulson@9840
   675
blanchet@47035
   676
(*Sort clauses by number of literals*)
wenzelm@59582
   677
fun fewerlits (th1, th2) = nliterals (Thm.prop_of th1) < nliterals (Thm.prop_of th2)
blanchet@47035
   678
paulson@9840
   679
(*Make clauses from a list of theorems, previously Skolemized and put into nnf.
paulson@9840
   680
  The resulting clauses are HOL disjunctions.*)
blanchet@43964
   681
fun make_clauses_unsorted ctxt ths = fold_rev (add_clauses ctxt) ths [];
blanchet@47035
   682
val make_clauses = sort (make_ord fewerlits) oo make_clauses_unsorted;
quigley@15773
   683
paulson@16563
   684
(*Convert a list of clauses (disjunctions) to Horn clauses (contrapositives)*)
wenzelm@9869
   685
fun make_horns ths =
paulson@9840
   686
    name_thms "Horn#"
wenzelm@33339
   687
      (distinct Thm.eq_thm_prop (fold_rev (add_contras clause_rules) ths []));
paulson@9840
   688
paulson@9840
   689
(*Could simply use nprems_of, which would count remaining subgoals -- no
paulson@9840
   690
  discrimination as to their size!  With BEST_FIRST, fails for problem 41.*)
paulson@9840
   691
wenzelm@58963
   692
fun best_prolog_tac ctxt sizef horns =
wenzelm@58963
   693
    BEST_FIRST (has_fewer_prems 1, sizef) (prolog_step_tac ctxt horns 1);
paulson@9840
   694
wenzelm@58963
   695
fun depth_prolog_tac ctxt horns =
wenzelm@58963
   696
    DEPTH_FIRST (has_fewer_prems 1) (prolog_step_tac ctxt horns 1);
paulson@9840
   697
paulson@9840
   698
(*Return all negative clauses, as possible goal clauses*)
paulson@9840
   699
fun gocls cls = name_thms "Goal#" (map make_goal (neg_clauses cls));
paulson@9840
   700
wenzelm@32262
   701
fun skolemize_prems_tac ctxt prems =
wenzelm@59498
   702
  cut_facts_tac (maps (try_skolemize_etc ctxt) prems) THEN' REPEAT o eresolve_tac ctxt [exE]
paulson@9840
   703
paulson@22546
   704
(*Basis of all meson-tactics.  Supplies cltac with clauses: HOL disjunctions.
paulson@22546
   705
  Function mkcl converts theorems to clauses.*)
blanchet@39037
   706
fun MESON preskolem_tac mkcl cltac ctxt i st =
paulson@16588
   707
  SELECT_GOAL
wenzelm@54742
   708
    (EVERY [Object_Logic.atomize_prems_tac ctxt 1,
wenzelm@59498
   709
            resolve_tac ctxt @{thms ccontr} 1,
blanchet@39269
   710
            preskolem_tac,
wenzelm@32283
   711
            Subgoal.FOCUS (fn {context = ctxt', prems = negs, ...} =>
wenzelm@60696
   712
                      EVERY1 [skolemize_prems_tac ctxt' negs,
wenzelm@32283
   713
                              Subgoal.FOCUS (cltac o mkcl o #prems) ctxt']) ctxt 1]) i st
wenzelm@24300
   714
  handle THM _ => no_tac st;    (*probably from make_meta_clause, not first-order*)
paulson@9840
   715
blanchet@39037
   716
paulson@9840
   717
(** Best-first search versions **)
paulson@9840
   718
paulson@16563
   719
(*ths is a list of additional clauses (HOL disjunctions) to use.*)
blanchet@43964
   720
fun best_meson_tac sizef ctxt =
blanchet@43964
   721
  MESON all_tac (make_clauses ctxt)
paulson@22546
   722
    (fn cls =>
wenzelm@59498
   723
         THEN_BEST_FIRST (resolve_tac ctxt (gocls cls) 1)
paulson@9840
   724
                         (has_fewer_prems 1, sizef)
wenzelm@58963
   725
                         (prolog_step_tac ctxt (make_horns cls) 1))
blanchet@43964
   726
    ctxt
paulson@9840
   727
paulson@9840
   728
(*First, breaks the goal into independent units*)
wenzelm@32262
   729
fun safe_best_meson_tac ctxt =
wenzelm@42793
   730
  SELECT_GOAL (TRY (safe_tac ctxt) THEN TRYALL (best_meson_tac size_of_subgoals ctxt));
paulson@9840
   731
paulson@9840
   732
(** Depth-first search version **)
paulson@9840
   733
blanchet@43964
   734
fun depth_meson_tac ctxt =
blanchet@43964
   735
  MESON all_tac (make_clauses ctxt)
wenzelm@59498
   736
    (fn cls => EVERY [resolve_tac ctxt (gocls cls) 1, depth_prolog_tac ctxt (make_horns cls)])
blanchet@43964
   737
    ctxt
paulson@9840
   738
paulson@9840
   739
(** Iterative deepening version **)
paulson@9840
   740
paulson@9840
   741
(*This version does only one inference per call;
paulson@9840
   742
  having only one eq_assume_tac speeds it up!*)
wenzelm@58957
   743
fun prolog_step_tac' ctxt horns =
blanchet@39328
   744
    let val (horn0s, _) = (*0 subgoals vs 1 or more*)
paulson@9840
   745
            take_prefix Thm.no_prems horns
wenzelm@59164
   746
        val nrtac = resolve_from_net_tac ctxt (Tactic.build_net horns)
paulson@9840
   747
    in  fn i => eq_assume_tac i ORELSE
wenzelm@58957
   748
                match_tac ctxt horn0s i ORELSE  (*no backtracking if unit MATCHES*)
wenzelm@58963
   749
                ((assume_tac ctxt i APPEND nrtac i) THEN check_tac)
paulson@9840
   750
    end;
paulson@9840
   751
wenzelm@58957
   752
fun iter_deepen_prolog_tac ctxt horns =
wenzelm@58957
   753
    ITER_DEEPEN iter_deepen_limit (has_fewer_prems 1) (prolog_step_tac' ctxt horns);
paulson@9840
   754
blanchet@43964
   755
fun iter_deepen_meson_tac ctxt ths = ctxt |> MESON all_tac (make_clauses ctxt)
wenzelm@32091
   756
  (fn cls =>
wenzelm@32091
   757
    (case (gocls (cls @ ths)) of
wenzelm@32091
   758
      [] => no_tac  (*no goal clauses*)
wenzelm@32091
   759
    | goes =>
wenzelm@32091
   760
        let
wenzelm@32091
   761
          val horns = make_horns (cls @ ths)
blanchet@39979
   762
          val _ = trace_msg ctxt (fn () =>
wenzelm@32091
   763
            cat_lines ("meson method called:" ::
wenzelm@32262
   764
              map (Display.string_of_thm ctxt) (cls @ ths) @
wenzelm@32262
   765
              ["clauses:"] @ map (Display.string_of_thm ctxt) horns))
wenzelm@38802
   766
        in
wenzelm@38802
   767
          THEN_ITER_DEEPEN iter_deepen_limit
wenzelm@59498
   768
            (resolve_tac ctxt goes 1) (has_fewer_prems 1) (prolog_step_tac' ctxt horns)
wenzelm@38802
   769
        end));
paulson@9840
   770
wenzelm@32262
   771
fun meson_tac ctxt ths =
wenzelm@42793
   772
  SELECT_GOAL (TRY (safe_tac ctxt) THEN TRYALL (iter_deepen_meson_tac ctxt ths));
wenzelm@9869
   773
wenzelm@9869
   774
paulson@14813
   775
(**** Code to support ordinary resolution, rather than Model Elimination ****)
paulson@14744
   776
wenzelm@24300
   777
(*Convert a list of clauses (disjunctions) to meta-level clauses (==>),
paulson@15008
   778
  with no contrapositives, for ordinary resolution.*)
paulson@14744
   779
paulson@14744
   780
(*Rules to convert the head literal into a negated assumption. If the head
paulson@14744
   781
  literal is already negated, then using notEfalse instead of notEfalse'
paulson@14744
   782
  prevents a double negation.*)
wenzelm@46503
   783
val notEfalse = @{lemma "~ P ==> P ==> False" by (rule notE)};
wenzelm@46503
   784
val notEfalse' = @{lemma "P ==> ~ P ==> False" by (rule notE)};
paulson@14744
   785
wenzelm@24300
   786
fun negated_asm_of_head th =
paulson@14744
   787
    th RS notEfalse handle THM _ => th RS notEfalse';
paulson@14744
   788
paulson@26066
   789
(*Converting one theorem from a disjunction to a meta-level clause*)
wenzelm@60358
   790
fun make_meta_clause ctxt th =
wenzelm@60358
   791
  let val (fth, thaw) = Misc_Legacy.freeze_thaw_robust ctxt th
paulson@26066
   792
  in  
wenzelm@35845
   793
      (zero_var_indexes o Thm.varifyT_global o thaw 0 o 
paulson@26066
   794
       negated_asm_of_head o make_horn resolution_clause_rules) fth
paulson@26066
   795
  end;
wenzelm@24300
   796
wenzelm@60358
   797
fun make_meta_clauses ctxt ths =
paulson@14744
   798
    name_thms "MClause#"
wenzelm@60358
   799
      (distinct Thm.eq_thm_prop (map (make_meta_clause ctxt) ths));
paulson@14744
   800
paulson@9840
   801
end;