src/Provers/Arith/fast_lin_arith.ML
author wenzelm
Sat Jun 04 16:10:44 2016 +0200 (2016-06-04)
changeset 63227 d3ed7f00e818
parent 63201 f151704c08e4
child 66035 de6cd60b1226
permissions -rw-r--r--
Integer.lcm normalizes the sign as in HOL/GCD.thy;
tuned;
nipkow@5982
     1
(*  Title:      Provers/Arith/fast_lin_arith.ML
boehmes@31510
     2
    Author:     Tobias Nipkow and Tjark Weber and Sascha Boehme
nipkow@6102
     3
wenzelm@46709
     4
A generic linear arithmetic package.
nipkow@6102
     5
wenzelm@24076
     6
Only take premises and conclusions into account that are already
wenzelm@24076
     7
(negated) (in)equations. lin_arith_simproc tries to prove or disprove
wenzelm@24076
     8
the term.
nipkow@5982
     9
*)
nipkow@5982
    10
nipkow@5982
    11
(*** Data needed for setting up the linear arithmetic package ***)
nipkow@5982
    12
nipkow@6102
    13
signature LIN_ARITH_LOGIC =
nipkow@6102
    14
sig
webertj@20276
    15
  val conjI       : thm  (* P ==> Q ==> P & Q *)
webertj@20276
    16
  val ccontr      : thm  (* (~ P ==> False) ==> P *)
webertj@20276
    17
  val notI        : thm  (* (P ==> False) ==> ~ P *)
webertj@20276
    18
  val not_lessD   : thm  (* ~(m < n) ==> n <= m *)
webertj@20276
    19
  val not_leD     : thm  (* ~(m <= n) ==> n < m *)
webertj@20276
    20
  val sym         : thm  (* x = y ==> y = x *)
boehmes@31510
    21
  val trueI       : thm  (* True *)
webertj@20276
    22
  val mk_Eq       : thm -> thm
webertj@20276
    23
  val atomize     : thm -> thm list
webertj@20276
    24
  val mk_Trueprop : term -> term
webertj@20276
    25
  val neg_prop    : term -> term
webertj@20276
    26
  val is_False    : thm -> bool
webertj@20276
    27
  val is_nat      : typ list * term -> bool
webertj@20276
    28
  val mk_nat_thm  : theory -> term -> thm
nipkow@6102
    29
end;
nipkow@6102
    30
