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