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