(*
nipkow@6102
    31
mk_Eq(~in) = `in == False'
nipkow@6102
    32
mk_Eq(in) = `in == True'
nipkow@6102
    33
where `in' is an (in)equality.
nipkow@6102
    34
webertj@23190
    35
neg_prop(t) = neg  if t is wrapped up in Trueprop and neg is the
webertj@23190
    36
  (logically) negated version of t (again wrapped up in Trueprop),
webertj@23190
    37
  where the negation of a negative term is the term itself (no
webertj@23190
    38
  double negation!); raises TERM ("neg_prop", [t]) if t is not of
webertj@23190
    39
  the form 'Trueprop $ _'
nipkow@6128
    40
nipkow@6128
    41
is_nat(parameter-types,t) =  t:nat
nipkow@6128
    42
mk_nat_thm(t) = "0 <= t"
nipkow@6102
    43
*)
nipkow@6102
    44
nipkow@5982
    45
signature LIN_ARITH_DATA =
nipkow@5982
    46
sig
wenzelm@24076
    47
  (*internal representation of linear (in-)equations:*)
wenzelm@26945
    48
  type decomp = (term * Rat.rat) list * Rat.rat * string * (term * Rat.rat) list * Rat.rat * bool
wenzelm@26945
    49
  val decomp: Proof.context -> term -> decomp option
wenzelm@24076
    50
  val domain_is_nat: term -> bool
wenzelm@24076
    51
wenzelm@24076
    52
  (*preprocessing, performed on a representation of subgoals as list of premises:*)
wenzelm@24076
    53
  val pre_decomp: Proof.context -> typ list * term list -> (typ list * term list) list
wenzelm@24076
    54
wenzelm@24076
    55
  (*preprocessing, performed on the goal -- must do the same as 'pre_decomp':*)
wenzelm@51717
    56
  val pre_tac: Proof.context -> int -> tactic
wenzelm@24076
    57
wenzelm@24076
    58
  (*the limit on the number of ~= allowed; because each ~= is split
wenzelm@24076
    59
    into two cases, this can lead to an explosion*)
wenzelm@44654
    60
  val neq_limit: int Config.T
boehmes@43607
    61
wenzelm@44654
    62
  val trace: bool Config.T
nipkow@5982
    63
end;
nipkow@5982
    64
(*
nipkow@7551
    65
decomp(`x Rel y') should yield (p,i,Rel,q,j,d)
nipkow@5982
    66
   where Rel is one of "<", "~<", "<=", "~<=" and "=" and
webertj@20217
    67
         p (q, respectively) is the decomposition of the sum term x
webertj@20217
    68
         (y, respectively) into a list of summand * multiplicity
webertj@20217
    69
         pairs and a constant summand and d indicates if the domain
webertj@20217
    70
         is discrete.
webertj@20217
    71
webertj@20276
    72
domain_is_nat(`x Rel y') t should yield true iff x is of type "nat".
webertj@20276
    73
webertj@20217
    74
The relationship between pre_decomp and pre_tac is somewhat tricky.  The
webertj@20217
    75
internal representation of a subgoal and the corresponding theorem must
webertj@20217
    76
be modified by pre_decomp (pre_tac, resp.) in a corresponding way.  See
webertj@20217
    77
the comment for split_items below.  (This is even necessary for eta- and
webertj@20217
    78
beta-equivalent modifications, as some of the lin. arith. code is not
webertj@20217
    79
insensitive to them.)
nipkow@5982
    80
wenzelm@51717
    81
Simpset must reduce contradictory <= to False.
nipkow@5982
    82
   It should also cancel common summands to keep <= reduced;
nipkow@5982
    83
   otherwise <= can grow to massive proportions.
nipkow@5982
    84
*)
nipkow@5982
    85
nipkow@6062
    86
signature FAST_LIN_ARITH =
nipkow@6062
    87
sig
wenzelm@51717
    88
  val prems_lin_arith_tac: Proof.context -> int -> tactic
wenzelm@59656
    89
  val lin_arith_tac: Proof.context -> int -> tactic
wenzelm@61144
    90
  val lin_arith_simproc: Proof.context -> cterm -> thm option
wenzelm@38763
    91
  val map_data:
wenzelm@38763
    92
    ({add_mono_thms: thm list, mult_mono_thms: thm list, inj_thms: thm list,
wenzelm@51717
    93
      lessD: thm list, neqE: thm list, simpset: simpset,
wenzelm@59996
    94
      number_of: (Proof.context -> typ -> int -> cterm) option} ->
wenzelm@38763
    95
     {add_mono_thms: thm list, mult_mono_thms: thm list, inj_thms: thm list,
wenzelm@51717
    96
      lessD: thm list, neqE: thm list, simpset: simpset,
wenzelm@59996
    97
      number_of: (Proof.context -> typ -> int -> cterm) option}) ->
wenzelm@38763
    98
      Context.generic -> Context.generic
wenzelm@38762
    99
  val add_inj_thms: thm list -> Context.generic -> Context.generic
wenzelm@38762
   100
  val add_lessD: thm -> Context.generic -> Context.generic
wenzelm@38762
   101
  val add_simps: thm list -> Context.generic -> Context.generic
wenzelm@38762
   102
  val add_simprocs: simproc list -> Context.generic -> Context.generic
wenzelm@59996
   103
  val set_number_of: (Proof.context -> typ -> int -> cterm) -> Context.generic -> Context.generic
nipkow@6062
   104
end;
nipkow@6062
   105
wenzelm@24076
   106
functor Fast_Lin_Arith
wenzelm@24076
   107
  (structure LA_Logic: LIN_ARITH_LOGIC and LA_Data: LIN_ARITH_DATA): FAST_LIN_ARITH =
nipkow@5982
   108
struct
nipkow@5982
   109
wenzelm@9420
   110
wenzelm@9420
   111
(** theory data **)
wenzelm@9420
   112
wenzelm@33519
   113
structure Data = Generic_Data
wenzelm@22846
   114
(
wenzelm@24076
   115
  type T =
wenzelm@24076
   116
   {add_mono_thms: thm list,
wenzelm@24076
   117
    mult_mono_thms: thm list,
wenzelm@24076
   118
    inj_thms: thm list,
wenzelm@24076
   119
    lessD: thm list,
wenzelm@24076
   120
    neqE: thm list,
wenzelm@51717
   121
    simpset: simpset,
wenzelm@59996
   122
    number_of: (Proof.context -> typ -> int -> cterm) option};
wenzelm@9420
   123
wenzelm@38763
   124
  val empty : T =
wenzelm@38763
   125
   {add_mono_thms = [], mult_mono_thms = [], inj_thms = [],
wenzelm@51717
   126
    lessD = [], neqE = [], simpset = empty_ss,
wenzelm@38763
   127
    number_of = NONE};
wenzelm@16458
   128
  val extend = I;
wenzelm@33519
   129
  fun merge
wenzelm@38763
   130
    ({add_mono_thms = add_mono_thms1, mult_mono_thms = mult_mono_thms1, inj_thms = inj_thms1,
wenzelm@38763
   131
      lessD = lessD1, neqE = neqE1, simpset = simpset1, number_of = number_of1},
wenzelm@38763
   132
     {add_mono_thms = add_mono_thms2, mult_mono_thms = mult_mono_thms2, inj_thms = inj_thms2,
wenzelm@38763
   133
      lessD = lessD2, neqE = neqE2, simpset = simpset2, number_of = number_of2}) : T =
wenzelm@24039
   134
    {add_mono_thms = Thm.merge_thms (add_mono_thms1, add_mono_thms2),
wenzelm@24039
   135
     mult_mono_thms = Thm.merge_thms (mult_mono_thms1, mult_mono_thms2),
wenzelm@24039
   136
     inj_thms = Thm.merge_thms (inj_thms1, inj_thms2),
wenzelm@24039
   137
     lessD = Thm.merge_thms (lessD1, lessD2),
wenzelm@24039
   138
     neqE = Thm.merge_thms (neqE1, neqE2),
wenzelm@51717
   139
     simpset = merge_ss (simpset1, simpset2),
wenzelm@41493
   140
     number_of = merge_options (number_of1, number_of2)};
wenzelm@22846
   141
);
wenzelm@9420
   142
wenzelm@9420
   143
val map_data = Data.map;
wenzelm@24076
   144
val get_data = Data.get o Context.Proof;
wenzelm@9420
   145
wenzelm@61097
   146
fun get_neqE ctxt = map (Thm.transfer (Proof_Context.theory_of ctxt)) (#neqE (get_data ctxt));
wenzelm@61097
   147
wenzelm@38762
   148
fun map_inj_thms f {add_mono_thms, mult_mono_thms, inj_thms, lessD, neqE, simpset, number_of} =
wenzelm@38762
   149
  {add_mono_thms = add_mono_thms, mult_mono_thms = mult_mono_thms, inj_thms = f inj_thms,
wenzelm@38762
   150
    lessD = lessD, neqE = neqE, simpset = simpset, number_of = number_of};
wenzelm@38762
   151
wenzelm@38762
   152
fun map_lessD f {add_mono_thms, mult_mono_thms, inj_thms, lessD, neqE, simpset, number_of} =
wenzelm@38762
   153
  {add_mono_thms = add_mono_thms, mult_mono_thms = mult_mono_thms, inj_thms = inj_thms,
wenzelm@38762
   154
    lessD = f lessD, neqE = neqE, simpset = simpset, number_of = number_of};
wenzelm@38762
   155
wenzelm@51717
   156
fun map_simpset f context =
wenzelm@51717
   157
  map_data (fn {add_mono_thms, mult_mono_thms, inj_thms, lessD, neqE, simpset, number_of} =>
wenzelm@51717
   158
    {add_mono_thms = add_mono_thms, mult_mono_thms = mult_mono_thms, inj_thms = inj_thms,
wenzelm@51717
   159
      lessD = lessD, neqE = neqE, simpset = simpset_map (Context.proof_of context) f simpset,
wenzelm@51717
   160
      number_of = number_of}) context;
wenzelm@38762
   161
wenzelm@61097
   162
fun add_inj_thms thms = map_data (map_inj_thms (append (map Thm.trim_context thms)));
wenzelm@61097
   163
fun add_lessD thm = map_data (map_lessD (fn thms => thms @ [Thm.trim_context thm]));
wenzelm@51717
   164
fun add_simps thms = map_simpset (fn ctxt => ctxt addsimps thms);
wenzelm@51717
   165
fun add_simprocs procs = map_simpset (fn ctxt => ctxt addsimprocs procs);
wenzelm@38762
   166
wenzelm@38763
   167
fun set_number_of f =
wenzelm@38763
   168
  map_data (fn {add_mono_thms, mult_mono_thms, inj_thms, lessD, neqE, simpset, ...} =>
wenzelm@38763
   169
   {add_mono_thms = add_mono_thms, mult_mono_thms = mult_mono_thms, inj_thms = inj_thms,
wenzelm@38763
   170
    lessD = lessD, neqE = neqE, simpset = simpset, number_of = SOME f});
wenzelm@38763
   171
wenzelm@38763
   172
fun number_of ctxt =
wenzelm@61097
   173
  (case get_data ctxt of
wenzelm@59996
   174
    {number_of = SOME f, ...} => f ctxt
wenzelm@38763
   175
  | _ => fn _ => fn _ => raise CTERM ("number_of", []));
wenzelm@38763
   176
wenzelm@9420
   177
wenzelm@9420
   178
nipkow@5982
   179
(*** A fast decision procedure ***)
nipkow@5982
   180
(*** Code ported from HOL Light ***)
nipkow@6056
   181
(* possible optimizations:
nipkow@6056
   182
   use (var,coeff) rep or vector rep  tp save space;
nipkow@6056
   183
   treat non-negative atoms separately rather than adding 0 <= atom
nipkow@6056
   184
*)
nipkow@5982
   185
nipkow@5982
   186
datatype lineq_type = Eq | Le | Lt;
nipkow@5982
   187
nipkow@6056
   188
datatype injust = Asm of int
nipkow@6056
   189
                | Nat of int (* index of atom *)
nipkow@6128
   190
                | LessD of injust
nipkow@6128
   191
                | NotLessD of injust
nipkow@6128
   192
                | NotLeD of injust
nipkow@7551
   193
                | NotLeDD of injust
wenzelm@24630
   194
                | Multiplied of int * injust
nipkow@5982
   195
                | Added of injust * injust;
nipkow@5982
   196
wenzelm@24630
   197
datatype lineq = Lineq of int * lineq_type * int list * injust;
nipkow@5982
   198
nipkow@13498
   199
(* ------------------------------------------------------------------------- *)
nipkow@13498
   200
(* Finding a (counter) example from the trace of a failed elimination        *)
nipkow@13498
   201
(* ------------------------------------------------------------------------- *)
nipkow@13498
   202
(* Examples are represented as rational numbers,                             *)
nipkow@13498
   203
(* Dont blame John Harrison for this code - it is entirely mine. TN          *)
nipkow@13498
   204
nipkow@13498
   205
exception NoEx;
nipkow@13498
   206
nipkow@14372
   207
(* Coding: (i,true,cs) means i <= cs and (i,false,cs) means i < cs.
nipkow@14372
   208
   In general, true means the bound is included, false means it is excluded.
nipkow@14372
   209
   Need to know if it is a lower or upper bound for unambiguous interpretation!
nipkow@14372
   210
*)
nipkow@14372
   211
nipkow@13498
   212
(* ------------------------------------------------------------------------- *)
webertj@23197
   213
(* End of counterexample finder. The actual decision procedure starts here.  *)
nipkow@13498
   214
(* ------------------------------------------------------------------------- *)
nipkow@13498
   215
nipkow@5982
   216
(* ------------------------------------------------------------------------- *)
nipkow@5982
   217
(* Calculate new (in)equality type after addition.                           *)
nipkow@5982
   218
(* ------------------------------------------------------------------------- *)
nipkow@5982
   219
nipkow@5982
   220
fun find_add_type(Eq,x) = x
nipkow@5982
   221
  | find_add_type(x,Eq) = x
nipkow@5982
   222
  | find_add_type(_,Lt) = Lt
nipkow@5982
   223
  | find_add_type(Lt,_) = Lt
nipkow@5982
   224
  | find_add_type(Le,Le) = Le;
nipkow@5982
   225
nipkow@5982
   226
(* ------------------------------------------------------------------------- *)
nipkow@5982
   227
(* Multiply out an (in)equation.                                             *)
nipkow@5982
   228
(* ------------------------------------------------------------------------- *)
nipkow@5982
   229
nipkow@5982
   230
fun multiply_ineq n (i as Lineq(k,ty,l,just)) =
nipkow@5982
   231
  if n = 1 then i
wenzelm@40316
   232
  else if n = 0 andalso ty = Lt then raise Fail "multiply_ineq"
wenzelm@40316
   233
  else if n < 0 andalso (ty=Le orelse ty=Lt) then raise Fail "multiply_ineq"
wenzelm@33002
   234
  else Lineq (n * k, ty, map (Integer.mult n) l, Multiplied (n, just));
nipkow@5982
   235
nipkow@5982
   236
(* ------------------------------------------------------------------------- *)
nipkow@5982
   237
(* Add together (in)equations.                                               *)
nipkow@5982
   238
(* ------------------------------------------------------------------------- *)
nipkow@5982
   239
haftmann@38052
   240
fun add_ineq (Lineq (k1,ty1,l1,just1)) (Lineq (k2,ty2,l2,just2)) =
wenzelm@33002
   241
  let val l = map2 Integer.add l1 l2
nipkow@5982
   242
  in Lineq(k1+k2,find_add_type(ty1,ty2),l,Added(just1,just2)) end;
nipkow@5982
   243
nipkow@5982
   244
(* ------------------------------------------------------------------------- *)
nipkow@5982
   245
(* Elimination of variable between a single pair of (in)equations.           *)
nipkow@5982
   246
(* If they're both inequalities, 1st coefficient must be +ve, 2nd -ve.       *)
nipkow@5982
   247
(* ------------------------------------------------------------------------- *)
nipkow@5982
   248
haftmann@49387
   249
fun elim_var v (i1 as Lineq(_,ty1,l1,_)) (i2 as Lineq(_,ty2,l2,_)) =
haftmann@23063
   250
  let val c1 = nth l1 v and c2 = nth l2 v
wenzelm@63227
   251
      val m = Integer.lcm c1 c2
nipkow@5982
   252
      val m1 = m div (abs c1) and m2 = m div (abs c2)
nipkow@5982
   253
      val (n1,n2) =
nipkow@5982
   254
        if (c1 >= 0) = (c2 >= 0)
nipkow@5982
   255
        then if ty1 = Eq then (~m1,m2)
nipkow@5982
   256
             else if ty2 = Eq then (m1,~m2)
wenzelm@40316
   257
                  else raise Fail "elim_var"
nipkow@5982
   258
        else (m1,m2)
nipkow@5982
   259
      val (p1,p2) = if ty1=Eq andalso ty2=Eq andalso (n1 = ~1 orelse n2 = ~1)
nipkow@5982
   260
                    then (~n1,~n2) else (n1,n2)
boehmes@31510
   261
  in add_ineq (multiply_ineq p1 i1) (multiply_ineq p2 i2) end;
nipkow@5982
   262
nipkow@5982
   263
(* ------------------------------------------------------------------------- *)
nipkow@5982
   264
(* The main refutation-finding code.                                         *)
nipkow@5982
   265
(* ------------------------------------------------------------------------- *)
nipkow@5982
   266
nipkow@5982
   267
fun is_trivial (Lineq(_,_,l,_)) = forall (fn i => i=0) l;
nipkow@5982
   268
haftmann@38052
   269
fun is_contradictory (Lineq(k,ty,_,_)) =
nipkow@5982
   270
  case ty  of Eq => k <> 0 | Le => k > 0 | Lt => k >= 0;
nipkow@5982
   271
wenzelm@24630
   272
fun calc_blowup l =
wenzelm@33317
   273
  let val (p,n) = List.partition (curry (op <) 0) (filter (curry (op <>) 0) l)
wenzelm@24630
   274
  in length p * length n end;
nipkow@5982
   275
nipkow@5982
   276
(* ------------------------------------------------------------------------- *)
nipkow@5982
   277
(* Main elimination code:                                                    *)
nipkow@5982
   278
(*                                                                           *)
nipkow@5982
   279
(* (1) Looks for immediate solutions (false assertions with no variables).   *)
nipkow@5982
   280
(*                                                                           *)
nipkow@5982
   281
(* (2) If there are any equations, picks a variable with the lowest absolute *)
nipkow@5982
   282
(* coefficient in any of them, and uses it to eliminate.                     *)
nipkow@5982
   283
(*                                                                           *)
nipkow@5982
   284
(* (3) Otherwise, chooses a variable in the inequality to minimize the       *)
nipkow@5982
   285
(* blowup (number of consequences generated) and eliminates it.              *)
nipkow@5982
   286
(* ------------------------------------------------------------------------- *)
nipkow@5982
   287
nipkow@5982
   288
fun extract_first p =
boehmes@31510
   289
  let
boehmes@31510
   290
    fun extract xs (y::ys) = if p y then (y, xs @ ys) else extract (y::xs) ys
wenzelm@47060
   291
      | extract xs [] = raise List.Empty
nipkow@5982
   292
  in extract [] end;
nipkow@5982
   293
wenzelm@44654
   294
fun print_ineqs ctxt ineqs =
wenzelm@44654
   295
  if Config.get ctxt LA_Data.trace then
wenzelm@12262
   296
     tracing(cat_lines(""::map (fn Lineq(c,t,l,_) =>
wenzelm@24630
   297
       string_of_int c ^
paulson@9073
   298
       (case t of Eq => " =  " | Lt=> " <  " | Le => " <= ") ^
wenzelm@24630
   299
       commas(map string_of_int l)) ineqs))
paulson@9073
   300
  else ();
nipkow@6056
   301
nipkow@13498
   302
type history = (int * lineq list) list;
nipkow@13498
   303
datatype result = Success of injust | Failure of history;
nipkow@13498
   304
wenzelm@44654
   305
fun elim ctxt (ineqs, hist) =
wenzelm@44654
   306
  let val _ = print_ineqs ctxt ineqs
webertj@20217
   307
      val (triv, nontriv) = List.partition is_trivial ineqs in
webertj@20217
   308
  if not (null triv)
wenzelm@59584
   309
  then case find_first is_contradictory triv of
wenzelm@44654
   310
         NONE => elim ctxt (nontriv, hist)
skalberg@15531
   311
       | SOME(Lineq(_,_,_,j)) => Success j
nipkow@5982
   312
  else
webertj@20217
   313
  if null nontriv then Failure hist
nipkow@13498
   314
  else
webertj@20217
   315
  let val (eqs, noneqs) = List.partition (fn (Lineq(_,ty,_,_)) => ty=Eq) nontriv in
webertj@20217
   316
  if not (null eqs) then
boehmes@31510
   317
     let val c =
haftmann@33042
   318
           fold (fn Lineq(_,_,l,_) => fn cs => union (op =) l cs) eqs []
boehmes@31510
   319
           |> filter (fn i => i <> 0)
wenzelm@59058
   320
           |> sort (int_ord o apply2 abs)
boehmes@31510
   321
           |> hd
boehmes@31510
   322
         val (eq as Lineq(_,_,ceq,_),othereqs) =
haftmann@36692
   323
               extract_first (fn Lineq(_,_,l,_) => member (op =) l c) eqs
haftmann@31986
   324
         val v = find_index (fn v => v = c) ceq
haftmann@23063
   325
         val (ioth,roth) = List.partition (fn (Lineq(_,_,l,_)) => nth l v = 0)
nipkow@5982
   326
                                     (othereqs @ noneqs)
nipkow@5982
   327
         val others = map (elim_var v eq) roth @ ioth
wenzelm@44654
   328
     in elim ctxt (others,(v,nontriv)::hist) end
nipkow@5982
   329
  else
nipkow@5982
   330
  let val lists = map (fn (Lineq(_,_,l,_)) => l) noneqs
haftmann@23063
   331
      val numlist = 0 upto (length (hd lists) - 1)
haftmann@23063
   332
      val coeffs = map (fn i => map (fn xs => nth xs i) lists) numlist
nipkow@5982
   333
      val blows = map calc_blowup coeffs
nipkow@5982
   334
      val iblows = blows ~~ numlist
haftmann@23063
   335
      val nziblows = filter_out (fn (i, _) => i = 0) iblows
nipkow@13498
   336
  in if null nziblows then Failure((~1,nontriv)::hist)
nipkow@13498
   337
     else
haftmann@60348
   338
     let val (_,v) = hd(sort (fn (x,y) => int_ord(fst(x),fst(y))) nziblows)
haftmann@23063
   339
         val (no,yes) = List.partition (fn (Lineq(_,_,l,_)) => nth l v = 0) ineqs
haftmann@23063
   340
         val (pos,neg) = List.partition(fn (Lineq(_,_,l,_)) => nth l v > 0) yes
wenzelm@44654
   341
     in elim ctxt (no @ map_product (elim_var v) pos neg, (v,nontriv)::hist) end
nipkow@5982
   342
  end
nipkow@5982
   343
  end
nipkow@5982
   344
  end;
nipkow@5982
   345
nipkow@5982
   346
(* ------------------------------------------------------------------------- *)
nipkow@5982
   347
(* Translate back a proof.                                                   *)
nipkow@5982
   348
(* ------------------------------------------------------------------------- *)
nipkow@5982
   349
wenzelm@44654
   350
fun trace_thm ctxt msgs th =
wenzelm@44654
   351
 (if Config.get ctxt LA_Data.trace
wenzelm@61268
   352
  then tracing (cat_lines (msgs @ [Thm.string_of_thm ctxt th]))
wenzelm@44654
   353
  else (); th);
paulson@9073
   354
wenzelm@44654
   355
fun trace_term ctxt msgs t =
wenzelm@44654
   356
 (if Config.get ctxt LA_Data.trace
wenzelm@44654
   357
  then tracing (cat_lines (msgs @ [Syntax.string_of_term ctxt t]))
wenzelm@44654
   358
  else (); t);
wenzelm@24076
   359
wenzelm@44654
   360
fun trace_msg ctxt msg =
wenzelm@44654
   361
  if Config.get ctxt LA_Data.trace then tracing msg else ();
paulson@9073
   362
wenzelm@52131
   363
val union_term = union Envir.aeconv;
berghofe@26835
   364
boehmes@31510
   365
fun add_atoms (lhs, _, _, rhs, _, _) =
boehmes@31510
   366
  union_term (map fst lhs) o union_term (map fst rhs);
nipkow@6056
   367
boehmes@31510
   368
fun atoms_of ds = fold add_atoms ds [];
boehmes@31510
   369
boehmes@31510
   370
(*
nipkow@6056
   371
Simplification may detect a contradiction 'prematurely' due to type
nipkow@6056
   372
information: n+1 <= 0 is simplified to False and does not need to be crossed
nipkow@6056
   373
with 0 <= n.
nipkow@6056
   374
*)
nipkow@6056
   375
local
wenzelm@24076
   376
  exception FalseE of thm
nipkow@6056
   377
in
wenzelm@27020
   378
wenzelm@51717
   379
fun mkthm ctxt asms (just: injust) =
wenzelm@24076
   380
  let
wenzelm@42361
   381
    val thy = Proof_Context.theory_of ctxt;
wenzelm@61097
   382
    val {add_mono_thms = add_mono_thms0, mult_mono_thms = mult_mono_thms0,
wenzelm@61097
   383
      inj_thms = inj_thms0, lessD = lessD0, simpset, ...} = get_data ctxt;
wenzelm@61097
   384
    val add_mono_thms = map (Thm.transfer thy) add_mono_thms0;
wenzelm@61097
   385
    val mult_mono_thms = map (Thm.transfer thy) mult_mono_thms0;
wenzelm@61097
   386
    val inj_thms = map (Thm.transfer thy) inj_thms0;
wenzelm@61097
   387
    val lessD = map (Thm.transfer thy) lessD0;
wenzelm@61097
   388
wenzelm@38763
   389
    val number_of = number_of ctxt;
wenzelm@51717
   390
    val simpset_ctxt = put_simpset simpset ctxt;
boehmes@31510
   391
    fun only_concl f thm =
boehmes@31510
   392
      if Thm.no_prems thm then f (Thm.concl_of thm) else NONE;
boehmes@31510
   393
    val atoms = atoms_of (map_filter (only_concl (LA_Data.decomp ctxt)) asms);
boehmes@31510
   394
boehmes@31510
   395
    fun use_first rules thm =
boehmes@31510
   396
      get_first (fn th => SOME (thm RS th) handle THM _ => NONE) rules
boehmes@31510
   397
boehmes@31510
   398
    fun add2 thm1 thm2 =
boehmes@31510
   399
      use_first add_mono_thms (thm1 RS (thm2 RS LA_Logic.conjI));
boehmes@31510
   400
    fun try_add thms thm = get_first (fn th => add2 th thm) thms;
nipkow@6056
   401
boehmes@31510
   402
    fun add_thms thm1 thm2 =
boehmes@31510
   403
      (case add2 thm1 thm2 of
boehmes@31510
   404
        NONE =>
boehmes@31510
   405
          (case try_add ([thm1] RL inj_thms) thm2 of
boehmes@31510
   406
            NONE =>
boehmes@31510
   407
              (the (try_add ([thm2] RL inj_thms) thm1)
wenzelm@51930
   408
                handle Option.Option =>
wenzelm@44654
   409
                  (trace_thm ctxt [] thm1; trace_thm ctxt [] thm2;
wenzelm@40316
   410
                   raise Fail "Linear arithmetic: failed to add thms"))
boehmes@31510
   411
          | SOME thm => thm)
boehmes@31510
   412
      | SOME thm => thm);
boehmes@31510
   413
boehmes@31510
   414
    fun mult_by_add n thm =
boehmes@31510
   415
      let fun mul i th = if i = 1 then th else mul (i - 1) (add_thms thm th)
boehmes@31510
   416
      in mul n thm end;
nipkow@10575
   417
wenzelm@51717
   418
    val rewr = Simplifier.rewrite simpset_ctxt;
boehmes@31510
   419
    val rewrite_concl = Conv.fconv_rule (Conv.concl_conv ~1 (Conv.arg_conv
boehmes@31510
   420
      (Conv.binop_conv rewr)));
boehmes@31510
   421
    fun discharge_prem thm = if Thm.nprems_of thm = 0 then thm else
boehmes@31510
   422
      let val cv = Conv.arg1_conv (Conv.arg_conv rewr)
boehmes@31510
   423
      in Thm.implies_elim (Conv.fconv_rule cv thm) LA_Logic.trueI end
webertj@20217
   424
boehmes@31510
   425
    fun mult n thm =
boehmes@31510
   426
      (case use_first mult_mono_thms thm of
boehmes@31510
   427
        NONE => mult_by_add n thm
boehmes@31510
   428
      | SOME mth =>
boehmes@31510
   429
          let
boehmes@31510
   430
            val cv = mth |> Thm.cprop_of |> Drule.strip_imp_concl
boehmes@31510
   431
              |> Thm.dest_arg |> Thm.dest_arg1 |> Thm.dest_arg1
wenzelm@59586
   432
            val T = Thm.typ_of_cterm cv
boehmes@31510
   433
          in
boehmes@31510
   434
            mth
wenzelm@60642
   435
            |> Thm.instantiate ([], [(dest_Var (Thm.term_of cv), number_of T n)])
boehmes@31510
   436
            |> rewrite_concl
boehmes@31510
   437
            |> discharge_prem
boehmes@31510
   438
            handle CTERM _ => mult_by_add n thm
boehmes@31510
   439
                 | THM _ => mult_by_add n thm
boehmes@31510
   440
          end);
nipkow@10691
   441
boehmes@31510
   442
    fun mult_thm (n, thm) =
boehmes@31510
   443
      if n = ~1 then thm RS LA_Logic.sym
boehmes@31510
   444
      else if n < 0 then mult (~n) thm RS LA_Logic.sym
boehmes@31510
   445
      else mult n thm;
boehmes@31510
   446
boehmes@31510
   447
    fun simp thm =
wenzelm@51717
   448
      let val thm' = trace_thm ctxt ["Simplified:"] (full_simplify simpset_ctxt thm)
boehmes@31510
   449
      in if LA_Logic.is_False thm' then raise FalseE thm' else thm' end;
nipkow@6056
   450
wenzelm@44654
   451
    fun mk (Asm i) = trace_thm ctxt ["Asm " ^ string_of_int i] (nth asms i)
wenzelm@44654
   452
      | mk (Nat i) = trace_thm ctxt ["Nat " ^ string_of_int i] (LA_Logic.mk_nat_thm thy (nth atoms i))
wenzelm@44654
   453
      | mk (LessD j) = trace_thm ctxt ["L"] (hd ([mk j] RL lessD))
wenzelm@44654
   454
      | mk (NotLeD j) = trace_thm ctxt ["NLe"] (mk j RS LA_Logic.not_leD)
wenzelm@44654
   455
      | mk (NotLeDD j) = trace_thm ctxt ["NLeD"] (hd ([mk j RS LA_Logic.not_leD] RL lessD))
wenzelm@44654
   456
      | mk (NotLessD j) = trace_thm ctxt ["NL"] (mk j RS LA_Logic.not_lessD)
wenzelm@44654
   457
      | mk (Added (j1, j2)) = simp (trace_thm ctxt ["+"] (add_thms (mk j1) (mk j2)))
wenzelm@32091
   458
      | mk (Multiplied (n, j)) =
wenzelm@44654
   459
          (trace_msg ctxt ("*" ^ string_of_int n); trace_thm ctxt ["*"] (mult_thm (n, mk j)))
nipkow@5982
   460
wenzelm@27020
   461
  in
wenzelm@27020
   462
    let
wenzelm@44654
   463
      val _ = trace_msg ctxt "mkthm";
wenzelm@44654
   464
      val thm = trace_thm ctxt ["Final thm:"] (mk just);
wenzelm@51717
   465
      val fls = simplify simpset_ctxt thm;
wenzelm@44654
   466
      val _ = trace_thm ctxt ["After simplification:"] fls;
wenzelm@27020
   467
      val _ =
wenzelm@27020
   468
        if LA_Logic.is_False fls then ()
wenzelm@27020
   469
        else
boehmes@35872
   470
         (tracing (cat_lines
wenzelm@61268
   471
           (["Assumptions:"] @ map (Thm.string_of_thm ctxt) asms @ [""] @
wenzelm@61268
   472
            ["Proved:", Thm.string_of_thm ctxt fls, ""]));
boehmes@35872
   473
          warning "Linear arithmetic should have refuted the assumptions.\n\
boehmes@35872
   474
            \Please inform Tobias Nipkow.")
wenzelm@27020
   475
    in fls end
wenzelm@44654
   476
    handle FalseE thm => trace_thm ctxt ["False reached early:"] thm
wenzelm@27020
   477
  end;
wenzelm@27020
   478
nipkow@6056
   479
end;
nipkow@5982
   480
haftmann@23261
   481
fun coeff poly atom =
wenzelm@52131
   482
  AList.lookup Envir.aeconv poly atom |> the_default 0;
nipkow@10691
   483
nipkow@10691
   484
fun integ(rlhs,r,rel,rrhs,s,d) =
wenzelm@63201
   485
let val (rn,rd) = Rat.dest r and (sn,sd) = Rat.dest s
wenzelm@63227
   486
    val m = Integer.lcms(map (snd o Rat.dest) (r :: s :: map snd rlhs @ map snd rrhs))
wenzelm@22846
   487
    fun mult(t,r) =
wenzelm@63201
   488
        let val (i,j) = Rat.dest r
paulson@15965
   489
        in (t,i * (m div j)) end
nipkow@12932
   490
in (m,(map mult rlhs, rn*(m div rd), rel, map mult rrhs, sn*(m div sd), d)) end
nipkow@10691
   491
haftmann@38052
   492
fun mklineq atoms =
webertj@20217
   493
  fn (item, k) =>
webertj@20217
   494
  let val (m, (lhs,i,rel,rhs,j,discrete)) = integ item
nipkow@13498
   495
      val lhsa = map (coeff lhs) atoms
nipkow@13498
   496
      and rhsa = map (coeff rhs) atoms
haftmann@18330
   497
      val diff = map2 (curry (op -)) rhsa lhsa
nipkow@13498
   498
      val c = i-j
nipkow@13498
   499
      val just = Asm k
boehmes@31511
   500
      fun lineq(c,le,cs,j) = Lineq(c,le,cs, if m=1 then j else Multiplied(m,j))
nipkow@13498
   501
  in case rel of
nipkow@13498
   502
      "<="   => lineq(c,Le,diff,just)
nipkow@13498
   503
     | "~<=" => if discrete
nipkow@13498
   504
                then lineq(1-c,Le,map (op ~) diff,NotLeDD(just))
nipkow@13498
   505
                else lineq(~c,Lt,map (op ~) diff,NotLeD(just))
nipkow@13498
   506
     | "<"   => if discrete
nipkow@13498
   507
                then lineq(c+1,Le,diff,LessD(just))
nipkow@13498
   508
                else lineq(c,Lt,diff,just)
nipkow@13498
   509
     | "~<"  => lineq(~c,Le,map (op~) diff,NotLessD(just))
nipkow@13498
   510
     | "="   => lineq(c,Eq,diff,just)
wenzelm@40316
   511
     | _     => raise Fail ("mklineq" ^ rel)
nipkow@5982
   512
  end;
nipkow@5982
   513
nipkow@13498
   514
(* ------------------------------------------------------------------------- *)
nipkow@13498
   515
(* Print (counter) example                                                   *)
nipkow@13498
   516
(* ------------------------------------------------------------------------- *)
nipkow@13498
   517
webertj@20217
   518
(* ------------------------------------------------------------------------- *)
webertj@20217
   519
webertj@20268
   520
fun mknat (pTs : typ list) (ixs : int list) (atom : term, i : int) : lineq option =
webertj@20217
   521
  if LA_Logic.is_nat (pTs, atom)
nipkow@6056
   522
  then let val l = map (fn j => if j=i then 1 else 0) ixs
webertj@20217
   523
       in SOME (Lineq (0, Le, l, Nat i)) end
webertj@20217
   524
  else NONE;
nipkow@6056
   525
nipkow@13186
   526
(* This code is tricky. It takes a list of premises in the order they occur
skalberg@15531
   527
in the subgoal. Numerical premises are coded as SOME(tuple), non-numerical
skalberg@15531
   528
ones as NONE. Going through the premises, each numeric one is converted into
nipkow@13186
   529
a Lineq. The tricky bit is to convert ~= which is split into two cases < and
nipkow@13498
   530
>. Thus split_items returns a list of equation systems. This may blow up if
nipkow@13186
   531
there are many ~=, but in practice it does not seem to happen. The really
nipkow@13186
   532
tricky bit is to arrange the order of the cases such that they coincide with
nipkow@13186
   533
the order in which the cases are in the end generated by the tactic that
nipkow@13186
   534
applies the generated refutation thms (see function 'refute_tac').
nipkow@13186
   535
nipkow@13186
   536
For variables n of type nat, a constraint 0 <= n is added.
nipkow@13186
   537
*)
webertj@20217
   538
webertj@20217
   539
(* FIXME: To optimize, the splitting of cases and the search for refutations *)
webertj@20276
   540
(*        could be intertwined: separate the first (fully split) case,       *)
webertj@20217
   541
(*        refute it, continue with splitting and refuting.  Terminate with   *)
webertj@20217
   542
(*        failure as soon as a case could not be refuted; i.e. delay further *)
webertj@20217
   543
(*        splitting until after a refutation for other cases has been found. *)
webertj@20217
   544
webertj@30406
   545
fun split_items ctxt do_pre split_neq (Ts, terms) : (typ list * (LA_Data.decomp * int) list) list =
webertj@20276
   546
let
webertj@20276
   547
  (* splits inequalities '~=' into '<' and '>'; this corresponds to *)
webertj@20276
   548
  (* 'REPEAT_DETERM (eresolve_tac neqE i)' at the theorem/tactic    *)
webertj@20276
   549
  (* level                                                          *)
webertj@20276
   550
  (* FIXME: this is currently sensitive to the order of theorems in *)
webertj@20276
   551
  (*        neqE:  The theorem for type "nat" must come first.  A   *)
webertj@20276
   552
  (*        better (i.e. less likely to break when neqE changes)    *)
webertj@20276
   553
  (*        implementation should *test* which theorem from neqE    *)
webertj@20276
   554
  (*        can be applied, and split the premise accordingly.      *)
wenzelm@26945
   555
  fun elim_neq (ineqs : (LA_Data.decomp option * bool) list) :
wenzelm@26945
   556
               (LA_Data.decomp option * bool) list list =
webertj@20276
   557
  let
wenzelm@26945
   558
    fun elim_neq' nat_only ([] : (LA_Data.decomp option * bool) list) :
wenzelm@26945
   559
                  (LA_Data.decomp option * bool) list list =
webertj@20276
   560
          [[]]
webertj@20276
   561
      | elim_neq' nat_only ((NONE, is_nat) :: ineqs) =
webertj@20276
   562
          map (cons (NONE, is_nat)) (elim_neq' nat_only ineqs)
webertj@20276
   563
      | elim_neq' nat_only ((ineq as (SOME (l, i, rel, r, j, d), is_nat)) :: ineqs) =
webertj@20276
   564
          if rel = "~=" andalso (not nat_only orelse is_nat) then
webertj@20276
   565
            (* [| ?l ~= ?r; ?l < ?r ==> ?R; ?r < ?l ==> ?R |] ==> ?R *)
webertj@20276
   566
            elim_neq' nat_only (ineqs @ [(SOME (l, i, "<", r, j, d), is_nat)]) @
webertj@20276
   567
            elim_neq' nat_only (ineqs @ [(SOME (r, j, "<", l, i, d), is_nat)])
webertj@20276
   568
          else
webertj@20276
   569
            map (cons ineq) (elim_neq' nat_only ineqs)
webertj@20276
   570
  in
webertj@20276
   571
    ineqs |> elim_neq' true
wenzelm@26945
   572
          |> maps (elim_neq' false)
webertj@20276
   573
  end
nipkow@13464
   574
webertj@30406
   575
  fun ignore_neq (NONE, bool) = (NONE, bool)
webertj@30406
   576
    | ignore_neq (ineq as SOME (_, _, rel, _, _, _), bool) =
webertj@30406
   577
      if rel = "~=" then (NONE, bool) else (ineq, bool)
webertj@30406
   578
webertj@20276
   579
  fun number_hyps _ []             = []
webertj@20276
   580
    | number_hyps n (NONE::xs)     = number_hyps (n+1) xs
webertj@20276
   581
    | number_hyps n ((SOME x)::xs) = (x, n) :: number_hyps (n+1) xs
webertj@20276
   582
webertj@20276
   583
  val result = (Ts, terms)
webertj@20276
   584
    |> (* user-defined preprocessing of the subgoal *)
wenzelm@24076
   585
       (if do_pre then LA_Data.pre_decomp ctxt else Library.single)
wenzelm@44654
   586
    |> tap (fn subgoals => trace_msg ctxt ("Preprocessing yields " ^
webertj@23195
   587
         string_of_int (length subgoals) ^ " subgoal(s) total."))
wenzelm@22846
   588
    |> (* produce the internal encoding of (in-)equalities *)
wenzelm@24076
   589
       map (apsnd (map (fn t => (LA_Data.decomp ctxt t, LA_Data.domain_is_nat t))))
webertj@20276
   590
    |> (* splitting of inequalities *)
webertj@30406
   591
       map (apsnd (if split_neq then elim_neq else
webertj@30406
   592
                     Library.single o map ignore_neq))
wenzelm@22846
   593
    |> maps (fn (Ts, subgoals) => map (pair Ts o map fst) subgoals)
webertj@20276
   594
    |> (* numbering of hypotheses, ignoring irrelevant ones *)
webertj@20276
   595
       map (apsnd (number_hyps 0))
webertj@23195
   596
in
wenzelm@44654
   597
  trace_msg ctxt ("Splitting of inequalities yields " ^
webertj@23195
   598
    string_of_int (length result) ^ " subgoal(s) total.");
webertj@23195
   599
  result
webertj@23195
   600
end;
nipkow@13464
   601
wenzelm@59656
   602
fun refutes ctxt :
wenzelm@26945
   603
    (typ list * (LA_Data.decomp * int) list) list -> injust list -> injust list option =
wenzelm@26945
   604
  let
wenzelm@26945
   605
    fun refute ((Ts, initems : (LA_Data.decomp * int) list) :: initemss) (js: injust list) =
wenzelm@26945
   606
          let
boehmes@31510
   607
            val atoms = atoms_of (map fst initems)
wenzelm@26945
   608
            val n = length atoms
haftmann@38052
   609
            val mkleq = mklineq atoms
wenzelm@26945
   610
            val ixs = 0 upto (n - 1)
wenzelm@26945
   611
            val iatoms = atoms ~~ ixs
wenzelm@32952
   612
            val natlineqs = map_filter (mknat Ts ixs) iatoms
wenzelm@26945
   613
            val ineqs = map mkleq initems @ natlineqs
wenzelm@59656
   614
          in
wenzelm@59656
   615
            (case elim ctxt (ineqs, []) of
wenzelm@26945
   616
               Success j =>
wenzelm@44654
   617
                 (trace_msg ctxt ("Contradiction! (" ^ string_of_int (length js + 1) ^ ")");
wenzelm@26945
   618
                  refute initemss (js @ [j]))
wenzelm@59656
   619
             | Failure _ => NONE)
wenzelm@26945
   620
          end
wenzelm@26945
   621
      | refute [] js = SOME js
wenzelm@26945
   622
  in refute end;
nipkow@5982
   623
wenzelm@59656
   624
fun refute ctxt params do_pre split_neq terms : injust list option =
wenzelm@59656
   625
  refutes ctxt (split_items ctxt do_pre split_neq (map snd params, terms)) [];
webertj@20254
   626
haftmann@22950
   627
fun count P xs = length (filter P xs);
webertj@20254
   628
wenzelm@59656
   629
fun prove ctxt params do_pre Hs concl : bool * injust list option =
webertj@20254
   630
  let
wenzelm@44654
   631
    val _ = trace_msg ctxt "prove:"
webertj@20254
   632
    (* append the negated conclusion to 'Hs' -- this corresponds to     *)
webertj@20254
   633
    (* 'DETERM (resolve_tac [LA_Logic.notI, LA_Logic.ccontr] i)' at the *)
webertj@20254
   634
    (* theorem/tactic level                                             *)
webertj@20254
   635
    val Hs' = Hs @ [LA_Logic.neg_prop concl]
webertj@20254
   636
    fun is_neq NONE                 = false
webertj@20254
   637
      | is_neq (SOME (_,_,r,_,_,_)) = (r = "~=")
wenzelm@44654
   638
    val neq_limit = Config.get ctxt LA_Data.neq_limit
webertj@30406
   639
    val split_neq = count is_neq (map (LA_Data.decomp ctxt) Hs') <= neq_limit
webertj@20254
   640
  in
webertj@30406
   641
    if split_neq then ()
wenzelm@24076
   642
    else
wenzelm@44654
   643
      trace_msg ctxt ("neq_limit exceeded (current value is " ^
webertj@30406
   644
        string_of_int neq_limit ^ "), ignoring all inequalities");
wenzelm@59656
   645
    (split_neq, refute ctxt params do_pre split_neq Hs')
webertj@23190
   646
  end handle TERM ("neg_prop", _) =>
webertj@23190
   647
    (* since no meta-logic negation is available, we can only fail if   *)
webertj@23190
   648
    (* the conclusion is not of the form 'Trueprop $ _' (simply         *)
webertj@23190
   649
    (* dropping the conclusion doesn't work either, because even        *)
webertj@23190
   650
    (* 'False' does not imply arbitrary 'concl::prop')                  *)
wenzelm@44654
   651
    (trace_msg ctxt "prove failed (cannot negate conclusion).";
webertj@30406
   652
      (false, NONE));
webertj@20217
   653
wenzelm@51717
   654
fun refute_tac ctxt (i, split_neq, justs) =
nipkow@6074
   655
  fn state =>
wenzelm@24076
   656
    let
wenzelm@32091
   657
      val _ = trace_thm ctxt
wenzelm@44654
   658
        ["refute_tac (on subgoal " ^ string_of_int i ^ ", with " ^
wenzelm@44654
   659
          string_of_int (length justs) ^ " justification(s)):"] state
wenzelm@61097
   660
      val neqE = get_neqE ctxt;
wenzelm@24076
   661
      fun just1 j =
wenzelm@24076
   662
        (* eliminate inequalities *)
webertj@30406
   663
        (if split_neq then
wenzelm@59498
   664
          REPEAT_DETERM (eresolve_tac ctxt neqE i)
webertj@30406
   665
        else
webertj@30406
   666
          all_tac) THEN
wenzelm@44654
   667
          PRIMITIVE (trace_thm ctxt ["State after neqE:"]) THEN
wenzelm@24076
   668
          (* use theorems generated from the actual justifications *)
wenzelm@59498
   669
          Subgoal.FOCUS (fn {prems, ...} => resolve_tac ctxt [mkthm ctxt prems j] 1) ctxt i
wenzelm@24076
   670
    in
wenzelm@24076
   671
      (* rewrite "[| A1; ...; An |] ==> B" to "[| A1; ...; An; ~B |] ==> False" *)
wenzelm@59498
   672
      DETERM (resolve_tac ctxt [LA_Logic.notI, LA_Logic.ccontr] i) THEN
wenzelm@24076
   673
      (* user-defined preprocessing of the subgoal *)
wenzelm@51717
   674
      DETERM (LA_Data.pre_tac ctxt i) THEN
wenzelm@44654
   675
      PRIMITIVE (trace_thm ctxt ["State after pre_tac:"]) THEN
wenzelm@24076
   676
      (* prove every resulting subgoal, using its justification *)
wenzelm@24076
   677
      EVERY (map just1 justs)
webertj@20217
   678
    end  state;
nipkow@6074
   679
nipkow@5982
   680
(*
nipkow@5982
   681
Fast but very incomplete decider. Only premises and conclusions
nipkow@5982
   682
that are already (negated) (in)equations are taken into account.
nipkow@5982
   683
*)
wenzelm@59656
   684
fun simpset_lin_arith_tac ctxt = SUBGOAL (fn (A, i) =>
wenzelm@24076
   685
  let
wenzelm@24076
   686
    val params = rev (Logic.strip_params A)
wenzelm@24076
   687
    val Hs = Logic.strip_assums_hyp A
wenzelm@24076
   688
    val concl = Logic.strip_assums_concl A
wenzelm@44654
   689
    val _ = trace_term ctxt ["Trying to refute subgoal " ^ string_of_int i] A
wenzelm@24076
   690
  in
wenzelm@59656
   691
    case prove ctxt params true Hs concl of
wenzelm@44654
   692
      (_, NONE) => (trace_msg ctxt "Refutation failed."; no_tac)
wenzelm@44654
   693
    | (split_neq, SOME js) => (trace_msg ctxt "Refutation succeeded.";
wenzelm@51717
   694
                               refute_tac ctxt (i, split_neq, js))
wenzelm@24076
   695
  end);
nipkow@5982
   696
wenzelm@51717
   697
fun prems_lin_arith_tac ctxt =
wenzelm@61841
   698
  Method.insert_tac ctxt (Simplifier.prems_of ctxt) THEN'
wenzelm@59656
   699
  simpset_lin_arith_tac ctxt;
wenzelm@17613
   700
wenzelm@24076
   701
fun lin_arith_tac ctxt =
wenzelm@51717
   702
  simpset_lin_arith_tac (empty_simpset ctxt);
wenzelm@24076
   703
wenzelm@24076
   704
nipkow@5982
   705
nipkow@13186
   706
(** Forward proof from theorems **)
nipkow@13186
   707
webertj@20433
   708
(* More tricky code. Needs to arrange the proofs of the multiple cases (due
webertj@20433
   709
to splits of ~= premises) such that it coincides with the order of the cases
webertj@20433
   710
generated by function split_items. *)
webertj@20433
   711
webertj@20433
   712
datatype splittree = Tip of thm list
webertj@20433
   713
                   | Spl of thm * cterm * splittree * cterm * splittree;
webertj@20433
   714
webertj@20433
   715
(* "(ct1 ==> ?R) ==> (ct2 ==> ?R) ==> ?R" is taken to (ct1, ct2) *)
webertj@20433
   716
webertj@20433
   717
fun extract (imp : cterm) : cterm * cterm =
webertj@20433
   718
let val (Il, r)    = Thm.dest_comb imp
webertj@20433
   719
    val (_, imp1)  = Thm.dest_comb Il
webertj@20433
   720
    val (Ict1, _)  = Thm.dest_comb imp1
webertj@20433
   721
    val (_, ct1)   = Thm.dest_comb Ict1
webertj@20433
   722
    val (Ir, _)    = Thm.dest_comb r
webertj@20433
   723
    val (_, Ict2r) = Thm.dest_comb Ir
webertj@20433
   724
    val (Ict2, _)  = Thm.dest_comb Ict2r
webertj@20433
   725
    val (_, ct2)   = Thm.dest_comb Ict2
webertj@20433
   726
in (ct1, ct2) end;
webertj@20433
   727
wenzelm@24076
   728
fun splitasms ctxt (asms : thm list) : splittree =
wenzelm@61097
   729
let val neqE = get_neqE ctxt
hoelzl@35693
   730
    fun elim_neq [] (asms', []) = Tip (rev asms')
hoelzl@35693
   731
      | elim_neq [] (asms', asms) = Tip (rev asms' @ asms)
haftmann@49387
   732
      | elim_neq (_ :: neqs) (asms', []) = elim_neq neqs ([],rev asms')
hoelzl@35693
   733
      | elim_neq (neqs as (neq :: _)) (asms', asm::asms) =
hoelzl@35693
   734
      (case get_first (fn th => SOME (asm COMP th) handle THM _ => NONE) [neq] of
webertj@20433
   735
        SOME spl =>
wenzelm@59582
   736
          let val (ct1, ct2) = extract (Thm.cprop_of spl)
wenzelm@36945
   737
              val thm1 = Thm.assume ct1
wenzelm@36945
   738
              val thm2 = Thm.assume ct2
hoelzl@35693
   739
          in Spl (spl, ct1, elim_neq neqs (asms', asms@[thm1]),
hoelzl@35693
   740
            ct2, elim_neq neqs (asms', asms@[thm2]))
webertj@20433
   741
          end
hoelzl@35693
   742
      | NONE => elim_neq neqs (asm::asms', asms))
hoelzl@35693
   743
in elim_neq neqE ([], asms) end;
webertj@20433
   744
wenzelm@51717
   745
fun fwdproof ctxt (Tip asms : splittree) (j::js : injust list) = (mkthm ctxt asms j, js)
wenzelm@51717
   746
  | fwdproof ctxt (Spl (thm, ct1, tree1, ct2, tree2)) js =
wenzelm@24076
   747
      let
wenzelm@51717
   748
        val (thm1, js1) = fwdproof ctxt tree1 js
wenzelm@51717
   749
        val (thm2, js2) = fwdproof ctxt tree2 js1
wenzelm@36945
   750
        val thm1' = Thm.implies_intr ct1 thm1
wenzelm@36945
   751
        val thm2' = Thm.implies_intr ct2 thm2
wenzelm@24076
   752
      in (thm2' COMP (thm1' COMP thm), js2) end;
wenzelm@24076
   753
      (* FIXME needs handle THM _ => NONE ? *)
webertj@20433
   754
wenzelm@51717
   755
fun prover ctxt thms Tconcl (js : injust list) split_neq pos : thm option =
wenzelm@24076
   756
  let
wenzelm@24076
   757
    val nTconcl = LA_Logic.neg_prop Tconcl
wenzelm@59642
   758
    val cnTconcl = Thm.cterm_of ctxt nTconcl
wenzelm@36945
   759
    val nTconclthm = Thm.assume cnTconcl
webertj@30406
   760
    val tree = (if split_neq then splitasms ctxt else Tip) (thms @ [nTconclthm])
wenzelm@51717
   761
    val (Falsethm, _) = fwdproof ctxt tree js
wenzelm@24076
   762
    val contr = if pos then LA_Logic.ccontr else LA_Logic.notI
wenzelm@36945
   763
    val concl = Thm.implies_intr cnTconcl Falsethm COMP contr
wenzelm@44654
   764
  in SOME (trace_thm ctxt ["Proved by lin. arith. prover:"] (LA_Logic.mk_Eq concl)) end
wenzelm@24076
   765
  (*in case concl contains ?-var, which makes assume fail:*)   (* FIXME Variable.import_terms *)
wenzelm@24076
   766
  handle THM _ => NONE;
nipkow@13186
   767
nipkow@13186
   768
(* PRE: concl is not negated!
nipkow@13186
   769
   This assumption is OK because
wenzelm@24076
   770
   1. lin_arith_simproc tries both to prove and disprove concl and
wenzelm@24076
   771
   2. lin_arith_simproc is applied by the Simplifier which
nipkow@13186
   772
      dives into terms and will thus try the non-negated concl anyway.
nipkow@13186
   773
*)
wenzelm@51717
   774
fun lin_arith_simproc ctxt concl =
wenzelm@24076
   775
  let
wenzelm@51717
   776
    val thms = maps LA_Logic.atomize (Simplifier.prems_of ctxt)
wenzelm@24076
   777
    val Hs = map Thm.prop_of thms
wenzelm@61144
   778
    val Tconcl = LA_Logic.mk_Trueprop (Thm.term_of concl)
wenzelm@24076
   779
  in
wenzelm@59656
   780
    case prove ctxt [] false Hs Tconcl of (* concl provable? *)
wenzelm@51717
   781
      (split_neq, SOME js) => prover ctxt thms Tconcl js split_neq true
webertj@30406
   782
    | (_, NONE) =>
wenzelm@24076
   783
        let val nTconcl = LA_Logic.neg_prop Tconcl in
wenzelm@59656
   784
          case prove ctxt [] false Hs nTconcl of (* ~concl provable? *)
wenzelm@51717
   785
            (split_neq, SOME js) => prover ctxt thms nTconcl js split_neq false
webertj@30406
   786
          | (_, NONE) => NONE
wenzelm@24076
   787
        end
wenzelm@24076
   788
  end;
nipkow@6074
   789
nipkow@6074
   790
end;