src/HOL/Tools/Nitpick/nitpick_preproc.ML
author blanchet
Thu, 25 Feb 2010 16:33:39 +0100
changeset 35385 29f81babefd7
parent 35384 88dbcfe75c45
child 35386 45a4e19d3ebd
permissions -rw-r--r--
improved precision of infinite "shallow" datatypes in Nitpick;
e.g. strings used for variable names, instead of an opaque type
blanchet@35067
     1
(*  Title:      HOL/Tools/Nitpick/nitpick_preproc.ML
blanchet@35067
     2
    Author:     Jasmin Blanchette, TU Muenchen
blanchet@35067
     3
    Copyright   2008, 2009, 2010
blanchet@35067
     4
blanchet@35067
     5
Nitpick's HOL preprocessor.
blanchet@35067
     6
*)
blanchet@35067
     7
blanchet@35067
     8
signature NITPICK_PREPROC =
blanchet@35067
     9
sig
blanchet@35067
    10
  type hol_context = Nitpick_HOL.hol_context
blanchet@35067
    11
  val preprocess_term :
blanchet@35190
    12
    hol_context -> term
blanchet@35190
    13
    -> ((term list * term list) * (bool * bool)) * term * bool
blanchet@35067
    14
end
blanchet@35067
    15
blanchet@35067
    16
structure Nitpick_Preproc : NITPICK_PREPROC =
blanchet@35067
    17
struct
blanchet@35067
    18
blanchet@35067
    19
open Nitpick_Util
blanchet@35067
    20
open Nitpick_HOL
blanchet@35067
    21
blanchet@35067
    22
(* polarity -> string -> bool *)
blanchet@35067
    23
fun is_positive_existential polar quant_s =
blanchet@35067
    24
  (polar = Pos andalso quant_s = @{const_name Ex}) orelse
blanchet@35067
    25
  (polar = Neg andalso quant_s <> @{const_name Ex})
blanchet@35067
    26
blanchet@35067
    27
(** Binary coding of integers **)
blanchet@35067
    28
blanchet@35067
    29
(* If a formula contains a numeral whose absolute value is more than this
blanchet@35067
    30
   threshold, the unary coding is likely not to work well and we prefer the
blanchet@35067
    31
   binary coding. *)
blanchet@35067
    32
val binary_int_threshold = 3
blanchet@35067
    33
blanchet@35067
    34
(* term -> bool *)
blanchet@35067
    35
fun may_use_binary_ints (t1 $ t2) =
blanchet@35067
    36
    may_use_binary_ints t1 andalso may_use_binary_ints t2
blanchet@35067
    37
  | may_use_binary_ints (t as Const (s, _)) =
blanchet@35067
    38
    t <> @{const Suc} andalso
blanchet@35067
    39
    not (member (op =) [@{const_name Abs_Frac}, @{const_name Rep_Frac},
blanchet@35067
    40
                        @{const_name nat_gcd}, @{const_name nat_lcm},
blanchet@35067
    41
                        @{const_name Frac}, @{const_name norm_frac}] s)
blanchet@35067
    42
  | may_use_binary_ints (Abs (_, _, t')) = may_use_binary_ints t'
blanchet@35067
    43
  | may_use_binary_ints _ = true
blanchet@35067
    44
fun should_use_binary_ints (t1 $ t2) =
blanchet@35067
    45
    should_use_binary_ints t1 orelse should_use_binary_ints t2
blanchet@35220
    46
  | should_use_binary_ints (Const (s, T)) =
blanchet@35220
    47
    ((s = @{const_name times} orelse s = @{const_name div}) andalso
blanchet@35220
    48
     is_integer_type (body_type T)) orelse
blanchet@35067
    49
    (String.isPrefix numeral_prefix s andalso
blanchet@35067
    50
     let val n = the (Int.fromString (unprefix numeral_prefix s)) in
blanchet@35067
    51
       n < ~ binary_int_threshold orelse n > binary_int_threshold
blanchet@35067
    52
     end)
blanchet@35067
    53
  | should_use_binary_ints (Abs (_, _, t')) = should_use_binary_ints t'
blanchet@35067
    54
  | should_use_binary_ints _ = false
blanchet@35067
    55
blanchet@35067
    56
(** Uncurrying **)
blanchet@35067
    57
blanchet@35067
    58
(* theory -> term -> int Termtab.tab -> int Termtab.tab *)
blanchet@35067
    59
fun add_to_uncurry_table thy t =
blanchet@35067
    60
  let
blanchet@35067
    61
    (* term -> term list -> int Termtab.tab -> int Termtab.tab *)
blanchet@35067
    62
    fun aux (t1 $ t2) args table =
blanchet@35067
    63
        let val table = aux t2 [] table in aux t1 (t2 :: args) table end
blanchet@35067
    64
      | aux (Abs (_, _, t')) _ table = aux t' [] table
blanchet@35067
    65
      | aux (t as Const (x as (s, _))) args table =
blanchet@35220
    66
        if is_built_in_const thy [(NONE, true)] true x orelse
blanchet@35220
    67
           is_constr_like thy x orelse
blanchet@35067
    68
           is_sel s orelse s = @{const_name Sigma} then
blanchet@35067
    69
          table
blanchet@35067
    70
        else
blanchet@35067
    71
          Termtab.map_default (t, 65536) (curry Int.min (length args)) table
blanchet@35067
    72
      | aux _ _ table = table
blanchet@35067
    73
  in aux t [] end
blanchet@35067
    74
blanchet@35067
    75
(* int -> int -> string *)
blanchet@35067
    76
fun uncurry_prefix_for k j =
blanchet@35067
    77
  uncurry_prefix ^ string_of_int k ^ "@" ^ string_of_int j ^ name_sep
blanchet@35067
    78
blanchet@35067
    79
(* int Termtab.tab term -> term *)
blanchet@35067
    80
fun uncurry_term table t =
blanchet@35067
    81
  let
blanchet@35067
    82
    (* term -> term list -> term *)
blanchet@35067
    83
    fun aux (t1 $ t2) args = aux t1 (aux t2 [] :: args)
blanchet@35067
    84
      | aux (Abs (s, T, t')) args = betapplys (Abs (s, T, aux t' []), args)
blanchet@35067
    85
      | aux (t as Const (s, T)) args =
blanchet@35067
    86
        (case Termtab.lookup table t of
blanchet@35067
    87
           SOME n =>
blanchet@35067
    88
           if n >= 2 then
blanchet@35067
    89
             let
blanchet@35280
    90
               val arg_Ts = strip_n_binders n T |> fst
blanchet@35067
    91
               val j =
blanchet@35280
    92
                 if is_iterator_type (hd arg_Ts) then
blanchet@35067
    93
                   1
blanchet@35067
    94
                 else case find_index (not_equal bool_T) arg_Ts of
blanchet@35067
    95
                   ~1 => n
blanchet@35067
    96
                 | j => j
blanchet@35067
    97
               val ((before_args, tuple_args), after_args) =
blanchet@35067
    98
                 args |> chop n |>> chop j
blanchet@35067
    99
               val ((before_arg_Ts, tuple_arg_Ts), rest_T) =
blanchet@35067
   100
                 T |> strip_n_binders n |>> chop j
blanchet@35067
   101
               val tuple_T = HOLogic.mk_tupleT tuple_arg_Ts
blanchet@35067
   102
             in
blanchet@35067
   103
               if n - j < 2 then
blanchet@35067
   104
                 betapplys (t, args)
blanchet@35067
   105
               else
blanchet@35067
   106
                 betapplys (Const (uncurry_prefix_for (n - j) j ^ s,
blanchet@35067
   107
                                   before_arg_Ts ---> tuple_T --> rest_T),
blanchet@35067
   108
                            before_args @ [mk_flat_tuple tuple_T tuple_args] @
blanchet@35067
   109
                            after_args)
blanchet@35067
   110
             end
blanchet@35067
   111
           else
blanchet@35067
   112
             betapplys (t, args)
blanchet@35067
   113
         | NONE => betapplys (t, args))
blanchet@35067
   114
      | aux t args = betapplys (t, args)
blanchet@35067
   115
  in aux t [] end
blanchet@35067
   116
blanchet@35067
   117
(** Boxing **)
blanchet@35067
   118
blanchet@35067
   119
(* hol_context -> typ -> term -> term *)
blanchet@35220
   120
fun constr_expand (hol_ctxt as {thy, stds, ...}) T t =
blanchet@35067
   121
  (case head_of t of
blanchet@35067
   122
     Const x => if is_constr_like thy x then t else raise SAME ()
blanchet@35067
   123
   | _ => raise SAME ())
blanchet@35067
   124
  handle SAME () =>
blanchet@35067
   125
         let
blanchet@35067
   126
           val x' as (_, T') =
blanchet@35067
   127
             if is_pair_type T then
blanchet@35067
   128
               let val (T1, T2) = HOLogic.dest_prodT T in
blanchet@35067
   129
                 (@{const_name Pair}, T1 --> T2 --> T)
blanchet@35067
   130
               end
blanchet@35067
   131
             else
blanchet@35067
   132
               datatype_constrs hol_ctxt T |> hd
blanchet@35067
   133
           val arg_Ts = binder_types T'
blanchet@35067
   134
         in
blanchet@35220
   135
           list_comb (Const x', map2 (select_nth_constr_arg thy stds x' t)
blanchet@35067
   136
                                     (index_seq 0 (length arg_Ts)) arg_Ts)
blanchet@35067
   137
         end
blanchet@35067
   138
blanchet@35384
   139
(* (term -> term) -> int -> term -> term *)
blanchet@35384
   140
fun coerce_bound_no f j t =
blanchet@35384
   141
  case t of
blanchet@35384
   142
    t1 $ t2 => coerce_bound_no f j t1 $ coerce_bound_no f j t2
blanchet@35384
   143
  | Abs (s, T, t') => Abs (s, T, coerce_bound_no f (j + 1) t')
blanchet@35384
   144
  | Bound j' => if j' = j then f t else t
blanchet@35384
   145
  | _ => t
blanchet@35384
   146
(* hol_context -> typ -> typ -> term -> term *)
blanchet@35384
   147
fun coerce_bound_0_in_term hol_ctxt new_T old_T =
blanchet@35384
   148
  old_T <> new_T ? coerce_bound_no (coerce_term hol_ctxt [new_T] old_T new_T) 0
blanchet@35384
   149
(* hol_context -> typ list -> typ -> typ -> term -> term *)
blanchet@35384
   150
and coerce_term (hol_ctxt as {thy, stds, fast_descrs, ...}) Ts new_T old_T t =
blanchet@35384
   151
  if old_T = new_T then
blanchet@35384
   152
    t
blanchet@35384
   153
  else
blanchet@35384
   154
    case (new_T, old_T) of
blanchet@35384
   155
      (Type (new_s, new_Ts as [new_T1, new_T2]),
blanchet@35384
   156
       Type ("fun", [old_T1, old_T2])) =>
blanchet@35384
   157
      (case eta_expand Ts t 1 of
blanchet@35384
   158
         Abs (s, _, t') =>
blanchet@35384
   159
         Abs (s, new_T1,
blanchet@35384
   160
              t' |> coerce_bound_0_in_term hol_ctxt new_T1 old_T1
blanchet@35384
   161
                 |> coerce_term hol_ctxt (new_T1 :: Ts) new_T2 old_T2)
blanchet@35384
   162
         |> Envir.eta_contract
blanchet@35384
   163
         |> new_s <> "fun"
blanchet@35384
   164
            ? construct_value thy stds
blanchet@35384
   165
                  (@{const_name FunBox}, Type ("fun", new_Ts) --> new_T)
blanchet@35384
   166
                  o single
blanchet@35384
   167
       | t' => raise TERM ("Nitpick_Preproc.coerce_term", [t']))
blanchet@35384
   168
    | (Type (new_s, new_Ts as [new_T1, new_T2]),
blanchet@35384
   169
       Type (old_s, old_Ts as [old_T1, old_T2])) =>
blanchet@35384
   170
      if old_s = @{type_name fun_box} orelse
blanchet@35384
   171
         old_s = @{type_name pair_box} orelse old_s = "*" then
blanchet@35384
   172
        case constr_expand hol_ctxt old_T t of
blanchet@35384
   173
          Const (old_s, _) $ t1 =>
blanchet@35384
   174
          if new_s = "fun" then
blanchet@35384
   175
            coerce_term hol_ctxt Ts new_T (Type ("fun", old_Ts)) t1
blanchet@35384
   176
          else
blanchet@35384
   177
            construct_value thy stds
blanchet@35384
   178
                (old_s, Type ("fun", new_Ts) --> new_T)
blanchet@35384
   179
                [coerce_term hol_ctxt Ts (Type ("fun", new_Ts))
blanchet@35384
   180
                             (Type ("fun", old_Ts)) t1]
blanchet@35384
   181
        | Const _ $ t1 $ t2 =>
blanchet@35384
   182
          construct_value thy stds
blanchet@35384
   183
              (if new_s = "*" then @{const_name Pair}
blanchet@35384
   184
               else @{const_name PairBox}, new_Ts ---> new_T)
blanchet@35384
   185
              [coerce_term hol_ctxt Ts new_T1 old_T1 t1,
blanchet@35384
   186
               coerce_term hol_ctxt Ts new_T2 old_T2 t2]
blanchet@35384
   187
        | t' => raise TERM ("Nitpick_Preproc.coerce_term", [t'])
blanchet@35384
   188
      else
blanchet@35384
   189
        raise TYPE ("Nitpick_Preproc.coerce_term", [new_T, old_T], [t])
blanchet@35384
   190
    | _ => raise TYPE ("Nitpick_Preproc.coerce_term", [new_T, old_T], [t])
blanchet@35384
   191
blanchet@35067
   192
(* hol_context -> bool -> term -> term *)
blanchet@35220
   193
fun box_fun_and_pair_in_term (hol_ctxt as {thy, stds, fast_descrs, ...}) def
blanchet@35220
   194
                             orig_t =
blanchet@35067
   195
  let
blanchet@35067
   196
    (* typ -> typ *)
blanchet@35067
   197
    fun box_relational_operator_type (Type ("fun", Ts)) =
blanchet@35067
   198
        Type ("fun", map box_relational_operator_type Ts)
blanchet@35067
   199
      | box_relational_operator_type (Type ("*", Ts)) =
blanchet@35067
   200
        Type ("*", map (box_type hol_ctxt InPair) Ts)
blanchet@35067
   201
      | box_relational_operator_type T = T
blanchet@35067
   202
    (* indexname * typ -> typ * term -> typ option list -> typ option list *)
blanchet@35067
   203
    fun add_boxed_types_for_var (z as (_, T)) (T', t') =
blanchet@35067
   204
      case t' of
blanchet@35067
   205
        Var z' => z' = z ? insert (op =) T'
blanchet@35067
   206
      | Const (@{const_name Pair}, _) $ t1 $ t2 =>
blanchet@35067
   207
        (case T' of
blanchet@35067
   208
           Type (_, [T1, T2]) =>
blanchet@35067
   209
           fold (add_boxed_types_for_var z) [(T1, t1), (T2, t2)]
blanchet@35067
   210
         | _ => raise TYPE ("Nitpick_Preproc.box_fun_and_pair_in_term.\
blanchet@35067
   211
                            \add_boxed_types_for_var", [T'], []))
blanchet@35067
   212
      | _ => exists_subterm (curry (op =) (Var z)) t' ? insert (op =) T
blanchet@35067
   213
    (* typ list -> typ list -> term -> indexname * typ -> typ *)
blanchet@35067
   214
    fun box_var_in_def new_Ts old_Ts t (z as (_, T)) =
blanchet@35067
   215
      case t of
blanchet@35067
   216
        @{const Trueprop} $ t1 => box_var_in_def new_Ts old_Ts t1 z
blanchet@35067
   217
      | Const (s0, _) $ t1 $ _ =>
blanchet@35067
   218
        if s0 = @{const_name "=="} orelse s0 = @{const_name "op ="} then
blanchet@35067
   219
          let
blanchet@35067
   220
            val (t', args) = strip_comb t1
blanchet@35067
   221
            val T' = fastype_of1 (new_Ts, do_term new_Ts old_Ts Neut t')
blanchet@35067
   222
          in
blanchet@35067
   223
            case fold (add_boxed_types_for_var z)
blanchet@35067
   224
                      (fst (strip_n_binders (length args) T') ~~ args) [] of
blanchet@35067
   225
              [T''] => T''
blanchet@35067
   226
            | _ => T
blanchet@35067
   227
          end
blanchet@35067
   228
        else
blanchet@35067
   229
          T
blanchet@35067
   230
      | _ => T
blanchet@35067
   231
    (* typ list -> typ list -> polarity -> string -> typ -> string -> typ
blanchet@35067
   232
       -> term -> term *)
blanchet@35067
   233
    and do_quantifier new_Ts old_Ts polar quant_s quant_T abs_s abs_T t =
blanchet@35067
   234
      let
blanchet@35067
   235
        val abs_T' =
blanchet@35067
   236
          if polar = Neut orelse is_positive_existential polar quant_s then
blanchet@35067
   237
            box_type hol_ctxt InFunLHS abs_T
blanchet@35067
   238
          else
blanchet@35067
   239
            abs_T
blanchet@35067
   240
        val body_T = body_type quant_T
blanchet@35067
   241
      in
blanchet@35067
   242
        Const (quant_s, (abs_T' --> body_T) --> body_T)
blanchet@35067
   243
        $ Abs (abs_s, abs_T',
blanchet@35067
   244
               t |> do_term (abs_T' :: new_Ts) (abs_T :: old_Ts) polar)
blanchet@35067
   245
      end
blanchet@35067
   246
    (* typ list -> typ list -> string -> typ -> term -> term -> term *)
blanchet@35067
   247
    and do_equals new_Ts old_Ts s0 T0 t1 t2 =
blanchet@35067
   248
      let
blanchet@35067
   249
        val (t1, t2) = pairself (do_term new_Ts old_Ts Neut) (t1, t2)
blanchet@35067
   250
        val (T1, T2) = pairself (curry fastype_of1 new_Ts) (t1, t2)
blanchet@35067
   251
        val T = [T1, T2] |> sort TermOrd.typ_ord |> List.last
blanchet@35067
   252
      in
blanchet@35067
   253
        list_comb (Const (s0, T --> T --> body_type T0),
blanchet@35384
   254
                   map2 (coerce_term hol_ctxt new_Ts T) [T1, T2] [t1, t2])
blanchet@35067
   255
      end
blanchet@35067
   256
    (* string -> typ -> term *)
blanchet@35067
   257
    and do_description_operator s T =
blanchet@35067
   258
      let val T1 = box_type hol_ctxt InFunLHS (range_type T) in
blanchet@35067
   259
        Const (s, (T1 --> bool_T) --> T1)
blanchet@35067
   260
      end
blanchet@35067
   261
    (* typ list -> typ list -> polarity -> term -> term *)
blanchet@35067
   262
    and do_term new_Ts old_Ts polar t =
blanchet@35067
   263
      case t of
blanchet@35067
   264
        Const (s0 as @{const_name all}, T0) $ Abs (s1, T1, t1) =>
blanchet@35067
   265
        do_quantifier new_Ts old_Ts polar s0 T0 s1 T1 t1
blanchet@35067
   266
      | Const (s0 as @{const_name "=="}, T0) $ t1 $ t2 =>
blanchet@35067
   267
        do_equals new_Ts old_Ts s0 T0 t1 t2
blanchet@35067
   268
      | @{const "==>"} $ t1 $ t2 =>
blanchet@35067
   269
        @{const "==>"} $ do_term new_Ts old_Ts (flip_polarity polar) t1
blanchet@35067
   270
        $ do_term new_Ts old_Ts polar t2
blanchet@35067
   271
      | @{const Pure.conjunction} $ t1 $ t2 =>
blanchet@35067
   272
        @{const Pure.conjunction} $ do_term new_Ts old_Ts polar t1
blanchet@35067
   273
        $ do_term new_Ts old_Ts polar t2
blanchet@35067
   274
      | @{const Trueprop} $ t1 =>
blanchet@35067
   275
        @{const Trueprop} $ do_term new_Ts old_Ts polar t1
blanchet@35067
   276
      | @{const Not} $ t1 =>
blanchet@35067
   277
        @{const Not} $ do_term new_Ts old_Ts (flip_polarity polar) t1
blanchet@35067
   278
      | Const (s0 as @{const_name All}, T0) $ Abs (s1, T1, t1) =>
blanchet@35067
   279
        do_quantifier new_Ts old_Ts polar s0 T0 s1 T1 t1
blanchet@35067
   280
      | Const (s0 as @{const_name Ex}, T0) $ Abs (s1, T1, t1) =>
blanchet@35067
   281
        do_quantifier new_Ts old_Ts polar s0 T0 s1 T1 t1
blanchet@35067
   282
      | Const (s0 as @{const_name "op ="}, T0) $ t1 $ t2 =>
blanchet@35067
   283
        do_equals new_Ts old_Ts s0 T0 t1 t2
blanchet@35067
   284
      | @{const "op &"} $ t1 $ t2 =>
blanchet@35067
   285
        @{const "op &"} $ do_term new_Ts old_Ts polar t1
blanchet@35067
   286
        $ do_term new_Ts old_Ts polar t2
blanchet@35067
   287
      | @{const "op |"} $ t1 $ t2 =>
blanchet@35067
   288
        @{const "op |"} $ do_term new_Ts old_Ts polar t1
blanchet@35067
   289
        $ do_term new_Ts old_Ts polar t2
blanchet@35067
   290
      | @{const "op -->"} $ t1 $ t2 =>
blanchet@35067
   291
        @{const "op -->"} $ do_term new_Ts old_Ts (flip_polarity polar) t1
blanchet@35067
   292
        $ do_term new_Ts old_Ts polar t2
blanchet@35067
   293
      | Const (s as @{const_name The}, T) => do_description_operator s T
blanchet@35067
   294
      | Const (s as @{const_name Eps}, T) => do_description_operator s T
blanchet@35067
   295
      | Const (s as @{const_name Tha}, T) => do_description_operator s T
blanchet@35067
   296
      | Const (x as (s, T)) =>
blanchet@35067
   297
        Const (s, if s = @{const_name converse} orelse
blanchet@35067
   298
                     s = @{const_name trancl} then
blanchet@35067
   299
                    box_relational_operator_type T
blanchet@35311
   300
                  else if String.isPrefix quot_normal_prefix s then
blanchet@35311
   301
                    let val T' = box_type hol_ctxt InFunLHS (domain_type T) in
blanchet@35311
   302
                      T' --> T'
blanchet@35311
   303
                    end
blanchet@35220
   304
                  else if is_built_in_const thy stds fast_descrs x orelse
blanchet@35067
   305
                          s = @{const_name Sigma} then
blanchet@35067
   306
                    T
blanchet@35067
   307
                  else if is_constr_like thy x then
blanchet@35067
   308
                    box_type hol_ctxt InConstr T
blanchet@35067
   309
                  else if is_sel s
blanchet@35067
   310
                       orelse is_rep_fun thy x then
blanchet@35067
   311
                    box_type hol_ctxt InSel T
blanchet@35067
   312
                  else
blanchet@35067
   313
                    box_type hol_ctxt InExpr T)
blanchet@35067
   314
      | t1 $ Abs (s, T, t2') =>
blanchet@35067
   315
        let
blanchet@35067
   316
          val t1 = do_term new_Ts old_Ts Neut t1
blanchet@35067
   317
          val T1 = fastype_of1 (new_Ts, t1)
blanchet@35067
   318
          val (s1, Ts1) = dest_Type T1
blanchet@35067
   319
          val T' = hd (snd (dest_Type (hd Ts1)))
blanchet@35067
   320
          val t2 = Abs (s, T', do_term (T' :: new_Ts) (T :: old_Ts) Neut t2')
blanchet@35067
   321
          val T2 = fastype_of1 (new_Ts, t2)
blanchet@35384
   322
          val t2 = coerce_term hol_ctxt new_Ts (hd Ts1) T2 t2
blanchet@35067
   323
        in
blanchet@35067
   324
          betapply (if s1 = "fun" then
blanchet@35067
   325
                      t1
blanchet@35067
   326
                    else
blanchet@35220
   327
                      select_nth_constr_arg thy stds
blanchet@35067
   328
                          (@{const_name FunBox}, Type ("fun", Ts1) --> T1) t1 0
blanchet@35067
   329
                          (Type ("fun", Ts1)), t2)
blanchet@35067
   330
        end
blanchet@35067
   331
      | t1 $ t2 =>
blanchet@35067
   332
        let
blanchet@35067
   333
          val t1 = do_term new_Ts old_Ts Neut t1
blanchet@35067
   334
          val T1 = fastype_of1 (new_Ts, t1)
blanchet@35067
   335
          val (s1, Ts1) = dest_Type T1
blanchet@35067
   336
          val t2 = do_term new_Ts old_Ts Neut t2
blanchet@35067
   337
          val T2 = fastype_of1 (new_Ts, t2)
blanchet@35384
   338
          val t2 = coerce_term hol_ctxt new_Ts (hd Ts1) T2 t2
blanchet@35067
   339
        in
blanchet@35067
   340
          betapply (if s1 = "fun" then
blanchet@35067
   341
                      t1
blanchet@35067
   342
                    else
blanchet@35220
   343
                      select_nth_constr_arg thy stds
blanchet@35067
   344
                          (@{const_name FunBox}, Type ("fun", Ts1) --> T1) t1 0
blanchet@35067
   345
                          (Type ("fun", Ts1)), t2)
blanchet@35067
   346
        end
blanchet@35067
   347
      | Free (s, T) => Free (s, box_type hol_ctxt InExpr T)
blanchet@35067
   348
      | Var (z as (x, T)) =>
blanchet@35067
   349
        Var (x, if def then box_var_in_def new_Ts old_Ts orig_t z
blanchet@35067
   350
                else box_type hol_ctxt InExpr T)
blanchet@35067
   351
      | Bound _ => t
blanchet@35067
   352
      | Abs (s, T, t') =>
blanchet@35067
   353
        Abs (s, T, do_term (T :: new_Ts) (T :: old_Ts) Neut t')
blanchet@35067
   354
  in do_term [] [] Pos orig_t end
blanchet@35067
   355
blanchet@35067
   356
(** Destruction of constructors **)
blanchet@35067
   357
blanchet@35067
   358
val val_var_prefix = nitpick_prefix ^ "v"
blanchet@35067
   359
blanchet@35067
   360
(* typ list -> int -> int -> int -> term -> term *)
blanchet@35067
   361
fun fresh_value_var Ts k n j t =
blanchet@35067
   362
  Var ((val_var_prefix ^ nat_subscript (n - j), k), fastype_of1 (Ts, t))
blanchet@35067
   363
blanchet@35280
   364
(* typ list -> term -> bool *)
blanchet@35280
   365
fun has_heavy_bounds_or_vars Ts t =
blanchet@35067
   366
  let
blanchet@35067
   367
    (* typ list -> bool *)
blanchet@35067
   368
    fun aux [] = false
blanchet@35067
   369
      | aux [T] = is_fun_type T orelse is_pair_type T
blanchet@35067
   370
      | aux _ = true
blanchet@35067
   371
  in aux (map snd (Term.add_vars t []) @ map (nth Ts) (loose_bnos t)) end
blanchet@35067
   372
blanchet@35220
   373
(* hol_context -> typ list -> bool -> int -> int -> term -> term list
blanchet@35220
   374
   -> term list -> term * term list *)
blanchet@35220
   375
fun pull_out_constr_comb ({thy, stds, ...} : hol_context) Ts relax k level t
blanchet@35220
   376
                         args seen =
blanchet@35067
   377
  let val t_comb = list_comb (t, args) in
blanchet@35067
   378
    case t of
blanchet@35067
   379
      Const x =>
blanchet@35220
   380
      if not relax andalso is_constr thy stds x andalso
blanchet@35067
   381
         not (is_fun_type (fastype_of1 (Ts, t_comb))) andalso
blanchet@35280
   382
         has_heavy_bounds_or_vars Ts t_comb andalso
blanchet@35067
   383
         not (loose_bvar (t_comb, level)) then
blanchet@35067
   384
        let
blanchet@35067
   385
          val (j, seen) = case find_index (curry (op =) t_comb) seen of
blanchet@35067
   386
                            ~1 => (0, t_comb :: seen)
blanchet@35067
   387
                          | j => (j, seen)
blanchet@35067
   388
        in (fresh_value_var Ts k (length seen) j t_comb, seen) end
blanchet@35067
   389
      else
blanchet@35067
   390
        (t_comb, seen)
blanchet@35067
   391
    | _ => (t_comb, seen)
blanchet@35067
   392
  end
blanchet@35067
   393
blanchet@35067
   394
(* (term -> term) -> typ list -> int -> term list -> term list *)
blanchet@35067
   395
fun equations_for_pulled_out_constrs mk_eq Ts k seen =
blanchet@35067
   396
  let val n = length seen in
blanchet@35067
   397
    map2 (fn j => fn t => mk_eq (fresh_value_var Ts k n j t, t))
blanchet@35067
   398
         (index_seq 0 n) seen
blanchet@35067
   399
  end
blanchet@35067
   400
blanchet@35220
   401
(* hol_context -> bool -> term -> term *)
blanchet@35220
   402
fun pull_out_universal_constrs hol_ctxt def t =
blanchet@35067
   403
  let
blanchet@35067
   404
    val k = maxidx_of_term t + 1
blanchet@35067
   405
    (* typ list -> bool -> term -> term list -> term list -> term * term list *)
blanchet@35067
   406
    fun do_term Ts def t args seen =
blanchet@35067
   407
      case t of
blanchet@35067
   408
        (t0 as Const (@{const_name "=="}, _)) $ t1 $ t2 =>
blanchet@35067
   409
        do_eq_or_imp Ts true def t0 t1 t2 seen
blanchet@35067
   410
      | (t0 as @{const "==>"}) $ t1 $ t2 =>
blanchet@35067
   411
        if def then (t, []) else do_eq_or_imp Ts false def t0 t1 t2 seen
blanchet@35067
   412
      | (t0 as Const (@{const_name "op ="}, _)) $ t1 $ t2 =>
blanchet@35067
   413
        do_eq_or_imp Ts true def t0 t1 t2 seen
blanchet@35067
   414
      | (t0 as @{const "op -->"}) $ t1 $ t2 =>
blanchet@35067
   415
        do_eq_or_imp Ts false def t0 t1 t2 seen
blanchet@35067
   416
      | Abs (s, T, t') =>
blanchet@35067
   417
        let val (t', seen) = do_term (T :: Ts) def t' [] seen in
blanchet@35067
   418
          (list_comb (Abs (s, T, t'), args), seen)
blanchet@35067
   419
        end
blanchet@35067
   420
      | t1 $ t2 =>
blanchet@35067
   421
        let val (t2, seen) = do_term Ts def t2 [] seen in
blanchet@35067
   422
          do_term Ts def t1 (t2 :: args) seen
blanchet@35067
   423
        end
blanchet@35220
   424
      | _ => pull_out_constr_comb hol_ctxt Ts def k 0 t args seen
blanchet@35067
   425
    (* typ list -> bool -> bool -> term -> term -> term -> term list
blanchet@35067
   426
       -> term * term list *)
blanchet@35067
   427
    and do_eq_or_imp Ts eq def t0 t1 t2 seen =
blanchet@35067
   428
      let
blanchet@35067
   429
        val (t2, seen) = if eq andalso def then (t2, seen)
blanchet@35067
   430
                         else do_term Ts false t2 [] seen
blanchet@35067
   431
        val (t1, seen) = do_term Ts false t1 [] seen
blanchet@35067
   432
      in (t0 $ t1 $ t2, seen) end
blanchet@35067
   433
    val (concl, seen) = do_term [] def t [] []
blanchet@35067
   434
  in
blanchet@35067
   435
    Logic.list_implies (equations_for_pulled_out_constrs Logic.mk_equals [] k
blanchet@35067
   436
                                                         seen, concl)
blanchet@35067
   437
  end
blanchet@35067
   438
blanchet@35067
   439
(* term -> term -> term *)
blanchet@35067
   440
fun mk_exists v t =
blanchet@35067
   441
  HOLogic.exists_const (fastype_of v) $ lambda v (incr_boundvars 1 t)
blanchet@35067
   442
blanchet@35220
   443
(* hol_context -> term -> term *)
blanchet@35220
   444
fun pull_out_existential_constrs hol_ctxt t =
blanchet@35067
   445
  let
blanchet@35067
   446
    val k = maxidx_of_term t + 1
blanchet@35067
   447
    (* typ list -> int -> term -> term list -> term list -> term * term list *)
blanchet@35067
   448
    fun aux Ts num_exists t args seen =
blanchet@35067
   449
      case t of
blanchet@35067
   450
        (t0 as Const (@{const_name Ex}, _)) $ Abs (s1, T1, t1) =>
blanchet@35067
   451
        let
blanchet@35067
   452
          val (t1, seen') = aux (T1 :: Ts) (num_exists + 1) t1 [] []
blanchet@35067
   453
          val n = length seen'
blanchet@35067
   454
          (* unit -> term list *)
blanchet@35067
   455
          fun vars () = map2 (fresh_value_var Ts k n) (index_seq 0 n) seen'
blanchet@35067
   456
        in
blanchet@35067
   457
          (equations_for_pulled_out_constrs HOLogic.mk_eq Ts k seen'
blanchet@35067
   458
           |> List.foldl s_conj t1 |> fold mk_exists (vars ())
blanchet@35067
   459
           |> curry3 Abs s1 T1 |> curry (op $) t0, seen)
blanchet@35067
   460
        end
blanchet@35067
   461
      | t1 $ t2 =>
blanchet@35067
   462
        let val (t2, seen) = aux Ts num_exists t2 [] seen in
blanchet@35067
   463
          aux Ts num_exists t1 (t2 :: args) seen
blanchet@35067
   464
        end
blanchet@35067
   465
      | Abs (s, T, t') =>
blanchet@35067
   466
        let
blanchet@35067
   467
          val (t', seen) = aux (T :: Ts) 0 t' [] (map (incr_boundvars 1) seen)
blanchet@35067
   468
        in (list_comb (Abs (s, T, t'), args), map (incr_boundvars ~1) seen) end
blanchet@35067
   469
      | _ =>
blanchet@35067
   470
        if num_exists > 0 then
blanchet@35220
   471
          pull_out_constr_comb hol_ctxt Ts false k num_exists t args seen
blanchet@35067
   472
        else
blanchet@35067
   473
          (list_comb (t, args), seen)
blanchet@35067
   474
  in aux [] 0 t [] [] |> fst end
blanchet@35067
   475
blanchet@35067
   476
(* hol_context -> bool -> term -> term *)
blanchet@35220
   477
fun destroy_pulled_out_constrs (hol_ctxt as {thy, stds, ...}) axiom t =
blanchet@35067
   478
  let
blanchet@35067
   479
    (* styp -> int *)
blanchet@35067
   480
    val num_occs_of_var =
blanchet@35067
   481
      fold_aterms (fn Var z => (fn f => fn z' => f z' |> z = z' ? Integer.add 1)
blanchet@35067
   482
                    | _ => I) t (K 0)
blanchet@35067
   483
    (* bool -> term -> term *)
blanchet@35067
   484
    fun aux careful ((t0 as Const (@{const_name "=="}, _)) $ t1 $ t2) =
blanchet@35067
   485
        aux_eq careful true t0 t1 t2
blanchet@35067
   486
      | aux careful ((t0 as @{const "==>"}) $ t1 $ t2) =
blanchet@35067
   487
        t0 $ aux false t1 $ aux careful t2
blanchet@35067
   488
      | aux careful ((t0 as Const (@{const_name "op ="}, _)) $ t1 $ t2) =
blanchet@35067
   489
        aux_eq careful true t0 t1 t2
blanchet@35067
   490
      | aux careful ((t0 as @{const "op -->"}) $ t1 $ t2) =
blanchet@35067
   491
        t0 $ aux false t1 $ aux careful t2
blanchet@35067
   492
      | aux careful (Abs (s, T, t')) = Abs (s, T, aux careful t')
blanchet@35067
   493
      | aux careful (t1 $ t2) = aux careful t1 $ aux careful t2
blanchet@35067
   494
      | aux _ t = t
blanchet@35067
   495
    (* bool -> bool -> term -> term -> term -> term *)
blanchet@35067
   496
    and aux_eq careful pass1 t0 t1 t2 =
blanchet@35067
   497
      ((if careful then
blanchet@35067
   498
          raise SAME ()
blanchet@35067
   499
        else if axiom andalso is_Var t2 andalso
blanchet@35067
   500
                num_occs_of_var (dest_Var t2) = 1 then
blanchet@35067
   501
          @{const True}
blanchet@35067
   502
        else case strip_comb t2 of
blanchet@35067
   503
          (* The first case is not as general as it could be. *)
blanchet@35067
   504
          (Const (@{const_name PairBox}, _),
blanchet@35067
   505
                  [Const (@{const_name fst}, _) $ Var z1,
blanchet@35067
   506
                   Const (@{const_name snd}, _) $ Var z2]) =>
blanchet@35067
   507
          if z1 = z2 andalso num_occs_of_var z1 = 2 then @{const True}
blanchet@35067
   508
          else raise SAME ()
blanchet@35067
   509
        | (Const (x as (s, T)), args) =>
blanchet@35067
   510
          let val arg_Ts = binder_types T in
blanchet@35067
   511
            if length arg_Ts = length args andalso
blanchet@35220
   512
               (is_constr thy stds x orelse s = @{const_name Pair}) andalso
blanchet@35067
   513
               (not careful orelse not (is_Var t1) orelse
blanchet@35067
   514
                String.isPrefix val_var_prefix (fst (fst (dest_Var t1)))) then
blanchet@35067
   515
              discriminate_value hol_ctxt x t1 ::
blanchet@35067
   516
              map3 (sel_eq x t1) (index_seq 0 (length args)) arg_Ts args
blanchet@35067
   517
              |> foldr1 s_conj
blanchet@35067
   518
            else
blanchet@35067
   519
              raise SAME ()
blanchet@35067
   520
          end
blanchet@35067
   521
        | _ => raise SAME ())
blanchet@35067
   522
       |> body_type (type_of t0) = prop_T ? HOLogic.mk_Trueprop)
blanchet@35067
   523
      handle SAME () => if pass1 then aux_eq careful false t0 t2 t1
blanchet@35067
   524
                        else t0 $ aux false t2 $ aux false t1
blanchet@35067
   525
    (* styp -> term -> int -> typ -> term -> term *)
blanchet@35067
   526
    and sel_eq x t n nth_T nth_t =
blanchet@35220
   527
      HOLogic.eq_const nth_T $ nth_t
blanchet@35220
   528
                             $ select_nth_constr_arg thy stds x t n nth_T
blanchet@35067
   529
      |> aux false
blanchet@35067
   530
  in aux axiom t end
blanchet@35067
   531
blanchet@35067
   532
(** Destruction of universal and existential equalities **)
blanchet@35067
   533
blanchet@35067
   534
(* term -> term *)
blanchet@35067
   535
fun curry_assms (@{const "==>"} $ (@{const Trueprop}
blanchet@35067
   536
                                   $ (@{const "op &"} $ t1 $ t2)) $ t3) =
blanchet@35067
   537
    curry_assms (Logic.list_implies ([t1, t2] |> map HOLogic.mk_Trueprop, t3))
blanchet@35067
   538
  | curry_assms (@{const "==>"} $ t1 $ t2) =
blanchet@35067
   539
    @{const "==>"} $ curry_assms t1 $ curry_assms t2
blanchet@35067
   540
  | curry_assms t = t
blanchet@35067
   541
blanchet@35067
   542
(* term -> term *)
blanchet@35067
   543
val destroy_universal_equalities =
blanchet@35067
   544
  let
blanchet@35067
   545
    (* term list -> (indexname * typ) list -> term -> term *)
blanchet@35067
   546
    fun aux prems zs t =
blanchet@35067
   547
      case t of
blanchet@35067
   548
        @{const "==>"} $ t1 $ t2 => aux_implies prems zs t1 t2
blanchet@35067
   549
      | _ => Logic.list_implies (rev prems, t)
blanchet@35067
   550
    (* term list -> (indexname * typ) list -> term -> term -> term *)
blanchet@35067
   551
    and aux_implies prems zs t1 t2 =
blanchet@35067
   552
      case t1 of
blanchet@35067
   553
        Const (@{const_name "=="}, _) $ Var z $ t' => aux_eq prems zs z t' t1 t2
blanchet@35067
   554
      | @{const Trueprop} $ (Const (@{const_name "op ="}, _) $ Var z $ t') =>
blanchet@35067
   555
        aux_eq prems zs z t' t1 t2
blanchet@35067
   556
      | @{const Trueprop} $ (Const (@{const_name "op ="}, _) $ t' $ Var z) =>
blanchet@35067
   557
        aux_eq prems zs z t' t1 t2
blanchet@35067
   558
      | _ => aux (t1 :: prems) (Term.add_vars t1 zs) t2
blanchet@35067
   559
    (* term list -> (indexname * typ) list -> indexname * typ -> term -> term
blanchet@35067
   560
       -> term -> term *)
blanchet@35067
   561
    and aux_eq prems zs z t' t1 t2 =
blanchet@35067
   562
      if not (member (op =) zs z) andalso
blanchet@35067
   563
         not (exists_subterm (curry (op =) (Var z)) t') then
blanchet@35067
   564
        aux prems zs (subst_free [(Var z, t')] t2)
blanchet@35067
   565
      else
blanchet@35067
   566
        aux (t1 :: prems) (Term.add_vars t1 zs) t2
blanchet@35067
   567
  in aux [] [] end
blanchet@35067
   568
blanchet@35220
   569
(* theory -> (typ option * bool) list -> int -> term list -> term list
blanchet@35220
   570
   -> (term * term list) option *)
blanchet@35220
   571
fun find_bound_assign thy stds j =
blanchet@35220
   572
  let
blanchet@35220
   573
    (* term list -> term list -> (term * term list) option *)
blanchet@35220
   574
    fun do_term _ [] = NONE
blanchet@35220
   575
      | do_term seen (t :: ts) =
blanchet@35220
   576
        let
blanchet@35220
   577
          (* bool -> term -> term -> (term * term list) option *)
blanchet@35220
   578
          fun do_eq pass1 t1 t2 =
blanchet@35220
   579
            (if loose_bvar1 (t2, j) then
blanchet@35220
   580
               if pass1 then do_eq false t2 t1 else raise SAME ()
blanchet@35220
   581
             else case t1 of
blanchet@35220
   582
               Bound j' => if j' = j then SOME (t2, ts @ seen) else raise SAME ()
blanchet@35220
   583
             | Const (s, Type ("fun", [T1, T2])) $ Bound j' =>
blanchet@35220
   584
               if j' = j andalso
blanchet@35220
   585
                  s = nth_sel_name_for_constr_name @{const_name FunBox} 0 then
blanchet@35220
   586
                 SOME (construct_value thy stds (@{const_name FunBox}, T2 --> T1)
blanchet@35220
   587
                                       [t2], ts @ seen)
blanchet@35220
   588
               else
blanchet@35220
   589
                 raise SAME ()
blanchet@35220
   590
             | _ => raise SAME ())
blanchet@35220
   591
            handle SAME () => do_term (t :: seen) ts
blanchet@35220
   592
        in
blanchet@35220
   593
          case t of
blanchet@35220
   594
            Const (@{const_name "op ="}, _) $ t1 $ t2 => do_eq true t1 t2
blanchet@35220
   595
          | _ => do_term (t :: seen) ts
blanchet@35220
   596
        end
blanchet@35220
   597
  in do_term end
blanchet@35067
   598
blanchet@35067
   599
(* int -> term -> term -> term *)
blanchet@35067
   600
fun subst_one_bound j arg t =
blanchet@35067
   601
  let
blanchet@35220
   602
    (* term * int -> term *)
blanchet@35067
   603
    fun aux (Bound i, lev) =
blanchet@35067
   604
        if i < lev then raise SAME ()
blanchet@35067
   605
        else if i = lev then incr_boundvars (lev - j) arg
blanchet@35067
   606
        else Bound (i - 1)
blanchet@35067
   607
      | aux (Abs (a, T, body), lev) = Abs (a, T, aux (body, lev + 1))
blanchet@35067
   608
      | aux (f $ t, lev) =
blanchet@35067
   609
        (aux (f, lev) $ (aux (t, lev) handle SAME () => t)
blanchet@35067
   610
         handle SAME () => f $ aux (t, lev))
blanchet@35067
   611
      | aux _ = raise SAME ()
blanchet@35067
   612
  in aux (t, j) handle SAME () => t end
blanchet@35067
   613
blanchet@35220
   614
(* hol_context -> term -> term *)
blanchet@35220
   615
fun destroy_existential_equalities ({thy, stds, ...} : hol_context) =
blanchet@35067
   616
  let
blanchet@35067
   617
    (* string list -> typ list -> term list -> term *)
blanchet@35067
   618
    fun kill [] [] ts = foldr1 s_conj ts
blanchet@35067
   619
      | kill (s :: ss) (T :: Ts) ts =
blanchet@35220
   620
        (case find_bound_assign thy stds (length ss) [] ts of
blanchet@35067
   621
           SOME (_, []) => @{const True}
blanchet@35067
   622
         | SOME (arg_t, ts) =>
blanchet@35067
   623
           kill ss Ts (map (subst_one_bound (length ss)
blanchet@35067
   624
                                (incr_bv (~1, length ss + 1, arg_t))) ts)
blanchet@35067
   625
         | NONE =>
blanchet@35067
   626
           Const (@{const_name Ex}, (T --> bool_T) --> bool_T)
blanchet@35067
   627
           $ Abs (s, T, kill ss Ts ts))
blanchet@35067
   628
      | kill _ _ _ = raise UnequalLengths
blanchet@35067
   629
    (* string list -> typ list -> term -> term *)
blanchet@35280
   630
    fun gather ss Ts (Const (@{const_name Ex}, _) $ Abs (s1, T1, t1)) =
blanchet@35067
   631
        gather (ss @ [s1]) (Ts @ [T1]) t1
blanchet@35067
   632
      | gather [] [] (Abs (s, T, t1)) = Abs (s, T, gather [] [] t1)
blanchet@35067
   633
      | gather [] [] (t1 $ t2) = gather [] [] t1 $ gather [] [] t2
blanchet@35067
   634
      | gather [] [] t = t
blanchet@35067
   635
      | gather ss Ts t = kill ss Ts (conjuncts_of (gather [] [] t))
blanchet@35067
   636
  in gather [] [] end
blanchet@35067
   637
blanchet@35067
   638
(** Skolemization **)
blanchet@35067
   639
blanchet@35067
   640
(* int -> int -> string *)
blanchet@35067
   641
fun skolem_prefix_for k j =
blanchet@35067
   642
  skolem_prefix ^ string_of_int k ^ "@" ^ string_of_int j ^ name_sep
blanchet@35067
   643
blanchet@35067
   644
(* hol_context -> int -> term -> term *)
blanchet@35067
   645
fun skolemize_term_and_more (hol_ctxt as {thy, def_table, skolems, ...})
blanchet@35067
   646
                            skolem_depth =
blanchet@35067
   647
  let
blanchet@35067
   648
    (* int list -> int list *)
blanchet@35067
   649
    val incrs = map (Integer.add 1)
blanchet@35067
   650
    (* string list -> typ list -> int list -> int -> polarity -> term -> term *)
blanchet@35067
   651
    fun aux ss Ts js depth polar t =
blanchet@35067
   652
      let
blanchet@35067
   653
        (* string -> typ -> string -> typ -> term -> term *)
blanchet@35067
   654
        fun do_quantifier quant_s quant_T abs_s abs_T t =
blanchet@35067
   655
          if not (loose_bvar1 (t, 0)) then
blanchet@35067
   656
            aux ss Ts js depth polar (incr_boundvars ~1 t)
blanchet@35067
   657
          else if depth <= skolem_depth andalso
blanchet@35067
   658
                  is_positive_existential polar quant_s then
blanchet@35067
   659
            let
blanchet@35067
   660
              val j = length (!skolems) + 1
blanchet@35067
   661
              val sko_s = skolem_prefix_for (length js) j ^ abs_s
blanchet@35067
   662
              val _ = Unsynchronized.change skolems (cons (sko_s, ss))
blanchet@35067
   663
              val sko_t = list_comb (Const (sko_s, rev Ts ---> abs_T),
blanchet@35067
   664
                                     map Bound (rev js))
blanchet@35067
   665
              val abs_t = Abs (abs_s, abs_T, aux ss Ts (incrs js) depth polar t)
blanchet@35067
   666
            in
blanchet@35067
   667
              if null js then betapply (abs_t, sko_t)
blanchet@35067
   668
              else Const (@{const_name Let}, abs_T --> quant_T) $ sko_t $ abs_t
blanchet@35067
   669
            end
blanchet@35067
   670
          else
blanchet@35067
   671
            Const (quant_s, quant_T)
blanchet@35067
   672
            $ Abs (abs_s, abs_T,
blanchet@35067
   673
                   if is_higher_order_type abs_T then
blanchet@35067
   674
                     t
blanchet@35067
   675
                   else
blanchet@35067
   676
                     aux (abs_s :: ss) (abs_T :: Ts) (0 :: incrs js)
blanchet@35067
   677
                         (depth + 1) polar t)
blanchet@35067
   678
      in
blanchet@35067
   679
        case t of
blanchet@35067
   680
          Const (s0 as @{const_name all}, T0) $ Abs (s1, T1, t1) =>
blanchet@35067
   681
          do_quantifier s0 T0 s1 T1 t1
blanchet@35067
   682
        | @{const "==>"} $ t1 $ t2 =>
blanchet@35067
   683
          @{const "==>"} $ aux ss Ts js depth (flip_polarity polar) t1
blanchet@35067
   684
          $ aux ss Ts js depth polar t2
blanchet@35067
   685
        | @{const Pure.conjunction} $ t1 $ t2 =>
blanchet@35067
   686
          @{const Pure.conjunction} $ aux ss Ts js depth polar t1
blanchet@35067
   687
          $ aux ss Ts js depth polar t2
blanchet@35067
   688
        | @{const Trueprop} $ t1 =>
blanchet@35067
   689
          @{const Trueprop} $ aux ss Ts js depth polar t1
blanchet@35067
   690
        | @{const Not} $ t1 =>
blanchet@35067
   691
          @{const Not} $ aux ss Ts js depth (flip_polarity polar) t1
blanchet@35067
   692
        | Const (s0 as @{const_name All}, T0) $ Abs (s1, T1, t1) =>
blanchet@35067
   693
          do_quantifier s0 T0 s1 T1 t1
blanchet@35067
   694
        | Const (s0 as @{const_name Ex}, T0) $ Abs (s1, T1, t1) =>
blanchet@35067
   695
          do_quantifier s0 T0 s1 T1 t1
blanchet@35067
   696
        | @{const "op &"} $ t1 $ t2 =>
blanchet@35067
   697
          @{const "op &"} $ aux ss Ts js depth polar t1
blanchet@35067
   698
          $ aux ss Ts js depth polar t2
blanchet@35067
   699
        | @{const "op |"} $ t1 $ t2 =>
blanchet@35067
   700
          @{const "op |"} $ aux ss Ts js depth polar t1
blanchet@35067
   701
          $ aux ss Ts js depth polar t2
blanchet@35067
   702
        | @{const "op -->"} $ t1 $ t2 =>
blanchet@35067
   703
          @{const "op -->"} $ aux ss Ts js depth (flip_polarity polar) t1
blanchet@35067
   704
          $ aux ss Ts js depth polar t2
blanchet@35280
   705
        | (t0 as Const (@{const_name Let}, _)) $ t1 $ t2 =>
blanchet@35067
   706
          t0 $ t1 $ aux ss Ts js depth polar t2
blanchet@35067
   707
        | Const (x as (s, T)) =>
blanchet@35067
   708
          if is_inductive_pred hol_ctxt x andalso
blanchet@35067
   709
             not (is_well_founded_inductive_pred hol_ctxt x) then
blanchet@35067
   710
            let
blanchet@35067
   711
              val gfp = (fixpoint_kind_of_const thy def_table x = Gfp)
blanchet@35067
   712
              val (pref, connective, set_oper) =
blanchet@35067
   713
                if gfp then
blanchet@35220
   714
                  (lbfp_prefix, @{const "op |"},
blanchet@35220
   715
                   @{const_name semilattice_sup_class.sup})
blanchet@35067
   716
                else
blanchet@35220
   717
                  (ubfp_prefix, @{const "op &"},
blanchet@35220
   718
                   @{const_name semilattice_inf_class.inf})
blanchet@35067
   719
              (* unit -> term *)
blanchet@35067
   720
              fun pos () = unrolled_inductive_pred_const hol_ctxt gfp x
blanchet@35067
   721
                           |> aux ss Ts js depth polar
blanchet@35067
   722
              fun neg () = Const (pref ^ s, T)
blanchet@35067
   723
            in
blanchet@35067
   724
              (case polar |> gfp ? flip_polarity of
blanchet@35067
   725
                 Pos => pos ()
blanchet@35067
   726
               | Neg => neg ()
blanchet@35067
   727
               | Neut =>
blanchet@35067
   728
                 if is_fun_type T then
blanchet@35067
   729
                   let
blanchet@35067
   730
                     val ((trunk_arg_Ts, rump_arg_T), body_T) =
blanchet@35067
   731
                       T |> strip_type |>> split_last
blanchet@35067
   732
                     val set_T = rump_arg_T --> body_T
blanchet@35067
   733
                     (* (unit -> term) -> term *)
blanchet@35067
   734
                     fun app f =
blanchet@35067
   735
                       list_comb (f (),
blanchet@35067
   736
                                  map Bound (length trunk_arg_Ts - 1 downto 0))
blanchet@35067
   737
                   in
blanchet@35067
   738
                     List.foldr absdummy
blanchet@35067
   739
                                (Const (set_oper, set_T --> set_T --> set_T)
blanchet@35067
   740
                                        $ app pos $ app neg) trunk_arg_Ts
blanchet@35067
   741
                   end
blanchet@35067
   742
                 else
blanchet@35067
   743
                   connective $ pos () $ neg ())
blanchet@35067
   744
            end
blanchet@35067
   745
          else
blanchet@35067
   746
            Const x
blanchet@35067
   747
        | t1 $ t2 =>
blanchet@35067
   748
          betapply (aux ss Ts [] (skolem_depth + 1) polar t1,
blanchet@35067
   749
                    aux ss Ts [] depth Neut t2)
blanchet@35067
   750
        | Abs (s, T, t1) => Abs (s, T, aux ss Ts (incrs js) depth polar t1)
blanchet@35067
   751
        | _ => t
blanchet@35067
   752
      end
blanchet@35067
   753
  in aux [] [] [] 0 Pos end
blanchet@35067
   754
blanchet@35067
   755
(** Function specialization **)
blanchet@35067
   756
blanchet@35067
   757
(* term -> term list *)
blanchet@35067
   758
fun params_in_equation (@{const "==>"} $ _ $ t2) = params_in_equation t2
blanchet@35067
   759
  | params_in_equation (@{const Trueprop} $ t1) = params_in_equation t1
blanchet@35067
   760
  | params_in_equation (Const (@{const_name "op ="}, _) $ t1 $ _) =
blanchet@35067
   761
    snd (strip_comb t1)
blanchet@35067
   762
  | params_in_equation _ = []
blanchet@35067
   763
blanchet@35067
   764
(* styp -> styp -> int list -> term list -> term list -> term -> term *)
blanchet@35067
   765
fun specialize_fun_axiom x x' fixed_js fixed_args extra_args t =
blanchet@35067
   766
  let
blanchet@35067
   767
    val k = fold Integer.max (map maxidx_of_term (fixed_args @ extra_args)) 0
blanchet@35067
   768
            + 1
blanchet@35067
   769
    val t = map_aterms (fn Var ((s, i), T) => Var ((s, k + i), T) | t' => t') t
blanchet@35067
   770
    val fixed_params = filter_indices fixed_js (params_in_equation t)
blanchet@35067
   771
    (* term list -> term -> term *)
blanchet@35067
   772
    fun aux args (Abs (s, T, t)) = list_comb (Abs (s, T, aux [] t), args)
blanchet@35067
   773
      | aux args (t1 $ t2) = aux (aux [] t2 :: args) t1
blanchet@35067
   774
      | aux args t =
blanchet@35067
   775
        if t = Const x then
blanchet@35067
   776
          list_comb (Const x', extra_args @ filter_out_indices fixed_js args)
blanchet@35067
   777
        else
blanchet@35067
   778
          let val j = find_index (curry (op =) t) fixed_params in
blanchet@35067
   779
            list_comb (if j >= 0 then nth fixed_args j else t, args)
blanchet@35067
   780
          end
blanchet@35067
   781
  in aux [] t end
blanchet@35067
   782
blanchet@35067
   783
(* hol_context -> styp -> (int * term option) list *)
blanchet@35067
   784
fun static_args_in_term ({ersatz_table, ...} : hol_context) x t =
blanchet@35067
   785
  let
blanchet@35067
   786
    (* term -> term list -> term list -> term list list *)
blanchet@35067
   787
    fun fun_calls (Abs (_, _, t)) _ = fun_calls t []
blanchet@35067
   788
      | fun_calls (t1 $ t2) args = fun_calls t2 [] #> fun_calls t1 (t2 :: args)
blanchet@35067
   789
      | fun_calls t args =
blanchet@35067
   790
        (case t of
blanchet@35067
   791
           Const (x' as (s', T')) =>
blanchet@35067
   792
           x = x' orelse (case AList.lookup (op =) ersatz_table s' of
blanchet@35067
   793
                            SOME s'' => x = (s'', T')
blanchet@35067
   794
                          | NONE => false)
blanchet@35067
   795
         | _ => false) ? cons args
blanchet@35067
   796
    (* term list list -> term list list -> term list -> term list list *)
blanchet@35067
   797
    fun call_sets [] [] vs = [vs]
blanchet@35067
   798
      | call_sets [] uss vs = vs :: call_sets uss [] []
blanchet@35067
   799
      | call_sets ([] :: _) _ _ = []
blanchet@35067
   800
      | call_sets ((t :: ts) :: tss) uss vs =
blanchet@35067
   801
        OrdList.insert TermOrd.term_ord t vs |> call_sets tss (ts :: uss)
blanchet@35067
   802
    val sets = call_sets (fun_calls t [] []) [] []
blanchet@35067
   803
    val indexed_sets = sets ~~ (index_seq 0 (length sets))
blanchet@35067
   804
  in
blanchet@35067
   805
    fold_rev (fn (set, j) =>
blanchet@35067
   806
                 case set of
blanchet@35067
   807
                   [Var _] => AList.lookup (op =) indexed_sets set = SOME j
blanchet@35067
   808
                              ? cons (j, NONE)
blanchet@35067
   809
                 | [t as Const _] => cons (j, SOME t)
blanchet@35067
   810
                 | [t as Free _] => cons (j, SOME t)
blanchet@35067
   811
                 | _ => I) indexed_sets []
blanchet@35067
   812
  end
blanchet@35067
   813
(* hol_context -> styp -> term list -> (int * term option) list *)
blanchet@35067
   814
fun static_args_in_terms hol_ctxt x =
blanchet@35067
   815
  map (static_args_in_term hol_ctxt x)
blanchet@35067
   816
  #> fold1 (OrdList.inter (prod_ord int_ord (option_ord TermOrd.term_ord)))
blanchet@35067
   817
blanchet@35067
   818
(* (int * term option) list -> (int * term) list -> int list *)
blanchet@35067
   819
fun overlapping_indices [] _ = []
blanchet@35067
   820
  | overlapping_indices _ [] = []
blanchet@35067
   821
  | overlapping_indices (ps1 as (j1, t1) :: ps1') (ps2 as (j2, t2) :: ps2') =
blanchet@35067
   822
    if j1 < j2 then overlapping_indices ps1' ps2
blanchet@35067
   823
    else if j1 > j2 then overlapping_indices ps1 ps2'
blanchet@35067
   824
    else overlapping_indices ps1' ps2' |> the_default t2 t1 = t2 ? cons j1
blanchet@35067
   825
blanchet@35067
   826
(* typ list -> term -> bool *)
blanchet@35067
   827
fun is_eligible_arg Ts t =
blanchet@35067
   828
  let val bad_Ts = map snd (Term.add_vars t []) @ map (nth Ts) (loose_bnos t) in
blanchet@35067
   829
    null bad_Ts orelse
blanchet@35067
   830
    (is_higher_order_type (fastype_of1 (Ts, t)) andalso
blanchet@35067
   831
     forall (not o is_higher_order_type) bad_Ts)
blanchet@35067
   832
  end
blanchet@35067
   833
blanchet@35067
   834
(* int -> string *)
blanchet@35067
   835
fun special_prefix_for j = special_prefix ^ string_of_int j ^ name_sep
blanchet@35067
   836
blanchet@35067
   837
(* If a constant's definition is picked up deeper than this threshold, we
blanchet@35067
   838
   prevent excessive specialization by not specializing it. *)
blanchet@35067
   839
val special_max_depth = 20
blanchet@35067
   840
blanchet@35067
   841
val bound_var_prefix = "b"
blanchet@35067
   842
blanchet@35067
   843
(* hol_context -> int -> term -> term *)
blanchet@35280
   844
fun specialize_consts_in_term (hol_ctxt as {specialize, simp_table,
blanchet@35067
   845
                                            special_funs, ...}) depth t =
blanchet@35067
   846
  if not specialize orelse depth > special_max_depth then
blanchet@35067
   847
    t
blanchet@35067
   848
  else
blanchet@35067
   849
    let
blanchet@35067
   850
      val blacklist = if depth = 0 then []
blanchet@35067
   851
                      else case term_under_def t of Const x => [x] | _ => []
blanchet@35067
   852
      (* term list -> typ list -> term -> term *)
blanchet@35067
   853
      fun aux args Ts (Const (x as (s, T))) =
blanchet@35067
   854
          ((if not (member (op =) blacklist x) andalso not (null args) andalso
blanchet@35067
   855
               not (String.isPrefix special_prefix s) andalso
blanchet@35067
   856
               is_equational_fun hol_ctxt x then
blanchet@35067
   857
              let
blanchet@35067
   858
                val eligible_args = filter (is_eligible_arg Ts o snd)
blanchet@35067
   859
                                           (index_seq 0 (length args) ~~ args)
blanchet@35067
   860
                val _ = not (null eligible_args) orelse raise SAME ()
blanchet@35067
   861
                val old_axs = equational_fun_axioms hol_ctxt x
blanchet@35220
   862
                              |> map (destroy_existential_equalities hol_ctxt)
blanchet@35067
   863
                val static_params = static_args_in_terms hol_ctxt x old_axs
blanchet@35067
   864
                val fixed_js = overlapping_indices static_params eligible_args
blanchet@35067
   865
                val _ = not (null fixed_js) orelse raise SAME ()
blanchet@35067
   866
                val fixed_args = filter_indices fixed_js args
blanchet@35067
   867
                val vars = fold Term.add_vars fixed_args []
blanchet@35067
   868
                           |> sort (TermOrd.fast_indexname_ord o pairself fst)
blanchet@35067
   869
                val bound_js = fold (fn t => fn js => add_loose_bnos (t, 0, js))
blanchet@35067
   870
                                    fixed_args []
blanchet@35067
   871
                               |> sort int_ord
blanchet@35067
   872
                val live_args = filter_out_indices fixed_js args
blanchet@35067
   873
                val extra_args = map Var vars @ map Bound bound_js @ live_args
blanchet@35067
   874
                val extra_Ts = map snd vars @ filter_indices bound_js Ts
blanchet@35067
   875
                val k = maxidx_of_term t + 1
blanchet@35067
   876
                (* int -> term *)
blanchet@35067
   877
                fun var_for_bound_no j =
blanchet@35067
   878
                  Var ((bound_var_prefix ^
blanchet@35067
   879
                        nat_subscript (find_index (curry (op =) j) bound_js
blanchet@35067
   880
                                       + 1), k),
blanchet@35067
   881
                       nth Ts j)
blanchet@35067
   882
                val fixed_args_in_axiom =
blanchet@35067
   883
                  map (curry subst_bounds
blanchet@35067
   884
                             (map var_for_bound_no (index_seq 0 (length Ts))))
blanchet@35067
   885
                      fixed_args
blanchet@35067
   886
              in
blanchet@35067
   887
                case AList.lookup (op =) (!special_funs)
blanchet@35067
   888
                                  (x, fixed_js, fixed_args_in_axiom) of
blanchet@35067
   889
                  SOME x' => list_comb (Const x', extra_args)
blanchet@35067
   890
                | NONE =>
blanchet@35067
   891
                  let
blanchet@35067
   892
                    val extra_args_in_axiom =
blanchet@35067
   893
                      map Var vars @ map var_for_bound_no bound_js
blanchet@35067
   894
                    val x' as (s', _) =
blanchet@35067
   895
                      (special_prefix_for (length (!special_funs) + 1) ^ s,
blanchet@35067
   896
                       extra_Ts @ filter_out_indices fixed_js (binder_types T)
blanchet@35067
   897
                       ---> body_type T)
blanchet@35067
   898
                    val new_axs =
blanchet@35067
   899
                      map (specialize_fun_axiom x x' fixed_js
blanchet@35067
   900
                               fixed_args_in_axiom extra_args_in_axiom) old_axs
blanchet@35067
   901
                    val _ =
blanchet@35067
   902
                      Unsynchronized.change special_funs
blanchet@35067
   903
                          (cons ((x, fixed_js, fixed_args_in_axiom), x'))
blanchet@35067
   904
                    val _ = add_simps simp_table s' new_axs
blanchet@35067
   905
                  in list_comb (Const x', extra_args) end
blanchet@35067
   906
              end
blanchet@35067
   907
            else
blanchet@35067
   908
              raise SAME ())
blanchet@35067
   909
           handle SAME () => list_comb (Const x, args))
blanchet@35067
   910
        | aux args Ts (Abs (s, T, t)) =
blanchet@35067
   911
          list_comb (Abs (s, T, aux [] (T :: Ts) t), args)
blanchet@35067
   912
        | aux args Ts (t1 $ t2) = aux (aux [] Ts t2 :: args) Ts t1
blanchet@35067
   913
        | aux args _ t = list_comb (t, args)
blanchet@35067
   914
    in aux [] [] t end
blanchet@35067
   915
blanchet@35067
   916
type special_triple = int list * term list * styp
blanchet@35067
   917
blanchet@35067
   918
val cong_var_prefix = "c"
blanchet@35067
   919
blanchet@35280
   920
(* typ -> special_triple -> special_triple -> term *)
blanchet@35280
   921
fun special_congruence_axiom T (js1, ts1, x1) (js2, ts2, x2) =
blanchet@35067
   922
  let
blanchet@35067
   923
    val (bounds1, bounds2) = pairself (map Var o special_bounds) (ts1, ts2)
blanchet@35067
   924
    val Ts = binder_types T
blanchet@35067
   925
    val max_j = fold (fold Integer.max) [js1, js2] ~1
blanchet@35067
   926
    val (eqs, (args1, args2)) =
blanchet@35067
   927
      fold (fn j => case pairself (fn ps => AList.lookup (op =) ps j)
blanchet@35067
   928
                                  (js1 ~~ ts1, js2 ~~ ts2) of
blanchet@35067
   929
                      (SOME t1, SOME t2) => apfst (cons (t1, t2))
blanchet@35067
   930
                    | (SOME t1, NONE) => apsnd (apsnd (cons t1))
blanchet@35067
   931
                    | (NONE, SOME t2) => apsnd (apfst (cons t2))
blanchet@35067
   932
                    | (NONE, NONE) =>
blanchet@35067
   933
                      let val v = Var ((cong_var_prefix ^ nat_subscript j, 0),
blanchet@35067
   934
                                       nth Ts j) in
blanchet@35067
   935
                        apsnd (pairself (cons v))
blanchet@35067
   936
                      end) (max_j downto 0) ([], ([], []))
blanchet@35067
   937
  in
blanchet@35067
   938
    Logic.list_implies (eqs |> filter_out (op =) |> distinct (op =)
blanchet@35067
   939
                            |> map Logic.mk_equals,
blanchet@35067
   940
                        Logic.mk_equals (list_comb (Const x1, bounds1 @ args1),
blanchet@35067
   941
                                         list_comb (Const x2, bounds2 @ args2)))
blanchet@35075
   942
    |> close_form (* TODO: needed? *)
blanchet@35067
   943
  end
blanchet@35067
   944
blanchet@35067
   945
(* hol_context -> styp list -> term list *)
blanchet@35067
   946
fun special_congruence_axioms (hol_ctxt as {special_funs, ...}) xs =
blanchet@35067
   947
  let
blanchet@35067
   948
    val groups =
blanchet@35067
   949
      !special_funs
blanchet@35067
   950
      |> map (fn ((x, js, ts), x') => (x, (js, ts, x')))
blanchet@35067
   951
      |> AList.group (op =)
blanchet@35067
   952
      |> filter_out (is_equational_fun_surely_complete hol_ctxt o fst)
blanchet@35067
   953
      |> map (fn (x, zs) => (x, zs |> member (op =) xs x ? cons ([], [], x)))
blanchet@35067
   954
    (* special_triple -> int *)
blanchet@35067
   955
    fun generality (js, _, _) = ~(length js)
blanchet@35067
   956
    (* special_triple -> special_triple -> bool *)
blanchet@35067
   957
    fun is_more_specific (j1, t1, x1) (j2, t2, x2) =
blanchet@35067
   958
      x1 <> x2 andalso OrdList.subset (prod_ord int_ord TermOrd.term_ord)
blanchet@35067
   959
                                      (j2 ~~ t2, j1 ~~ t1)
blanchet@35280
   960
    (* typ -> special_triple list -> special_triple list -> special_triple list
blanchet@35067
   961
       -> term list -> term list *)
blanchet@35067
   962
    fun do_pass_1 _ [] [_] [_] = I
blanchet@35280
   963
      | do_pass_1 T skipped _ [] = do_pass_2 T skipped
blanchet@35280
   964
      | do_pass_1 T skipped all (z :: zs) =
blanchet@35067
   965
        case filter (is_more_specific z) all
blanchet@35067
   966
             |> sort (int_ord o pairself generality) of
blanchet@35280
   967
          [] => do_pass_1 T (z :: skipped) all zs
blanchet@35280
   968
        | (z' :: _) => cons (special_congruence_axiom T z z')
blanchet@35280
   969
                       #> do_pass_1 T skipped all zs
blanchet@35280
   970
    (* typ -> special_triple list -> term list -> term list *)
blanchet@35067
   971
    and do_pass_2 _ [] = I
blanchet@35280
   972
      | do_pass_2 T (z :: zs) =
blanchet@35280
   973
        fold (cons o special_congruence_axiom T z) zs #> do_pass_2 T zs
blanchet@35280
   974
  in fold (fn ((_, T), zs) => do_pass_1 T [] zs zs) groups [] end
blanchet@35067
   975
blanchet@35067
   976
(** Axiom selection **)
blanchet@35067
   977
blanchet@35067
   978
(* Similar to "Refute.specialize_type" but returns all matches rather than only
blanchet@35067
   979
   the first (preorder) match. *)
blanchet@35067
   980
(* theory -> styp -> term -> term list *)
blanchet@35280
   981
fun multi_specialize_type thy slack (s, T) t =
blanchet@35067
   982
  let
blanchet@35067
   983
    (* term -> (typ * term) list -> (typ * term) list *)
blanchet@35067
   984
    fun aux (Const (s', T')) ys =
blanchet@35067
   985
        if s = s' then
blanchet@35067
   986
          ys |> (if AList.defined (op =) ys T' then
blanchet@35067
   987
                   I
blanchet@35067
   988
                 else
blanchet@35067
   989
                  cons (T', Refute.monomorphic_term
blanchet@35067
   990
                                (Sign.typ_match thy (T', T) Vartab.empty) t)
blanchet@35067
   991
                  handle Type.TYPE_MATCH => I
blanchet@35067
   992
                       | Refute.REFUTE _ =>
blanchet@35067
   993
                         if slack then
blanchet@35067
   994
                           I
blanchet@35067
   995
                         else
blanchet@35067
   996
                           raise NOT_SUPPORTED ("too much polymorphism in \
blanchet@35067
   997
                                                \axiom involving " ^ quote s))
blanchet@35067
   998
        else
blanchet@35067
   999
          ys
blanchet@35067
  1000
      | aux _ ys = ys
blanchet@35067
  1001
  in map snd (fold_aterms aux t []) end
blanchet@35067
  1002
blanchet@35067
  1003
(* theory -> bool -> const_table -> styp -> term list *)
blanchet@35067
  1004
fun nondef_props_for_const thy slack table (x as (s, _)) =
blanchet@35067
  1005
  these (Symtab.lookup table s) |> maps (multi_specialize_type thy slack x)
blanchet@35067
  1006
blanchet@35067
  1007
(* 'a Symtab.table -> 'a list *)
blanchet@35067
  1008
fun all_table_entries table = Symtab.fold (append o snd) table []
blanchet@35067
  1009
(* const_table -> string -> const_table *)
blanchet@35067
  1010
fun extra_table table s = Symtab.make [(s, all_table_entries table)]
blanchet@35067
  1011
blanchet@35067
  1012
(* int -> term -> term *)
blanchet@35067
  1013
fun eval_axiom_for_term j t =
blanchet@35067
  1014
  Logic.mk_equals (Const (eval_prefix ^ string_of_int j, fastype_of t), t)
blanchet@35067
  1015
blanchet@35067
  1016
(* term -> bool *)
blanchet@35067
  1017
val is_trivial_equation = the_default false o try (op aconv o Logic.dest_equals)
blanchet@35067
  1018
blanchet@35067
  1019
(* Prevents divergence in case of cyclic or infinite axiom dependencies. *)
blanchet@35067
  1020
val axioms_max_depth = 255
blanchet@35067
  1021
blanchet@35067
  1022
(* hol_context -> term -> (term list * term list) * (bool * bool) *)
blanchet@35067
  1023
fun axioms_for_term
blanchet@35311
  1024
        (hol_ctxt as {thy, ctxt, max_bisim_depth, stds, user_axioms,
blanchet@35311
  1025
                      fast_descrs, evals, def_table, nondef_table, user_nondefs,
blanchet@35311
  1026
                      ...}) t =
blanchet@35067
  1027
  let
blanchet@35067
  1028
    type accumulator = styp list * (term list * term list)
blanchet@35067
  1029
    (* (term list * term list -> term list)
blanchet@35067
  1030
       -> ((term list -> term list) -> term list * term list
blanchet@35067
  1031
           -> term list * term list)
blanchet@35067
  1032
       -> int -> term -> accumulator -> accumulator *)
blanchet@35067
  1033
    fun add_axiom get app depth t (accum as (xs, axs)) =
blanchet@35067
  1034
      let
blanchet@35067
  1035
        val t = t |> unfold_defs_in_term hol_ctxt
blanchet@35067
  1036
                  |> skolemize_term_and_more hol_ctxt ~1
blanchet@35067
  1037
      in
blanchet@35067
  1038
        if is_trivial_equation t then
blanchet@35067
  1039
          accum
blanchet@35067
  1040
        else
blanchet@35067
  1041
          let val t' = t |> specialize_consts_in_term hol_ctxt depth in
blanchet@35067
  1042
            if exists (member (op aconv) (get axs)) [t, t'] then accum
blanchet@35067
  1043
            else add_axioms_for_term (depth + 1) t' (xs, app (cons t') axs)
blanchet@35067
  1044
          end
blanchet@35067
  1045
      end
blanchet@35067
  1046
    (* int -> term -> accumulator -> accumulator *)
blanchet@35067
  1047
    and add_def_axiom depth = add_axiom fst apfst depth
blanchet@35067
  1048
    and add_nondef_axiom depth = add_axiom snd apsnd depth
blanchet@35067
  1049
    and add_maybe_def_axiom depth t =
blanchet@35067
  1050
      (if head_of t <> @{const "==>"} then add_def_axiom
blanchet@35067
  1051
       else add_nondef_axiom) depth t
blanchet@35067
  1052
    and add_eq_axiom depth t =
blanchet@35067
  1053
      (if is_constr_pattern_formula thy t then add_def_axiom
blanchet@35067
  1054
       else add_nondef_axiom) depth t
blanchet@35067
  1055
    (* int -> term -> accumulator -> accumulator *)
blanchet@35067
  1056
    and add_axioms_for_term depth t (accum as (xs, axs)) =
blanchet@35067
  1057
      case t of
blanchet@35067
  1058
        t1 $ t2 => accum |> fold (add_axioms_for_term depth) [t1, t2]
blanchet@35067
  1059
      | Const (x as (s, T)) =>
blanchet@35220
  1060
        (if member (op =) xs x orelse
blanchet@35220
  1061
            is_built_in_const thy stds fast_descrs x then
blanchet@35067
  1062
           accum
blanchet@35067
  1063
         else
blanchet@35280
  1064
           let val accum = (x :: xs, axs) in
blanchet@35067
  1065
             if depth > axioms_max_depth then
blanchet@35067
  1066
               raise TOO_LARGE ("Nitpick_Preproc.axioms_for_term.\
blanchet@35067
  1067
                                \add_axioms_for_term",
blanchet@35067
  1068
                                "too many nested axioms (" ^
blanchet@35067
  1069
                                string_of_int depth ^ ")")
blanchet@35067
  1070
             else if Refute.is_const_of_class thy x then
blanchet@35067
  1071
               let
blanchet@35067
  1072
                 val class = Logic.class_of_const s
blanchet@35067
  1073
                 val of_class = Logic.mk_of_class (TVar (("'a", 0), [class]),
blanchet@35067
  1074
                                                   class)
blanchet@35067
  1075
                 val ax1 = try (Refute.specialize_type thy x) of_class
blanchet@35067
  1076
                 val ax2 = Option.map (Refute.specialize_type thy x o snd)
blanchet@35067
  1077
                                      (Refute.get_classdef thy class)
blanchet@35067
  1078
               in
blanchet@35067
  1079
                 fold (add_maybe_def_axiom depth) (map_filter I [ax1, ax2])
blanchet@35067
  1080
                      accum
blanchet@35067
  1081
               end
blanchet@35220
  1082
             else if is_constr thy stds x then
blanchet@35067
  1083
               accum
blanchet@35067
  1084
             else if is_equational_fun hol_ctxt x then
blanchet@35067
  1085
               fold (add_eq_axiom depth) (equational_fun_axioms hol_ctxt x)
blanchet@35067
  1086
                    accum
blanchet@35067
  1087
             else if is_abs_fun thy x then
blanchet@35067
  1088
               if is_quot_type thy (range_type T) then
blanchet@35067
  1089
                 raise NOT_SUPPORTED "\"Abs_\" function of quotient type"
blanchet@35067
  1090
               else
blanchet@35067
  1091
                 accum |> fold (add_nondef_axiom depth)
blanchet@35067
  1092
                               (nondef_props_for_const thy false nondef_table x)
blanchet@35312
  1093
                       |> (is_funky_typedef thy (range_type T) orelse
blanchet@35312
  1094
                           range_type T = nat_T)
blanchet@35067
  1095
                          ? fold (add_maybe_def_axiom depth)
blanchet@35067
  1096
                                 (nondef_props_for_const thy true
blanchet@35067
  1097
                                                    (extra_table def_table s) x)
blanchet@35067
  1098
             else if is_rep_fun thy x then
blanchet@35067
  1099
               if is_quot_type thy (domain_type T) then
blanchet@35067
  1100
                 raise NOT_SUPPORTED "\"Rep_\" function of quotient type"
blanchet@35067
  1101
               else
blanchet@35067
  1102
                 accum |> fold (add_nondef_axiom depth)
blanchet@35067
  1103
                               (nondef_props_for_const thy false nondef_table x)
blanchet@35312
  1104
                       |> (is_funky_typedef thy (range_type T) orelse
blanchet@35312
  1105
                           range_type T = nat_T)
blanchet@35067
  1106
                          ? fold (add_maybe_def_axiom depth)
blanchet@35067
  1107
                                 (nondef_props_for_const thy true
blanchet@35067
  1108
                                                    (extra_table def_table s) x)
blanchet@35067
  1109
                       |> add_axioms_for_term depth
blanchet@35067
  1110
                                              (Const (mate_of_rep_fun thy x))
blanchet@35067
  1111
                       |> fold (add_def_axiom depth)
blanchet@35067
  1112
                               (inverse_axioms_for_rep_fun thy x)
blanchet@35067
  1113
             else
blanchet@35067
  1114
               accum |> user_axioms <> SOME false
blanchet@35067
  1115
                        ? fold (add_nondef_axiom depth)
blanchet@35067
  1116
                               (nondef_props_for_const thy false nondef_table x)
blanchet@35067
  1117
           end)
blanchet@35067
  1118
        |> add_axioms_for_type depth T
blanchet@35067
  1119
      | Free (_, T) => add_axioms_for_type depth T accum
blanchet@35067
  1120
      | Var (_, T) => add_axioms_for_type depth T accum
blanchet@35067
  1121
      | Bound _ => accum
blanchet@35067
  1122
      | Abs (_, T, t) => accum |> add_axioms_for_term depth t
blanchet@35067
  1123
                               |> add_axioms_for_type depth T
blanchet@35067
  1124
    (* int -> typ -> accumulator -> accumulator *)
blanchet@35067
  1125
    and add_axioms_for_type depth T =
blanchet@35067
  1126
      case T of
blanchet@35067
  1127
        Type ("fun", Ts) => fold (add_axioms_for_type depth) Ts
blanchet@35067
  1128
      | Type ("*", Ts) => fold (add_axioms_for_type depth) Ts
blanchet@35067
  1129
      | @{typ prop} => I
blanchet@35067
  1130
      | @{typ bool} => I
blanchet@35067
  1131
      | @{typ unit} => I
blanchet@35067
  1132
      | TFree (_, S) => add_axioms_for_sort depth T S
blanchet@35067
  1133
      | TVar (_, S) => add_axioms_for_sort depth T S
blanchet@35280
  1134
      | Type (z as (_, Ts)) =>
blanchet@35067
  1135
        fold (add_axioms_for_type depth) Ts
blanchet@35067
  1136
        #> (if is_pure_typedef thy T then
blanchet@35067
  1137
              fold (add_maybe_def_axiom depth) (optimized_typedef_axioms thy z)
blanchet@35067
  1138
            else if is_quot_type thy T then
blanchet@35311
  1139
              fold (add_def_axiom depth)
blanchet@35311
  1140
                   (optimized_quot_type_axioms ctxt stds z)
blanchet@35067
  1141
            else if max_bisim_depth >= 0 andalso is_codatatype thy T then
blanchet@35067
  1142
              fold (add_maybe_def_axiom depth)
blanchet@35067
  1143
                   (codatatype_bisim_axioms hol_ctxt T)
blanchet@35067
  1144
            else
blanchet@35067
  1145
              I)
blanchet@35067
  1146
    (* int -> typ -> sort -> accumulator -> accumulator *)
blanchet@35067
  1147
    and add_axioms_for_sort depth T S =
blanchet@35067
  1148
      let
blanchet@35067
  1149
        val supers = Sign.complete_sort thy S
blanchet@35067
  1150
        val class_axioms =
blanchet@35067
  1151
          maps (fn class => map prop_of (AxClass.get_info thy class |> #axioms
blanchet@35067
  1152
                                         handle ERROR _ => [])) supers
blanchet@35067
  1153
        val monomorphic_class_axioms =
blanchet@35067
  1154
          map (fn t => case Term.add_tvars t [] of
blanchet@35067
  1155
                         [] => t
blanchet@35067
  1156
                       | [(x, S)] =>
blanchet@35067
  1157
                         Refute.monomorphic_term (Vartab.make [(x, (S, T))]) t
blanchet@35067
  1158
                       | _ => raise TERM ("Nitpick_Preproc.axioms_for_term.\
blanchet@35067
  1159
                                          \add_axioms_for_sort", [t]))
blanchet@35067
  1160
              class_axioms
blanchet@35067
  1161
      in fold (add_nondef_axiom depth) monomorphic_class_axioms end
blanchet@35067
  1162
    val (mono_user_nondefs, poly_user_nondefs) =
blanchet@35067
  1163
      List.partition (null o Term.hidden_polymorphism) user_nondefs
blanchet@35067
  1164
    val eval_axioms = map2 eval_axiom_for_term (index_seq 0 (length evals))
blanchet@35067
  1165
                           evals
blanchet@35067
  1166
    val (xs, (defs, nondefs)) =
blanchet@35067
  1167
      ([], ([], [])) |> add_axioms_for_term 1 t 
blanchet@35067
  1168
                     |> fold_rev (add_def_axiom 1) eval_axioms
blanchet@35067
  1169
                     |> user_axioms = SOME true
blanchet@35067
  1170
                        ? fold (add_nondef_axiom 1) mono_user_nondefs
blanchet@35067
  1171
    val defs = defs @ special_congruence_axioms hol_ctxt xs
blanchet@35067
  1172
  in
blanchet@35067
  1173
    ((defs, nondefs), (user_axioms = SOME true orelse null mono_user_nondefs,
blanchet@35067
  1174
                       null poly_user_nondefs))
blanchet@35067
  1175
  end
blanchet@35067
  1176
blanchet@35067
  1177
(** Simplification of constructor/selector terms **)
blanchet@35067
  1178
blanchet@35067
  1179
(* theory -> term -> term *)
blanchet@35067
  1180
fun simplify_constrs_and_sels thy t =
blanchet@35067
  1181
  let
blanchet@35067
  1182
    (* term -> int -> term *)
blanchet@35067
  1183
    fun is_nth_sel_on t' n (Const (s, _) $ t) =
blanchet@35067
  1184
        (t = t' andalso is_sel_like_and_no_discr s andalso
blanchet@35067
  1185
         sel_no_from_name s = n)
blanchet@35067
  1186
      | is_nth_sel_on _ _ _ = false
blanchet@35067
  1187
    (* term -> term list -> term *)
blanchet@35067
  1188
    fun do_term (Const (@{const_name Rep_Frac}, _)
blanchet@35067
  1189
                 $ (Const (@{const_name Abs_Frac}, _) $ t1)) [] = do_term t1 []
blanchet@35067
  1190
      | do_term (Const (@{const_name Abs_Frac}, _)
blanchet@35067
  1191
                 $ (Const (@{const_name Rep_Frac}, _) $ t1)) [] = do_term t1 []
blanchet@35067
  1192
      | do_term (t1 $ t2) args = do_term t1 (do_term t2 [] :: args)
blanchet@35067
  1193
      | do_term (t as Const (x as (s, T))) (args as _ :: _) =
blanchet@35067
  1194
        ((if is_constr_like thy x then
blanchet@35067
  1195
            if length args = num_binder_types T then
blanchet@35067
  1196
              case hd args of
blanchet@35280
  1197
                Const (_, T') $ t' =>
blanchet@35067
  1198
                if domain_type T' = body_type T andalso
blanchet@35067
  1199
                   forall (uncurry (is_nth_sel_on t'))
blanchet@35067
  1200
                          (index_seq 0 (length args) ~~ args) then
blanchet@35067
  1201
                  t'
blanchet@35067
  1202
                else
blanchet@35067
  1203
                  raise SAME ()
blanchet@35067
  1204
              | _ => raise SAME ()
blanchet@35067
  1205
            else
blanchet@35067
  1206
              raise SAME ()
blanchet@35067
  1207
          else if is_sel_like_and_no_discr s then
blanchet@35067
  1208
            case strip_comb (hd args) of
blanchet@35067
  1209
              (Const (x' as (s', T')), ts') =>
blanchet@35067
  1210
              if is_constr_like thy x' andalso
blanchet@35067
  1211
                 constr_name_for_sel_like s = s' andalso
blanchet@35067
  1212
                 not (exists is_pair_type (binder_types T')) then
blanchet@35067
  1213
                list_comb (nth ts' (sel_no_from_name s), tl args)
blanchet@35067
  1214
              else
blanchet@35067
  1215
                raise SAME ()
blanchet@35067
  1216
            | _ => raise SAME ()
blanchet@35067
  1217
          else
blanchet@35067
  1218
            raise SAME ())
blanchet@35067
  1219
         handle SAME () => betapplys (t, args))
blanchet@35067
  1220
      | do_term (Abs (s, T, t')) args =
blanchet@35067
  1221
        betapplys (Abs (s, T, do_term t' []), args)
blanchet@35067
  1222
      | do_term t args = betapplys (t, args)
blanchet@35067
  1223
  in do_term t [] end
blanchet@35067
  1224
blanchet@35067
  1225
(** Quantifier massaging: Distributing quantifiers **)
blanchet@35067
  1226
blanchet@35067
  1227
(* term -> term *)
blanchet@35067
  1228
fun distribute_quantifiers t =
blanchet@35067
  1229
  case t of
blanchet@35067
  1230
    (t0 as Const (@{const_name All}, T0)) $ Abs (s, T1, t1) =>
blanchet@35067
  1231
    (case t1 of
blanchet@35067
  1232
       (t10 as @{const "op &"}) $ t11 $ t12 =>
blanchet@35067
  1233
       t10 $ distribute_quantifiers (t0 $ Abs (s, T1, t11))
blanchet@35067
  1234
           $ distribute_quantifiers (t0 $ Abs (s, T1, t12))
blanchet@35067
  1235
     | (t10 as @{const Not}) $ t11 =>
blanchet@35067
  1236
       t10 $ distribute_quantifiers (Const (@{const_name Ex}, T0)
blanchet@35067
  1237
                                     $ Abs (s, T1, t11))
blanchet@35067
  1238
     | t1 =>
blanchet@35067
  1239
       if not (loose_bvar1 (t1, 0)) then
blanchet@35067
  1240
         distribute_quantifiers (incr_boundvars ~1 t1)
blanchet@35067
  1241
       else
blanchet@35067
  1242
         t0 $ Abs (s, T1, distribute_quantifiers t1))
blanchet@35067
  1243
  | (t0 as Const (@{const_name Ex}, T0)) $ Abs (s, T1, t1) =>
blanchet@35067
  1244
    (case distribute_quantifiers t1 of
blanchet@35067
  1245
       (t10 as @{const "op |"}) $ t11 $ t12 =>
blanchet@35067
  1246
       t10 $ distribute_quantifiers (t0 $ Abs (s, T1, t11))
blanchet@35067
  1247
           $ distribute_quantifiers (t0 $ Abs (s, T1, t12))
blanchet@35067
  1248
     | (t10 as @{const "op -->"}) $ t11 $ t12 =>
blanchet@35067
  1249
       t10 $ distribute_quantifiers (Const (@{const_name All}, T0)
blanchet@35067
  1250
                                     $ Abs (s, T1, t11))
blanchet@35067
  1251
           $ distribute_quantifiers (t0 $ Abs (s, T1, t12))
blanchet@35067
  1252
     | (t10 as @{const Not}) $ t11 =>
blanchet@35067
  1253
       t10 $ distribute_quantifiers (Const (@{const_name All}, T0)
blanchet@35067
  1254
                                     $ Abs (s, T1, t11))
blanchet@35067
  1255
     | t1 =>
blanchet@35067
  1256
       if not (loose_bvar1 (t1, 0)) then
blanchet@35067
  1257
         distribute_quantifiers (incr_boundvars ~1 t1)
blanchet@35067
  1258
       else
blanchet@35067
  1259
         t0 $ Abs (s, T1, distribute_quantifiers t1))
blanchet@35067
  1260
  | t1 $ t2 => distribute_quantifiers t1 $ distribute_quantifiers t2
blanchet@35067
  1261
  | Abs (s, T, t') => Abs (s, T, distribute_quantifiers t')
blanchet@35067
  1262
  | _ => t
blanchet@35067
  1263
blanchet@35067
  1264
(** Quantifier massaging: Pushing quantifiers inward **)
blanchet@35067
  1265
blanchet@35067
  1266
(* int -> int -> (int -> int) -> term -> term *)
blanchet@35067
  1267
fun renumber_bounds j n f t =
blanchet@35067
  1268
  case t of
blanchet@35067
  1269
    t1 $ t2 => renumber_bounds j n f t1 $ renumber_bounds j n f t2
blanchet@35067
  1270
  | Abs (s, T, t') => Abs (s, T, renumber_bounds (j + 1) n f t')
blanchet@35067
  1271
  | Bound j' =>
blanchet@35067
  1272
    Bound (if j' >= j andalso j' < j + n then f (j' - j) + j else j')
blanchet@35067
  1273
  | _ => t
blanchet@35067
  1274
blanchet@35067
  1275
(* Maximum number of quantifiers in a cluster for which the exponential
blanchet@35067
  1276
   algorithm is used. Larger clusters use a heuristic inspired by Claessen &
blanchet@35067
  1277
   Sörensson's polynomial binary splitting procedure (p. 5 of their MODEL 2003
blanchet@35067
  1278
   paper). *)
blanchet@35067
  1279
val quantifier_cluster_threshold = 7
blanchet@35067
  1280
blanchet@35280
  1281
(* term -> term *)
blanchet@35280
  1282
val push_quantifiers_inward =
blanchet@35067
  1283
  let
blanchet@35067
  1284
    (* string -> string list -> typ list -> term -> term *)
blanchet@35067
  1285
    fun aux quant_s ss Ts t =
blanchet@35067
  1286
      (case t of
blanchet@35280
  1287
         Const (s0, _) $ Abs (s1, T1, t1 as _ $ _) =>
blanchet@35067
  1288
         if s0 = quant_s then
blanchet@35067
  1289
           aux s0 (s1 :: ss) (T1 :: Ts) t1
blanchet@35067
  1290
         else if quant_s = "" andalso
blanchet@35067
  1291
                 (s0 = @{const_name All} orelse s0 = @{const_name Ex}) then
blanchet@35067
  1292
           aux s0 [s1] [T1] t1
blanchet@35067
  1293
         else
blanchet@35067
  1294
           raise SAME ()
blanchet@35067
  1295
       | _ => raise SAME ())
blanchet@35067
  1296
      handle SAME () =>
blanchet@35067
  1297
             case t of
blanchet@35067
  1298
               t1 $ t2 =>
blanchet@35067
  1299
               if quant_s = "" then
blanchet@35067
  1300
                 aux "" [] [] t1 $ aux "" [] [] t2
blanchet@35067
  1301
               else
blanchet@35067
  1302
                 let
blanchet@35067
  1303
                   val typical_card = 4
blanchet@35067
  1304
                   (* ('a -> ''b list) -> 'a list -> ''b list *)
blanchet@35067
  1305
                   fun big_union proj ps =
blanchet@35067
  1306
                     fold (fold (insert (op =)) o proj) ps []
blanchet@35067
  1307
                   val (ts, connective) = strip_any_connective t
blanchet@35067
  1308
                   val T_costs =
blanchet@35067
  1309
                     map (bounded_card_of_type 65536 typical_card []) Ts
blanchet@35067
  1310
                   val t_costs = map size_of_term ts
blanchet@35067
  1311
                   val num_Ts = length Ts
blanchet@35067
  1312
                   (* int -> int *)
blanchet@35067
  1313
                   val flip = curry (op -) (num_Ts - 1)
blanchet@35067
  1314
                   val t_boundss = map (map flip o loose_bnos) ts
blanchet@35067
  1315
                   (* (int list * int) list -> int list
blanchet@35067
  1316
                      -> (int list * int) list *)
blanchet@35067
  1317
                   fun merge costly_boundss [] = costly_boundss
blanchet@35067
  1318
                     | merge costly_boundss (j :: js) =
blanchet@35067
  1319
                       let
blanchet@35067
  1320
                         val (yeas, nays) =
blanchet@35067
  1321
                           List.partition (fn (bounds, _) =>
blanchet@35067
  1322
                                              member (op =) bounds j)
blanchet@35067
  1323
                                          costly_boundss
blanchet@35067
  1324
                         val yeas_bounds = big_union fst yeas
blanchet@35067
  1325
                         val yeas_cost = Integer.sum (map snd yeas)
blanchet@35067
  1326
                                         * nth T_costs j
blanchet@35067
  1327
                       in merge ((yeas_bounds, yeas_cost) :: nays) js end
blanchet@35067
  1328
                   (* (int list * int) list -> int list -> int *)
blanchet@35067
  1329
                   val cost = Integer.sum o map snd oo merge
blanchet@35067
  1330
                   (* (int list * int) list -> int list -> int list *)
blanchet@35067
  1331
                   fun heuristically_best_permutation _ [] = []
blanchet@35067
  1332
                     | heuristically_best_permutation costly_boundss js =
blanchet@35067
  1333
                       let
blanchet@35067
  1334
                         val (costly_boundss, (j, js)) =
blanchet@35067
  1335
                           js |> map (`(merge costly_boundss o single))
blanchet@35067
  1336
                              |> sort (int_ord
blanchet@35067
  1337
                                       o pairself (Integer.sum o map snd o fst))
blanchet@35067
  1338
                              |> split_list |>> hd ||> pairf hd tl
blanchet@35067
  1339
                       in
blanchet@35067
  1340
                         j :: heuristically_best_permutation costly_boundss js
blanchet@35067
  1341
                       end
blanchet@35067
  1342
                   val js =
blanchet@35067
  1343
                     if length Ts <= quantifier_cluster_threshold then
blanchet@35067
  1344
                       all_permutations (index_seq 0 num_Ts)
blanchet@35067
  1345
                       |> map (`(cost (t_boundss ~~ t_costs)))
blanchet@35067
  1346
                       |> sort (int_ord o pairself fst) |> hd |> snd
blanchet@35067
  1347
                     else
blanchet@35067
  1348
                       heuristically_best_permutation (t_boundss ~~ t_costs)
blanchet@35067
  1349
                                                      (index_seq 0 num_Ts)
blanchet@35067
  1350
                   val back_js = map (fn j => find_index (curry (op =) j) js)
blanchet@35067
  1351
                                     (index_seq 0 num_Ts)
blanchet@35067
  1352
                   val ts = map (renumber_bounds 0 num_Ts (nth back_js o flip))
blanchet@35067
  1353
                                ts
blanchet@35067
  1354
                   (* (term * int list) list -> term *)
blanchet@35067
  1355
                   fun mk_connection [] =
blanchet@35067
  1356
                       raise ARG ("Nitpick_Preproc.push_quantifiers_inward.aux.\
blanchet@35067
  1357
                                  \mk_connection", "")
blanchet@35067
  1358
                     | mk_connection ts_cum_bounds =
blanchet@35067
  1359
                       ts_cum_bounds |> map fst
blanchet@35067
  1360
                       |> foldr1 (fn (t1, t2) => connective $ t1 $ t2)
blanchet@35067
  1361
                   (* (term * int list) list -> int list -> term *)
blanchet@35067
  1362
                   fun build ts_cum_bounds [] = ts_cum_bounds |> mk_connection
blanchet@35067
  1363
                     | build ts_cum_bounds (j :: js) =
blanchet@35067
  1364
                       let
blanchet@35067
  1365
                         val (yeas, nays) =
blanchet@35067
  1366
                           List.partition (fn (_, bounds) =>
blanchet@35067
  1367
                                              member (op =) bounds j)
blanchet@35067
  1368
                                          ts_cum_bounds
blanchet@35067
  1369
                           ||> map (apfst (incr_boundvars ~1))
blanchet@35067
  1370
                       in
blanchet@35067
  1371
                         if null yeas then
blanchet@35067
  1372
                           build nays js
blanchet@35067
  1373
                         else
blanchet@35067
  1374
                           let val T = nth Ts (flip j) in
blanchet@35067
  1375
                             build ((Const (quant_s, (T --> bool_T) --> bool_T)
blanchet@35067
  1376
                                     $ Abs (nth ss (flip j), T,
blanchet@35067
  1377
                                            mk_connection yeas),
blanchet@35067
  1378
                                      big_union snd yeas) :: nays) js
blanchet@35067
  1379
                           end
blanchet@35067
  1380
                       end
blanchet@35067
  1381
                 in build (ts ~~ t_boundss) js end
blanchet@35067
  1382
             | Abs (s, T, t') => Abs (s, T, aux "" [] [] t')
blanchet@35067
  1383
             | _ => t
blanchet@35067
  1384
  in aux "" [] [] end
blanchet@35067
  1385
blanchet@35067
  1386
(** Preprocessor entry point **)
blanchet@35067
  1387
blanchet@35190
  1388
(* hol_context -> term
blanchet@35190
  1389
   -> ((term list * term list) * (bool * bool)) * term * bool *)
blanchet@35220
  1390
fun preprocess_term (hol_ctxt as {thy, stds, binary_ints, destroy_constrs,
blanchet@35220
  1391
                                  boxes, skolemize, uncurry, ...}) t =
blanchet@35067
  1392
  let
blanchet@35067
  1393
    val skolem_depth = if skolemize then 4 else ~1
blanchet@35067
  1394
    val (((def_ts, nondef_ts), (got_all_mono_user_axioms, no_poly_user_axioms)),
blanchet@35067
  1395
         core_t) = t |> unfold_defs_in_term hol_ctxt
blanchet@35075
  1396
                     |> close_form
blanchet@35067
  1397
                     |> skolemize_term_and_more hol_ctxt skolem_depth
blanchet@35067
  1398
                     |> specialize_consts_in_term hol_ctxt 0
blanchet@35067
  1399
                     |> `(axioms_for_term hol_ctxt)
blanchet@35067
  1400
    val binarize =
blanchet@35220
  1401
      is_standard_datatype thy stds nat_T andalso
blanchet@35067
  1402
      case binary_ints of
blanchet@35067
  1403
        SOME false => false
blanchet@35220
  1404
      | _ => forall may_use_binary_ints (core_t :: def_ts @ nondef_ts) andalso
blanchet@35220
  1405
             (binary_ints = SOME true orelse
blanchet@35220
  1406
              exists should_use_binary_ints (core_t :: def_ts @ nondef_ts))
blanchet@35067
  1407
    val box = exists (not_equal (SOME false) o snd) boxes
blanchet@35067
  1408
    val table =
blanchet@35067
  1409
      Termtab.empty |> uncurry
blanchet@35067
  1410
        ? fold (add_to_uncurry_table thy) (core_t :: def_ts @ nondef_ts)
blanchet@35280
  1411
    (* bool -> term -> term *)
blanchet@35280
  1412
    fun do_rest def =
blanchet@35067
  1413
      binarize ? binarize_nat_and_int_in_term
blanchet@35067
  1414
      #> uncurry ? uncurry_term table
blanchet@35067
  1415
      #> box ? box_fun_and_pair_in_term hol_ctxt def
blanchet@35220
  1416
      #> destroy_constrs ? (pull_out_universal_constrs hol_ctxt def
blanchet@35220
  1417
                            #> pull_out_existential_constrs hol_ctxt
blanchet@35067
  1418
                            #> destroy_pulled_out_constrs hol_ctxt def)
blanchet@35067
  1419
      #> curry_assms
blanchet@35067
  1420
      #> destroy_universal_equalities
blanchet@35220
  1421
      #> destroy_existential_equalities hol_ctxt
blanchet@35067
  1422
      #> simplify_constrs_and_sels thy
blanchet@35067
  1423
      #> distribute_quantifiers
blanchet@35280
  1424
      #> push_quantifiers_inward
blanchet@35075
  1425
      #> close_form
blanchet@35067
  1426
      #> Term.map_abs_vars shortest_name
blanchet@35384
  1427
    val def_ts = map (do_rest true) def_ts
blanchet@35384
  1428
    val nondef_ts = map (do_rest false) nondef_ts
blanchet@35384
  1429
    val core_t = do_rest false core_t
blanchet@35067
  1430
  in
blanchet@35384
  1431
    (((def_ts, nondef_ts), (got_all_mono_user_axioms, no_poly_user_axioms)),
blanchet@35384
  1432
     core_t, binarize)
blanchet@35067
  1433
  end
blanchet@35067
  1434
blanchet@35067
  1435
end;