src/HOL/Tools/Nitpick/nitpick_mono.ML
author blanchet
Tue Sep 14 13:44:43 2010 +0200 (2010-09-14)
changeset 39360 cdf2c3341422
parent 39359 6f49c7fbb1b1
child 40058 b4f62d0660e0
permissions -rw-r--r--
eliminate more clutter related to "fast_descrs" optimization
blanchet@33982
     1
(*  Title:      HOL/Tools/Nitpick/nitpick_mono.ML
blanchet@33192
     2
    Author:     Jasmin Blanchette, TU Muenchen
blanchet@34982
     3
    Copyright   2009, 2010
blanchet@33192
     4
blanchet@35384
     5
Monotonicity inference for higher-order logic.
blanchet@33192
     6
*)
blanchet@33192
     7
blanchet@33192
     8
signature NITPICK_MONO =
blanchet@33192
     9
sig
blanchet@35070
    10
  type hol_context = Nitpick_HOL.hol_context
blanchet@33192
    11
blanchet@38179
    12
  val trace : bool Unsynchronized.ref
blanchet@33192
    13
  val formulas_monotonic :
blanchet@35386
    14
    hol_context -> bool -> typ -> term list * term list -> bool
blanchet@35665
    15
  val finitize_funs :
blanchet@35665
    16
    hol_context -> bool -> (typ option * bool option) list -> typ
blanchet@35665
    17
    -> term list * term list -> term list * term list
blanchet@33192
    18
end;
blanchet@33192
    19
blanchet@33232
    20
structure Nitpick_Mono : NITPICK_MONO =
blanchet@33192
    21
struct
blanchet@33192
    22
blanchet@33232
    23
open Nitpick_Util
blanchet@33232
    24
open Nitpick_HOL
blanchet@33192
    25
blanchet@33192
    26
type var = int
blanchet@33192
    27
blanchet@34982
    28
datatype sign = Plus | Minus
blanchet@33192
    29
datatype sign_atom = S of sign | V of var
blanchet@33192
    30
blanchet@33192
    31
type literal = var * sign
blanchet@33192
    32
blanchet@35385
    33
datatype mtyp =
blanchet@35385
    34
  MAlpha |
blanchet@35385
    35
  MFun of mtyp * sign_atom * mtyp |
blanchet@35385
    36
  MPair of mtyp * mtyp |
blanchet@35385
    37
  MType of string * mtyp list |
blanchet@35385
    38
  MRec of string * typ list
blanchet@33192
    39
blanchet@35385
    40
datatype mterm =
blanchet@35386
    41
  MRaw of term * mtyp |
blanchet@35385
    42
  MAbs of string * typ * mtyp * sign_atom * mterm |
blanchet@35385
    43
  MApp of mterm * mterm
blanchet@35385
    44
blanchet@35385
    45
type mdata =
blanchet@35070
    46
  {hol_ctxt: hol_context,
blanchet@35190
    47
   binarize: bool,
blanchet@33192
    48
   alpha_T: typ,
blanchet@35665
    49
   no_harmless: bool,
blanchet@33192
    50
   max_fresh: int Unsynchronized.ref,
blanchet@35665
    51
   datatype_mcache: ((string * typ list) * mtyp) list Unsynchronized.ref,
blanchet@35665
    52
   constr_mcache: (styp * mtyp) list Unsynchronized.ref}
blanchet@33192
    53
blanchet@35812
    54
exception UNSOLVABLE of unit
blanchet@35665
    55
exception MTYPE of string * mtyp list * typ list
blanchet@35665
    56
exception MTERM of string * mterm list
blanchet@33192
    57
blanchet@38179
    58
val trace = Unsynchronized.ref false
blanchet@38179
    59
fun trace_msg msg = if !trace then tracing (msg ()) else ()
blanchet@33192
    60
blanchet@33192
    61
val string_for_var = signed_string_of_int
blanchet@33192
    62
fun string_for_vars sep [] = "0\<^bsub>" ^ sep ^ "\<^esub>"
blanchet@33192
    63
  | string_for_vars sep xs = space_implode sep (map string_for_var xs)
blanchet@33192
    64
fun subscript_string_for_vars sep xs =
blanchet@33192
    65
  if null xs then "" else "\<^bsub>" ^ string_for_vars sep xs ^ "\<^esub>"
blanchet@33192
    66
blanchet@34982
    67
fun string_for_sign Plus = "+"
blanchet@34982
    68
  | string_for_sign Minus = "-"
blanchet@33192
    69
blanchet@34982
    70
fun xor sn1 sn2 = if sn1 = sn2 then Plus else Minus
blanchet@34982
    71
val negate = xor Minus
blanchet@33192
    72
blanchet@33192
    73
fun string_for_sign_atom (S sn) = string_for_sign sn
blanchet@35665
    74
  | string_for_sign_atom (V x) = string_for_var x
blanchet@33192
    75
blanchet@33192
    76
fun string_for_literal (x, sn) = string_for_var x ^ " = " ^ string_for_sign sn
blanchet@33192
    77
blanchet@35385
    78
val bool_M = MType (@{type_name bool}, [])
blanchet@35386
    79
val dummy_M = MType (nitpick_prefix ^ "dummy", [])
blanchet@33192
    80
blanchet@35385
    81
fun is_MRec (MRec _) = true
blanchet@35385
    82
  | is_MRec _ = false
blanchet@35385
    83
fun dest_MFun (MFun z) = z
blanchet@35665
    84
  | dest_MFun M = raise MTYPE ("Nitpick_Mono.dest_MFun", [M], [])
blanchet@33192
    85
blanchet@33192
    86
val no_prec = 100
blanchet@33192
    87
blanchet@35385
    88
fun precedence_of_mtype (MFun _) = 1
blanchet@35385
    89
  | precedence_of_mtype (MPair _) = 2
blanchet@35385
    90
  | precedence_of_mtype _ = no_prec
blanchet@33192
    91
blanchet@35385
    92
val string_for_mtype =
blanchet@33192
    93
  let
blanchet@35385
    94
    fun aux outer_prec M =
blanchet@33192
    95
      let
blanchet@35385
    96
        val prec = precedence_of_mtype M
blanchet@33192
    97
        val need_parens = (prec < outer_prec)
blanchet@33192
    98
      in
blanchet@33192
    99
        (if need_parens then "(" else "") ^
blanchet@35386
   100
        (if M = dummy_M then
blanchet@35386
   101
           "_"
blanchet@35386
   102
         else case M of
blanchet@35386
   103
             MAlpha => "\<alpha>"
blanchet@35386
   104
           | MFun (M1, a, M2) =>
blanchet@35386
   105
             aux (prec + 1) M1 ^ " \<Rightarrow>\<^bsup>" ^
blanchet@35386
   106
             string_for_sign_atom a ^ "\<^esup> " ^ aux prec M2
blanchet@35386
   107
           | MPair (M1, M2) => aux (prec + 1) M1 ^ " \<times> " ^ aux prec M2
blanchet@35386
   108
           | MType (s, []) =>
blanchet@35386
   109
             if s = @{type_name prop} orelse s = @{type_name bool} then "o"
blanchet@35386
   110
             else s
blanchet@35386
   111
           | MType (s, Ms) => "(" ^ commas (map (aux 0) Ms) ^ ") " ^ s
blanchet@35386
   112
           | MRec (s, _) => "[" ^ s ^ "]") ^
blanchet@33192
   113
        (if need_parens then ")" else "")
blanchet@33192
   114
      end
blanchet@33192
   115
  in aux 0 end
blanchet@33192
   116
blanchet@35385
   117
fun flatten_mtype (MPair (M1, M2)) = maps flatten_mtype [M1, M2]
blanchet@35385
   118
  | flatten_mtype (MType (_, Ms)) = maps flatten_mtype Ms
blanchet@35385
   119
  | flatten_mtype M = [M]
blanchet@35385
   120
blanchet@35386
   121
fun precedence_of_mterm (MRaw _) = no_prec
blanchet@35385
   122
  | precedence_of_mterm (MAbs _) = 1
blanchet@35385
   123
  | precedence_of_mterm (MApp _) = 2
blanchet@33192
   124
blanchet@35385
   125
fun string_for_mterm ctxt =
blanchet@35385
   126
  let
blanchet@35385
   127
    fun mtype_annotation M = "\<^bsup>" ^ string_for_mtype M ^ "\<^esup>"
blanchet@35385
   128
    fun aux outer_prec m =
blanchet@35385
   129
      let
blanchet@35385
   130
        val prec = precedence_of_mterm m
blanchet@35385
   131
        val need_parens = (prec < outer_prec)
blanchet@35385
   132
      in
blanchet@35385
   133
        (if need_parens then "(" else "") ^
blanchet@35385
   134
        (case m of
blanchet@35386
   135
           MRaw (t, M) => Syntax.string_of_term ctxt t ^ mtype_annotation M
blanchet@35385
   136
         | MAbs (s, _, M, a, m) =>
blanchet@35385
   137
           "\<lambda>" ^ s ^ mtype_annotation M ^ ".\<^bsup>" ^
blanchet@35385
   138
           string_for_sign_atom a ^ "\<^esup> " ^ aux prec m
blanchet@35385
   139
         | MApp (m1, m2) => aux prec m1 ^ " " ^ aux (prec + 1) m2) ^
blanchet@35385
   140
        (if need_parens then ")" else "")
blanchet@35385
   141
      end
blanchet@35385
   142
  in aux 0 end
blanchet@35385
   143
blanchet@35386
   144
fun mtype_of_mterm (MRaw (_, M)) = M
blanchet@35385
   145
  | mtype_of_mterm (MAbs (_, _, M, a, m)) = MFun (M, a, mtype_of_mterm m)
blanchet@35385
   146
  | mtype_of_mterm (MApp (m1, _)) =
blanchet@35385
   147
    case mtype_of_mterm m1 of
blanchet@35385
   148
      MFun (_, _, M12) => M12
blanchet@35665
   149
    | M1 => raise MTYPE ("Nitpick_Mono.mtype_of_mterm", [M1], [])
blanchet@35665
   150
blanchet@35665
   151
fun strip_mcomb (MApp (m1, m2)) = strip_mcomb m1 ||> (fn ms => append ms [m2])
blanchet@35665
   152
  | strip_mcomb m = (m, [])
blanchet@35385
   153
blanchet@35665
   154
fun initial_mdata hol_ctxt binarize no_harmless alpha_T =
blanchet@35190
   155
  ({hol_ctxt = hol_ctxt, binarize = binarize, alpha_T = alpha_T,
blanchet@35665
   156
    no_harmless = no_harmless, max_fresh = Unsynchronized.ref 0,
blanchet@35665
   157
    datatype_mcache = Unsynchronized.ref [],
blanchet@35665
   158
    constr_mcache = Unsynchronized.ref []} : mdata)
blanchet@33192
   159
blanchet@33192
   160
fun could_exist_alpha_subtype alpha_T (T as Type (_, Ts)) =
blanchet@34936
   161
    T = alpha_T orelse (not (is_fp_iterator_type T) andalso
blanchet@34936
   162
                        exists (could_exist_alpha_subtype alpha_T) Ts)
blanchet@33192
   163
  | could_exist_alpha_subtype alpha_T T = (T = alpha_T)
blanchet@35385
   164
fun could_exist_alpha_sub_mtype _ (alpha_T as TFree _) T =
blanchet@34121
   165
    could_exist_alpha_subtype alpha_T T
blanchet@37256
   166
  | could_exist_alpha_sub_mtype ctxt alpha_T T =
blanchet@37256
   167
    (T = alpha_T orelse is_datatype ctxt [(NONE, true)] T)
blanchet@33192
   168
blanchet@35385
   169
fun exists_alpha_sub_mtype MAlpha = true
blanchet@35385
   170
  | exists_alpha_sub_mtype (MFun (M1, _, M2)) =
blanchet@35385
   171
    exists exists_alpha_sub_mtype [M1, M2]
blanchet@35385
   172
  | exists_alpha_sub_mtype (MPair (M1, M2)) =
blanchet@35385
   173
    exists exists_alpha_sub_mtype [M1, M2]
blanchet@35385
   174
  | exists_alpha_sub_mtype (MType (_, Ms)) = exists exists_alpha_sub_mtype Ms
blanchet@35385
   175
  | exists_alpha_sub_mtype (MRec _) = true
blanchet@33192
   176
blanchet@35385
   177
fun exists_alpha_sub_mtype_fresh MAlpha = true
blanchet@35385
   178
  | exists_alpha_sub_mtype_fresh (MFun (_, V _, _)) = true
blanchet@35385
   179
  | exists_alpha_sub_mtype_fresh (MFun (_, _, M2)) =
blanchet@35385
   180
    exists_alpha_sub_mtype_fresh M2
blanchet@35385
   181
  | exists_alpha_sub_mtype_fresh (MPair (M1, M2)) =
blanchet@35385
   182
    exists exists_alpha_sub_mtype_fresh [M1, M2]
blanchet@35385
   183
  | exists_alpha_sub_mtype_fresh (MType (_, Ms)) =
blanchet@35385
   184
    exists exists_alpha_sub_mtype_fresh Ms
blanchet@35385
   185
  | exists_alpha_sub_mtype_fresh (MRec _) = true
blanchet@33192
   186
blanchet@35385
   187
fun constr_mtype_for_binders z Ms =
blanchet@35385
   188
  fold_rev (fn M => curry3 MFun M (S Minus)) Ms (MRec z)
blanchet@33192
   189
blanchet@35385
   190
fun repair_mtype _ _ MAlpha = MAlpha
blanchet@35385
   191
  | repair_mtype cache seen (MFun (M1, a, M2)) =
blanchet@35385
   192
    MFun (repair_mtype cache seen M1, a, repair_mtype cache seen M2)
blanchet@35385
   193
  | repair_mtype cache seen (MPair Mp) =
blanchet@35385
   194
    MPair (pairself (repair_mtype cache seen) Mp)
blanchet@35385
   195
  | repair_mtype cache seen (MType (s, Ms)) =
blanchet@35385
   196
    MType (s, maps (flatten_mtype o repair_mtype cache seen) Ms)
blanchet@35385
   197
  | repair_mtype cache seen (MRec (z as (s, _))) =
blanchet@33192
   198
    case AList.lookup (op =) cache z |> the of
blanchet@35385
   199
      MRec _ => MType (s, [])
blanchet@35385
   200
    | M => if member (op =) seen M then MType (s, [])
blanchet@35385
   201
           else repair_mtype cache (M :: seen) M
blanchet@33192
   202
blanchet@35665
   203
fun repair_datatype_mcache cache =
blanchet@33192
   204
  let
blanchet@35385
   205
    fun repair_one (z, M) =
blanchet@33192
   206
      Unsynchronized.change cache
blanchet@35385
   207
          (AList.update (op =) (z, repair_mtype (!cache) [] M))
blanchet@33192
   208
  in List.app repair_one (rev (!cache)) end
blanchet@33192
   209
blanchet@35665
   210
fun repair_constr_mcache dtype_cache constr_mcache =
blanchet@33192
   211
  let
blanchet@35385
   212
    fun repair_one (x, M) =
blanchet@35665
   213
      Unsynchronized.change constr_mcache
blanchet@35385
   214
          (AList.update (op =) (x, repair_mtype dtype_cache [] M))
blanchet@35665
   215
  in List.app repair_one (!constr_mcache) end
blanchet@35665
   216
blanchet@35665
   217
fun is_fin_fun_supported_type @{typ prop} = true
blanchet@35665
   218
  | is_fin_fun_supported_type @{typ bool} = true
blanchet@35665
   219
  | is_fin_fun_supported_type (Type (@{type_name option}, _)) = true
blanchet@35665
   220
  | is_fin_fun_supported_type _ = false
blanchet@35665
   221
fun fin_fun_body _ _ (t as @{term False}) = SOME t
blanchet@35665
   222
  | fin_fun_body _ _ (t as Const (@{const_name None}, _)) = SOME t
blanchet@35665
   223
  | fin_fun_body dom_T ran_T
blanchet@35665
   224
                 ((t0 as Const (@{const_name If}, _))
haftmann@38864
   225
                  $ (t1 as Const (@{const_name HOL.eq}, _) $ Bound 0 $ t1')
blanchet@35665
   226
                  $ t2 $ t3) =
blanchet@35665
   227
    (if loose_bvar1 (t1', 0) then
blanchet@35665
   228
       NONE
blanchet@35665
   229
     else case fin_fun_body dom_T ran_T t3 of
blanchet@35665
   230
       NONE => NONE
blanchet@35665
   231
     | SOME t3 =>
blanchet@35665
   232
       SOME (t0 $ (Const (@{const_name is_unknown}, dom_T --> bool_T) $ t1')
blanchet@35665
   233
                $ (Const (@{const_name unknown}, ran_T)) $ (t0 $ t1 $ t2 $ t3)))
blanchet@35665
   234
  | fin_fun_body _ _ _ = NONE
blanchet@33192
   235
blanchet@35672
   236
fun fresh_mfun_for_fun_type (mdata as {max_fresh, ...} : mdata) all_minus
blanchet@35672
   237
                            T1 T2 =
blanchet@33192
   238
  let
blanchet@35672
   239
    val M1 = fresh_mtype_for_type mdata all_minus T1
blanchet@35672
   240
    val M2 = fresh_mtype_for_type mdata all_minus T2
blanchet@35672
   241
    val a = if not all_minus andalso exists_alpha_sub_mtype_fresh M1 andalso
blanchet@35672
   242
               is_fin_fun_supported_type (body_type T2) then
blanchet@35385
   243
              V (Unsynchronized.inc max_fresh)
blanchet@35385
   244
            else
blanchet@35385
   245
              S Minus
blanchet@35385
   246
  in (M1, a, M2) end
blanchet@37256
   247
and fresh_mtype_for_type (mdata as {hol_ctxt as {ctxt, ...}, binarize, alpha_T,
blanchet@35672
   248
                                    datatype_mcache, constr_mcache, ...})
blanchet@35672
   249
                         all_minus =
blanchet@35385
   250
  let
blanchet@35385
   251
    fun do_type T =
blanchet@33192
   252
      if T = alpha_T then
blanchet@35385
   253
        MAlpha
blanchet@33192
   254
      else case T of
blanchet@35665
   255
        Type (@{type_name fun}, [T1, T2]) =>
blanchet@39342
   256
        MFun (fresh_mfun_for_fun_type mdata all_minus T1 T2)
blanchet@38190
   257
      | Type (@{type_name prod}, [T1, T2]) => MPair (pairself do_type (T1, T2))
blanchet@33192
   258
      | Type (z as (s, _)) =>
blanchet@37256
   259
        if could_exist_alpha_sub_mtype ctxt alpha_T T then
blanchet@35665
   260
          case AList.lookup (op =) (!datatype_mcache) z of
blanchet@35385
   261
            SOME M => M
blanchet@33192
   262
          | NONE =>
blanchet@33192
   263
            let
blanchet@35665
   264
              val _ = Unsynchronized.change datatype_mcache (cons (z, MRec z))
blanchet@35219
   265
              val xs = binarized_and_boxed_datatype_constrs hol_ctxt binarize T
blanchet@35385
   266
              val (all_Ms, constr_Ms) =
blanchet@35385
   267
                fold_rev (fn (_, T') => fn (all_Ms, constr_Ms) =>
blanchet@33192
   268
                             let
blanchet@35385
   269
                               val binder_Ms = map do_type (binder_types T')
blanchet@35385
   270
                               val new_Ms = filter exists_alpha_sub_mtype_fresh
blanchet@35385
   271
                                                   binder_Ms
blanchet@35385
   272
                               val constr_M = constr_mtype_for_binders z
blanchet@35385
   273
                                                                       binder_Ms
blanchet@33192
   274
                             in
blanchet@35385
   275
                               (union (op =) new_Ms all_Ms,
blanchet@35385
   276
                                constr_M :: constr_Ms)
blanchet@33192
   277
                             end)
blanchet@33192
   278
                         xs ([], [])
blanchet@35385
   279
              val M = MType (s, all_Ms)
blanchet@35665
   280
              val _ = Unsynchronized.change datatype_mcache
blanchet@35385
   281
                          (AList.update (op =) (z, M))
blanchet@35665
   282
              val _ = Unsynchronized.change constr_mcache
blanchet@35385
   283
                          (append (xs ~~ constr_Ms))
blanchet@33192
   284
            in
blanchet@35665
   285
              if forall (not o is_MRec o snd) (!datatype_mcache) then
blanchet@35665
   286
                (repair_datatype_mcache datatype_mcache;
blanchet@35665
   287
                 repair_constr_mcache (!datatype_mcache) constr_mcache;
blanchet@35665
   288
                 AList.lookup (op =) (!datatype_mcache) z |> the)
blanchet@33192
   289
              else
blanchet@35385
   290
                M
blanchet@33192
   291
            end
blanchet@33192
   292
        else
blanchet@35385
   293
          MType (s, [])
blanchet@37260
   294
      | _ => MType (simple_string_of_typ T, [])
blanchet@33192
   295
  in do_type end
blanchet@33192
   296
blanchet@35385
   297
fun prodM_factors (MPair (M1, M2)) = maps prodM_factors [M1, M2]
blanchet@35385
   298
  | prodM_factors M = [M]
blanchet@35665
   299
fun curried_strip_mtype (MFun (M1, _, M2)) =
blanchet@35385
   300
    curried_strip_mtype M2 |>> append (prodM_factors M1)
blanchet@35385
   301
  | curried_strip_mtype M = ([], M)
blanchet@35385
   302
fun sel_mtype_from_constr_mtype s M =
blanchet@35385
   303
  let val (arg_Ms, dataM) = curried_strip_mtype M in
blanchet@35385
   304
    MFun (dataM, S Minus,
blanchet@35385
   305
          case sel_no_from_name s of ~1 => bool_M | n => nth arg_Ms n)
blanchet@33192
   306
  end
blanchet@33192
   307
blanchet@37256
   308
fun mtype_for_constr (mdata as {hol_ctxt = {ctxt, ...}, alpha_T, constr_mcache,
blanchet@33192
   309
                                ...}) (x as (_, T)) =
blanchet@37256
   310
  if could_exist_alpha_sub_mtype ctxt alpha_T T then
blanchet@35665
   311
    case AList.lookup (op =) (!constr_mcache) x of
blanchet@35385
   312
      SOME M => M
blanchet@35384
   313
    | NONE => if T = alpha_T then
blanchet@35672
   314
                let val M = fresh_mtype_for_type mdata false T in
blanchet@35665
   315
                  (Unsynchronized.change constr_mcache (cons (x, M)); M)
blanchet@35384
   316
                end
blanchet@35384
   317
              else
blanchet@35672
   318
                (fresh_mtype_for_type mdata false (body_type T);
blanchet@35665
   319
                 AList.lookup (op =) (!constr_mcache) x |> the)
blanchet@33192
   320
  else
blanchet@35672
   321
    fresh_mtype_for_type mdata false T
blanchet@35385
   322
fun mtype_for_sel (mdata as {hol_ctxt, binarize, ...}) (x as (s, _)) =
blanchet@35190
   323
  x |> binarized_and_boxed_constr_for_sel hol_ctxt binarize
blanchet@35385
   324
    |> mtype_for_constr mdata |> sel_mtype_from_constr_mtype s
blanchet@33192
   325
blanchet@35665
   326
fun resolve_sign_atom lits (V x) =
blanchet@35665
   327
    x |> AList.lookup (op =) lits |> Option.map S |> the_default (V x)
blanchet@35665
   328
  | resolve_sign_atom _ a = a
blanchet@35665
   329
fun resolve_mtype lits =
blanchet@33192
   330
  let
blanchet@35385
   331
    fun aux MAlpha = MAlpha
blanchet@35665
   332
      | aux (MFun (M1, a, M2)) = MFun (aux M1, resolve_sign_atom lits a, aux M2)
blanchet@35385
   333
      | aux (MPair Mp) = MPair (pairself aux Mp)
blanchet@35385
   334
      | aux (MType (s, Ms)) = MType (s, map aux Ms)
blanchet@35385
   335
      | aux (MRec z) = MRec z
blanchet@33192
   336
  in aux end
blanchet@33192
   337
blanchet@33192
   338
datatype comp_op = Eq | Leq
blanchet@33192
   339
blanchet@33192
   340
type comp = sign_atom * sign_atom * comp_op * var list
blanchet@33192
   341
type sign_expr = literal list
blanchet@33192
   342
blanchet@35812
   343
type constraint_set = literal list * comp list * sign_expr list
blanchet@33192
   344
blanchet@33192
   345
fun string_for_comp_op Eq = "="
blanchet@33192
   346
  | string_for_comp_op Leq = "\<le>"
blanchet@33192
   347
blanchet@33192
   348
fun string_for_sign_expr [] = "\<bot>"
blanchet@33192
   349
  | string_for_sign_expr lits =
blanchet@33192
   350
    space_implode " \<or> " (map string_for_literal lits)
blanchet@33192
   351
blanchet@33192
   352
fun do_literal _ NONE = NONE
blanchet@33192
   353
  | do_literal (x, sn) (SOME lits) =
blanchet@33192
   354
    case AList.lookup (op =) lits x of
blanchet@33192
   355
      SOME sn' => if sn = sn' then SOME lits else NONE
blanchet@33192
   356
    | NONE => SOME ((x, sn) :: lits)
blanchet@33192
   357
blanchet@33192
   358
fun do_sign_atom_comp Eq [] a1 a2 (accum as (lits, comps)) =
blanchet@33192
   359
    (case (a1, a2) of
blanchet@33192
   360
       (S sn1, S sn2) => if sn1 = sn2 then SOME accum else NONE
blanchet@33192
   361
     | (V x1, S sn2) =>
blanchet@33192
   362
       Option.map (rpair comps) (do_literal (x1, sn2) (SOME lits))
blanchet@33192
   363
     | (V _, V _) => SOME (lits, insert (op =) (a1, a2, Eq, []) comps)
blanchet@33192
   364
     | _ => do_sign_atom_comp Eq [] a2 a1 accum)
blanchet@33192
   365
  | do_sign_atom_comp Leq [] a1 a2 (accum as (lits, comps)) =
blanchet@33192
   366
    (case (a1, a2) of
blanchet@34982
   367
       (_, S Minus) => SOME accum
blanchet@34982
   368
     | (S Plus, _) => SOME accum
blanchet@34982
   369
     | (S Minus, S Plus) => NONE
blanchet@33192
   370
     | (V _, V _) => SOME (lits, insert (op =) (a1, a2, Leq, []) comps)
blanchet@33192
   371
     | _ => do_sign_atom_comp Eq [] a1 a2 accum)
blanchet@35280
   372
  | do_sign_atom_comp cmp xs a1 a2 (lits, comps) =
blanchet@33192
   373
    SOME (lits, insert (op =) (a1, a2, cmp, xs) comps)
blanchet@33192
   374
blanchet@35385
   375
fun do_mtype_comp _ _ _ _ NONE = NONE
blanchet@35385
   376
  | do_mtype_comp _ _ MAlpha MAlpha accum = accum
blanchet@35385
   377
  | do_mtype_comp Eq xs (MFun (M11, a1, M12)) (MFun (M21, a2, M22))
blanchet@33192
   378
                  (SOME accum) =
blanchet@35385
   379
     accum |> do_sign_atom_comp Eq xs a1 a2 |> do_mtype_comp Eq xs M11 M21
blanchet@35385
   380
           |> do_mtype_comp Eq xs M12 M22
blanchet@35385
   381
  | do_mtype_comp Leq xs (MFun (M11, a1, M12)) (MFun (M21, a2, M22))
blanchet@33192
   382
                  (SOME accum) =
blanchet@35385
   383
    (if exists_alpha_sub_mtype M11 then
blanchet@33192
   384
       accum |> do_sign_atom_comp Leq xs a1 a2
blanchet@35385
   385
             |> do_mtype_comp Leq xs M21 M11
blanchet@33192
   386
             |> (case a2 of
blanchet@34982
   387
                   S Minus => I
blanchet@35385
   388
                 | S Plus => do_mtype_comp Leq xs M11 M21
blanchet@35385
   389
                 | V x => do_mtype_comp Leq (x :: xs) M11 M21)
blanchet@33192
   390
     else
blanchet@33192
   391
       SOME accum)
blanchet@35385
   392
    |> do_mtype_comp Leq xs M12 M22
blanchet@35385
   393
  | do_mtype_comp cmp xs (M1 as MPair (M11, M12)) (M2 as MPair (M21, M22))
blanchet@33192
   394
                  accum =
blanchet@35385
   395
    (accum |> fold (uncurry (do_mtype_comp cmp xs)) [(M11, M21), (M12, M22)]
blanchet@33192
   396
     handle Library.UnequalLengths =>
blanchet@35665
   397
            raise MTYPE ("Nitpick_Mono.do_mtype_comp", [M1, M2], []))
blanchet@35385
   398
  | do_mtype_comp _ _ (MType _) (MType _) accum =
blanchet@33192
   399
    accum (* no need to compare them thanks to the cache *)
blanchet@35665
   400
  | do_mtype_comp cmp _ M1 M2 _ =
blanchet@35665
   401
    raise MTYPE ("Nitpick_Mono.do_mtype_comp (" ^ string_for_comp_op cmp ^ ")",
blanchet@35665
   402
                 [M1, M2], [])
blanchet@33192
   403
blanchet@35832
   404
fun add_mtype_comp cmp M1 M2 ((lits, comps, sexps) : constraint_set) =
blanchet@38179
   405
    (trace_msg (fn () => "*** Add " ^ string_for_mtype M1 ^ " " ^
blanchet@38179
   406
                         string_for_comp_op cmp ^ " " ^ string_for_mtype M2);
blanchet@35385
   407
     case do_mtype_comp cmp [] M1 M2 (SOME (lits, comps)) of
blanchet@38179
   408
       NONE => (trace_msg (K "**** Unsolvable"); raise UNSOLVABLE ())
blanchet@35812
   409
     | SOME (lits, comps) => (lits, comps, sexps))
blanchet@33192
   410
blanchet@35385
   411
val add_mtypes_equal = add_mtype_comp Eq
blanchet@35385
   412
val add_is_sub_mtype = add_mtype_comp Leq
blanchet@33192
   413
blanchet@35385
   414
fun do_notin_mtype_fv _ _ _ NONE = NONE
blanchet@35385
   415
  | do_notin_mtype_fv Minus _ MAlpha accum = accum
blanchet@35385
   416
  | do_notin_mtype_fv Plus [] MAlpha _ = NONE
blanchet@35385
   417
  | do_notin_mtype_fv Plus [(x, sn)] MAlpha (SOME (lits, sexps)) =
blanchet@33192
   418
    SOME lits |> do_literal (x, sn) |> Option.map (rpair sexps)
blanchet@35385
   419
  | do_notin_mtype_fv Plus sexp MAlpha (SOME (lits, sexps)) =
blanchet@33192
   420
    SOME (lits, insert (op =) sexp sexps)
blanchet@35385
   421
  | do_notin_mtype_fv sn sexp (MFun (M1, S sn', M2)) accum =
blanchet@34982
   422
    accum |> (if sn' = Plus andalso sn = Plus then
blanchet@35385
   423
                do_notin_mtype_fv Plus sexp M1
blanchet@34982
   424
              else
blanchet@34982
   425
                I)
blanchet@34982
   426
          |> (if sn' = Minus orelse sn = Plus then
blanchet@35385
   427
                do_notin_mtype_fv Minus sexp M1
blanchet@34982
   428
              else
blanchet@34982
   429
                I)
blanchet@35385
   430
          |> do_notin_mtype_fv sn sexp M2
blanchet@35385
   431
  | do_notin_mtype_fv Plus sexp (MFun (M1, V x, M2)) accum =
blanchet@34982
   432
    accum |> (case do_literal (x, Minus) (SOME sexp) of
blanchet@33192
   433
                NONE => I
blanchet@35385
   434
              | SOME sexp' => do_notin_mtype_fv Plus sexp' M1)
blanchet@35385
   435
          |> do_notin_mtype_fv Minus sexp M1
blanchet@35385
   436
          |> do_notin_mtype_fv Plus sexp M2
blanchet@35385
   437
  | do_notin_mtype_fv Minus sexp (MFun (M1, V x, M2)) accum =
blanchet@34982
   438
    accum |> (case do_literal (x, Plus) (SOME sexp) of
blanchet@33192
   439
                NONE => I
blanchet@35385
   440
              | SOME sexp' => do_notin_mtype_fv Plus sexp' M1)
blanchet@35385
   441
          |> do_notin_mtype_fv Minus sexp M2
blanchet@35385
   442
  | do_notin_mtype_fv sn sexp (MPair (M1, M2)) accum =
blanchet@35385
   443
    accum |> fold (do_notin_mtype_fv sn sexp) [M1, M2]
blanchet@35385
   444
  | do_notin_mtype_fv sn sexp (MType (_, Ms)) accum =
blanchet@35385
   445
    accum |> fold (do_notin_mtype_fv sn sexp) Ms
blanchet@35385
   446
  | do_notin_mtype_fv _ _ M _ =
blanchet@35665
   447
    raise MTYPE ("Nitpick_Mono.do_notin_mtype_fv", [M], [])
blanchet@33192
   448
blanchet@35832
   449
fun add_notin_mtype_fv sn M ((lits, comps, sexps) : constraint_set) =
blanchet@38179
   450
    (trace_msg (fn () => "*** Add " ^ string_for_mtype M ^ " is " ^
blanchet@38179
   451
                         (case sn of Minus => "concrete" | Plus => "complete") ^
blanchet@38179
   452
                         ".");
blanchet@35385
   453
     case do_notin_mtype_fv sn [] M (SOME (lits, sexps)) of
blanchet@38179
   454
       NONE => (trace_msg (K "**** Unsolvable"); raise UNSOLVABLE ())
blanchet@35812
   455
     | SOME (lits, sexps) => (lits, comps, sexps))
blanchet@33192
   456
blanchet@35665
   457
val add_mtype_is_concrete = add_notin_mtype_fv Minus
blanchet@35665
   458
val add_mtype_is_complete = add_notin_mtype_fv Plus
blanchet@33192
   459
blanchet@35384
   460
val bool_from_minus = true
blanchet@35384
   461
blanchet@35384
   462
fun bool_from_sign Plus = not bool_from_minus
blanchet@35384
   463
  | bool_from_sign Minus = bool_from_minus
blanchet@35384
   464
fun sign_from_bool b = if b = bool_from_minus then Minus else Plus
blanchet@33192
   465
blanchet@33192
   466
fun prop_for_literal (x, sn) =
blanchet@33192
   467
  (not (bool_from_sign sn) ? PropLogic.Not) (PropLogic.BoolVar x)
blanchet@33192
   468
fun prop_for_sign_atom_eq (S sn', sn) =
blanchet@33192
   469
    if sn = sn' then PropLogic.True else PropLogic.False
blanchet@33192
   470
  | prop_for_sign_atom_eq (V x, sn) = prop_for_literal (x, sn)
blanchet@33192
   471
fun prop_for_sign_expr xs = PropLogic.exists (map prop_for_literal xs)
blanchet@33192
   472
fun prop_for_exists_eq xs sn =
blanchet@33192
   473
  PropLogic.exists (map (fn x => prop_for_literal (x, sn)) xs)
blanchet@33192
   474
fun prop_for_comp (a1, a2, Eq, []) =
blanchet@33192
   475
    PropLogic.SAnd (prop_for_comp (a1, a2, Leq, []),
blanchet@33192
   476
                    prop_for_comp (a2, a1, Leq, []))
blanchet@33192
   477
  | prop_for_comp (a1, a2, Leq, []) =
blanchet@34982
   478
    PropLogic.SOr (prop_for_sign_atom_eq (a1, Plus),
blanchet@34982
   479
                   prop_for_sign_atom_eq (a2, Minus))
blanchet@33192
   480
  | prop_for_comp (a1, a2, cmp, xs) =
blanchet@34982
   481
    PropLogic.SOr (prop_for_exists_eq xs Minus, prop_for_comp (a1, a2, cmp, []))
blanchet@33192
   482
blanchet@34123
   483
fun literals_from_assignments max_var assigns lits =
blanchet@33192
   484
  fold (fn x => fn accum =>
blanchet@33192
   485
           if AList.defined (op =) lits x then
blanchet@33192
   486
             accum
blanchet@34123
   487
           else case assigns x of
blanchet@33192
   488
             SOME b => (x, sign_from_bool b) :: accum
blanchet@33192
   489
           | NONE => accum) (max_var downto 1) lits
blanchet@33192
   490
blanchet@33192
   491
fun string_for_comp (a1, a2, cmp, xs) =
blanchet@33192
   492
  string_for_sign_atom a1 ^ " " ^ string_for_comp_op cmp ^
blanchet@33192
   493
  subscript_string_for_vars " \<and> " xs ^ " " ^ string_for_sign_atom a2
blanchet@33192
   494
blanchet@33192
   495
fun print_problem lits comps sexps =
blanchet@38179
   496
  trace_msg (fn () => "*** Problem:\n" ^
blanchet@38179
   497
                      cat_lines (map string_for_literal lits @
blanchet@38179
   498
                                 map string_for_comp comps @
blanchet@38179
   499
                                 map string_for_sign_expr sexps))
blanchet@33192
   500
blanchet@33192
   501
fun print_solution lits =
blanchet@34982
   502
  let val (pos, neg) = List.partition (curry (op =) Plus o snd) lits in
blanchet@38179
   503
    trace_msg (fn () => "*** Solution:\n" ^
blanchet@38179
   504
                        "+: " ^ commas (map (string_for_var o fst) pos) ^ "\n" ^
blanchet@38179
   505
                        "-: " ^ commas (map (string_for_var o fst) neg))
blanchet@33192
   506
  end
blanchet@33192
   507
blanchet@35812
   508
fun solve max_var (lits, comps, sexps) =
blanchet@33192
   509
    let
blanchet@35386
   510
      fun do_assigns assigns =
blanchet@35386
   511
        SOME (literals_from_assignments max_var assigns lits
blanchet@35386
   512
              |> tap print_solution)
blanchet@33192
   513
      val _ = print_problem lits comps sexps
blanchet@33192
   514
      val prop = PropLogic.all (map prop_for_literal lits @
blanchet@33192
   515
                                map prop_for_comp comps @
blanchet@33192
   516
                                map prop_for_sign_expr sexps)
blanchet@35386
   517
      val default_val = bool_from_sign Minus
blanchet@33192
   518
    in
blanchet@35386
   519
      if PropLogic.eval (K default_val) prop then
blanchet@35386
   520
        do_assigns (K (SOME default_val))
blanchet@35386
   521
      else
blanchet@35386
   522
        let
blanchet@35386
   523
          (* use the first ML solver (to avoid startup overhead) *)
blanchet@35386
   524
          val solvers = !SatSolver.solvers
blanchet@35386
   525
                        |> filter (member (op =) ["dptsat", "dpll"] o fst)
blanchet@35386
   526
        in
blanchet@35386
   527
          case snd (hd solvers) prop of
blanchet@35386
   528
            SatSolver.SATISFIABLE assigns => do_assigns assigns
blanchet@35386
   529
          | _ => NONE
blanchet@35386
   530
        end
blanchet@33192
   531
    end
blanchet@33192
   532
blanchet@35385
   533
type mtype_schema = mtyp * constraint_set
blanchet@35385
   534
type mtype_context =
blanchet@35665
   535
  {bound_Ts: typ list,
blanchet@35665
   536
   bound_Ms: mtyp list,
blanchet@35385
   537
   frees: (styp * mtyp) list,
blanchet@35385
   538
   consts: (styp * mtyp) list}
blanchet@33192
   539
blanchet@35385
   540
type accumulator = mtype_context * constraint_set
blanchet@33192
   541
blanchet@35665
   542
val initial_gamma = {bound_Ts = [], bound_Ms = [], frees = [], consts = []}
blanchet@33192
   543
blanchet@35665
   544
fun push_bound T M {bound_Ts, bound_Ms, frees, consts} =
blanchet@35665
   545
  {bound_Ts = T :: bound_Ts, bound_Ms = M :: bound_Ms, frees = frees,
blanchet@35665
   546
   consts = consts}
blanchet@35665
   547
fun pop_bound {bound_Ts, bound_Ms, frees, consts} =
blanchet@35665
   548
  {bound_Ts = tl bound_Ts, bound_Ms = tl bound_Ms, frees = frees,
blanchet@35665
   549
   consts = consts}
blanchet@35665
   550
  handle List.Empty => initial_gamma (* FIXME: needed? *)
blanchet@33192
   551
blanchet@39359
   552
fun consider_term (mdata as {hol_ctxt = {thy, ctxt, stds, ...}, alpha_T,
blanchet@39359
   553
                             max_fresh, ...}) =
blanchet@33192
   554
  let
blanchet@37476
   555
    fun is_enough_eta_expanded t =
blanchet@37476
   556
      case strip_comb t of
blanchet@39359
   557
        (Const x, ts) => the_default 0 (arity_of_built_in_const thy stds x)
blanchet@37476
   558
        <= length ts
blanchet@37476
   559
      | _ => true
blanchet@35672
   560
    val mtype_for = fresh_mtype_for_type mdata false
blanchet@35665
   561
    fun plus_set_mtype_for_dom M =
blanchet@35385
   562
      MFun (M, S (if exists_alpha_sub_mtype M then Plus else Minus), bool_M)
blanchet@35385
   563
    fun do_all T (gamma, cset) =
blanchet@33192
   564
      let
blanchet@35385
   565
        val abs_M = mtype_for (domain_type (domain_type T))
blanchet@35386
   566
        val body_M = mtype_for (body_type T)
blanchet@33192
   567
      in
blanchet@35385
   568
        (MFun (MFun (abs_M, S Minus, body_M), S Minus, body_M),
blanchet@35665
   569
         (gamma, cset |> add_mtype_is_complete abs_M))
blanchet@33192
   570
      end
blanchet@33192
   571
    fun do_equals T (gamma, cset) =
blanchet@35385
   572
      let val M = mtype_for (domain_type T) in
blanchet@35385
   573
        (MFun (M, S Minus, MFun (M, V (Unsynchronized.inc max_fresh),
blanchet@35385
   574
                                 mtype_for (nth_range_type 2 T))),
blanchet@35665
   575
         (gamma, cset |> add_mtype_is_concrete M))
blanchet@33192
   576
      end
blanchet@33192
   577
    fun do_robust_set_operation T (gamma, cset) =
blanchet@33192
   578
      let
blanchet@33192
   579
        val set_T = domain_type T
blanchet@35385
   580
        val M1 = mtype_for set_T
blanchet@35385
   581
        val M2 = mtype_for set_T
blanchet@35385
   582
        val M3 = mtype_for set_T
blanchet@33192
   583
      in
blanchet@35385
   584
        (MFun (M1, S Minus, MFun (M2, S Minus, M3)),
blanchet@35385
   585
         (gamma, cset |> add_is_sub_mtype M1 M3 |> add_is_sub_mtype M2 M3))
blanchet@33192
   586
      end
blanchet@33192
   587
    fun do_fragile_set_operation T (gamma, cset) =
blanchet@33192
   588
      let
blanchet@33192
   589
        val set_T = domain_type T
blanchet@35385
   590
        val set_M = mtype_for set_T
blanchet@35665
   591
        fun custom_mtype_for (T as Type (@{type_name fun}, [T1, T2])) =
blanchet@35385
   592
            if T = set_T then set_M
blanchet@35385
   593
            else MFun (custom_mtype_for T1, S Minus, custom_mtype_for T2)
blanchet@35385
   594
          | custom_mtype_for T = mtype_for T
blanchet@33192
   595
      in
blanchet@35665
   596
        (custom_mtype_for T, (gamma, cset |> add_mtype_is_concrete set_M))
blanchet@33192
   597
      end
blanchet@33192
   598
    fun do_pair_constr T accum =
blanchet@35385
   599
      case mtype_for (nth_range_type 2 T) of
blanchet@35385
   600
        M as MPair (a_M, b_M) =>
blanchet@35385
   601
        (MFun (a_M, S Minus, MFun (b_M, S Minus, M)), accum)
blanchet@35665
   602
      | M => raise MTYPE ("Nitpick_Mono.consider_term.do_pair_constr", [M], [])
blanchet@33192
   603
    fun do_nth_pair_sel n T =
blanchet@35385
   604
      case mtype_for (domain_type T) of
blanchet@35385
   605
        M as MPair (a_M, b_M) =>
blanchet@35385
   606
        pair (MFun (M, S Minus, if n = 0 then a_M else b_M))
blanchet@35665
   607
      | M => raise MTYPE ("Nitpick_Mono.consider_term.do_nth_pair_sel", [M], [])
blanchet@35385
   608
    fun do_bounded_quantifier t0 abs_s abs_T connective_t bound_t body_t accum =
blanchet@33192
   609
      let
blanchet@35385
   610
        val abs_M = mtype_for abs_T
blanchet@35665
   611
        val (bound_m, accum) =
blanchet@35665
   612
          accum |>> push_bound abs_T abs_M |> do_term bound_t
blanchet@35665
   613
        val expected_bound_M = plus_set_mtype_for_dom abs_M
blanchet@35385
   614
        val (body_m, accum) =
blanchet@35385
   615
          accum ||> add_mtypes_equal expected_bound_M (mtype_of_mterm bound_m)
blanchet@35385
   616
                |> do_term body_t ||> apfst pop_bound
blanchet@35385
   617
        val bound_M = mtype_of_mterm bound_m
blanchet@39345
   618
        val (M1, a, _) = dest_MFun bound_M
blanchet@33192
   619
      in
blanchet@35386
   620
        (MApp (MRaw (t0, MFun (bound_M, S Minus, bool_M)),
blanchet@35385
   621
               MAbs (abs_s, abs_T, M1, a,
blanchet@35386
   622
                     MApp (MApp (MRaw (connective_t,
blanchet@35386
   623
                                       mtype_for (fastype_of connective_t)),
blanchet@35386
   624
                                 MApp (bound_m, MRaw (Bound 0, M1))),
blanchet@35385
   625
                           body_m))), accum)
blanchet@33192
   626
      end
blanchet@39345
   627
    and do_term t (accum as ({bound_Ts, bound_Ms, frees, consts}, cset)) =
blanchet@38179
   628
        (trace_msg (fn () => "  \<Gamma> \<turnstile> " ^
blanchet@38179
   629
                             Syntax.string_of_term ctxt t ^ " : _?");
blanchet@37704
   630
         case t of
blanchet@33192
   631
           Const (x as (s, T)) =>
blanchet@33192
   632
           (case AList.lookup (op =) consts x of
blanchet@35385
   633
              SOME M => (M, accum)
blanchet@33192
   634
            | NONE =>
blanchet@33192
   635
              if not (could_exist_alpha_subtype alpha_T T) then
blanchet@35385
   636
                (mtype_for T, accum)
blanchet@33192
   637
              else case s of
blanchet@35385
   638
                @{const_name all} => do_all T accum
blanchet@33192
   639
              | @{const_name "=="} => do_equals T accum
blanchet@35385
   640
              | @{const_name All} => do_all T accum
blanchet@35385
   641
              | @{const_name Ex} =>
blanchet@35386
   642
                let val set_T = domain_type T in
blanchet@35386
   643
                  do_term (Abs (Name.uu, set_T,
blanchet@35386
   644
                                @{const Not} $ (HOLogic.mk_eq
blanchet@35386
   645
                                    (Abs (Name.uu, domain_type set_T,
blanchet@35386
   646
                                          @{const False}),
blanchet@35386
   647
                                     Bound 0)))) accum
blanchet@35386
   648
                  |>> mtype_of_mterm
blanchet@35386
   649
                end
haftmann@38864
   650
              | @{const_name HOL.eq} => do_equals T accum
blanchet@37476
   651
              | @{const_name The} =>
blanchet@38179
   652
                (trace_msg (K "*** The"); raise UNSOLVABLE ())
blanchet@37476
   653
              | @{const_name Eps} =>
blanchet@38179
   654
                (trace_msg (K "*** Eps"); raise UNSOLVABLE ())
blanchet@33192
   655
              | @{const_name If} =>
blanchet@33192
   656
                do_robust_set_operation (range_type T) accum
blanchet@35385
   657
                |>> curry3 MFun bool_M (S Minus)
blanchet@33192
   658
              | @{const_name Pair} => do_pair_constr T accum
blanchet@33192
   659
              | @{const_name fst} => do_nth_pair_sel 0 T accum
blanchet@39316
   660
              | @{const_name snd} => do_nth_pair_sel 1 T accum
blanchet@33192
   661
              | @{const_name Id} =>
blanchet@35385
   662
                (MFun (mtype_for (domain_type T), S Minus, bool_M), accum)
blanchet@33192
   663
              | @{const_name converse} =>
blanchet@33192
   664
                let
blanchet@33192
   665
                  val x = Unsynchronized.inc max_fresh
blanchet@35385
   666
                  fun mtype_for_set T =
blanchet@35385
   667
                    MFun (mtype_for (domain_type T), V x, bool_M)
blanchet@35385
   668
                  val ab_set_M = domain_type T |> mtype_for_set
blanchet@35385
   669
                  val ba_set_M = range_type T |> mtype_for_set
blanchet@35385
   670
                in (MFun (ab_set_M, S Minus, ba_set_M), accum) end
blanchet@33192
   671
              | @{const_name trancl} => do_fragile_set_operation T accum
blanchet@33192
   672
              | @{const_name rel_comp} =>
blanchet@33192
   673
                let
blanchet@33192
   674
                  val x = Unsynchronized.inc max_fresh
blanchet@35385
   675
                  fun mtype_for_set T =
blanchet@35385
   676
                    MFun (mtype_for (domain_type T), V x, bool_M)
blanchet@35385
   677
                  val bc_set_M = domain_type T |> mtype_for_set
blanchet@35385
   678
                  val ab_set_M = domain_type (range_type T) |> mtype_for_set
blanchet@35385
   679
                  val ac_set_M = nth_range_type 2 T |> mtype_for_set
blanchet@33192
   680
                in
blanchet@35385
   681
                  (MFun (bc_set_M, S Minus, MFun (ab_set_M, S Minus, ac_set_M)),
blanchet@33192
   682
                   accum)
blanchet@33192
   683
                end
blanchet@33192
   684
              | @{const_name image} =>
blanchet@33192
   685
                let
blanchet@35385
   686
                  val a_M = mtype_for (domain_type (domain_type T))
blanchet@35385
   687
                  val b_M = mtype_for (range_type (domain_type T))
blanchet@33192
   688
                in
blanchet@35385
   689
                  (MFun (MFun (a_M, S Minus, b_M), S Minus,
blanchet@35665
   690
                         MFun (plus_set_mtype_for_dom a_M, S Minus,
blanchet@35665
   691
                               plus_set_mtype_for_dom b_M)), accum)
blanchet@33192
   692
                end
blanchet@35672
   693
              | @{const_name finite} =>
blanchet@35672
   694
                let val M1 = mtype_for (domain_type (domain_type T)) in
blanchet@35672
   695
                  (MFun (plus_set_mtype_for_dom M1, S Minus, bool_M), accum)
blanchet@35672
   696
                end
blanchet@33192
   697
              | @{const_name Sigma} =>
blanchet@33192
   698
                let
blanchet@33192
   699
                  val x = Unsynchronized.inc max_fresh
blanchet@35385
   700
                  fun mtype_for_set T =
blanchet@35385
   701
                    MFun (mtype_for (domain_type T), V x, bool_M)
blanchet@33192
   702
                  val a_set_T = domain_type T
blanchet@35385
   703
                  val a_M = mtype_for (domain_type a_set_T)
blanchet@35385
   704
                  val b_set_M = mtype_for_set (range_type (domain_type
blanchet@33192
   705
                                                               (range_type T)))
blanchet@35385
   706
                  val a_set_M = mtype_for_set a_set_T
blanchet@35385
   707
                  val a_to_b_set_M = MFun (a_M, S Minus, b_set_M)
blanchet@35385
   708
                  val ab_set_M = mtype_for_set (nth_range_type 2 T)
blanchet@33192
   709
                in
blanchet@35385
   710
                  (MFun (a_set_M, S Minus,
blanchet@35385
   711
                         MFun (a_to_b_set_M, S Minus, ab_set_M)), accum)
blanchet@33192
   712
                end
blanchet@35220
   713
              | _ =>
blanchet@39360
   714
                if s = @{const_name safe_The} then
blanchet@35671
   715
                  let
blanchet@35671
   716
                    val a_set_M = mtype_for (domain_type T)
blanchet@35671
   717
                    val a_M = dest_MFun a_set_M |> #1
blanchet@35671
   718
                  in (MFun (a_set_M, S Minus, a_M), accum) end
blanchet@35220
   719
                else if s = @{const_name ord_class.less_eq} andalso
blanchet@35220
   720
                        is_set_type (domain_type T) then
blanchet@35220
   721
                  do_fragile_set_operation T accum
blanchet@35220
   722
                else if is_sel s then
blanchet@35665
   723
                  (mtype_for_sel mdata x, accum)
blanchet@37256
   724
                else if is_constr ctxt stds x then
blanchet@35385
   725
                  (mtype_for_constr mdata x, accum)
blanchet@39359
   726
                else if is_built_in_const thy stds x then
blanchet@35672
   727
                  (fresh_mtype_for_type mdata true T, accum)
blanchet@35220
   728
                else
blanchet@35385
   729
                  let val M = mtype_for T in
blanchet@35665
   730
                    (M, ({bound_Ts = bound_Ts, bound_Ms = bound_Ms,
blanchet@35665
   731
                          frees = frees, consts = (x, M) :: consts}, cset))
blanchet@35386
   732
                  end) |>> curry MRaw t
blanchet@33192
   733
         | Free (x as (_, T)) =>
blanchet@33192
   734
           (case AList.lookup (op =) frees x of
blanchet@35385
   735
              SOME M => (M, accum)
blanchet@33192
   736
            | NONE =>
blanchet@35385
   737
              let val M = mtype_for T in
blanchet@35665
   738
                (M, ({bound_Ts = bound_Ts, bound_Ms = bound_Ms,
blanchet@35665
   739
                      frees = (x, M) :: frees, consts = consts}, cset))
blanchet@35386
   740
              end) |>> curry MRaw t
blanchet@38179
   741
         | Var _ => (trace_msg (K "*** Var"); raise UNSOLVABLE ())
blanchet@35665
   742
         | Bound j => (MRaw (t, nth bound_Ms j), accum)
blanchet@35385
   743
         | Abs (s, T, t') =>
blanchet@35665
   744
           (case fin_fun_body T (fastype_of1 (T :: bound_Ts, t')) t' of
blanchet@35665
   745
              SOME t' =>
blanchet@35665
   746
              let
blanchet@35665
   747
                val M = mtype_for T
blanchet@35665
   748
                val a = V (Unsynchronized.inc max_fresh)
blanchet@35665
   749
                val (m', accum) = do_term t' (accum |>> push_bound T M)
blanchet@35665
   750
              in (MAbs (s, T, M, a, m'), accum |>> pop_bound) end
blanchet@35665
   751
            | NONE =>
blanchet@35665
   752
              ((case t' of
blanchet@35665
   753
                  t1' $ Bound 0 =>
blanchet@37476
   754
                  if not (loose_bvar1 (t1', 0)) andalso
blanchet@37476
   755
                     is_enough_eta_expanded t1' then
blanchet@35665
   756
                    do_term (incr_boundvars ~1 t1') accum
blanchet@35665
   757
                  else
blanchet@35665
   758
                    raise SAME ()
haftmann@38864
   759
                | (t11 as Const (@{const_name HOL.eq}, _)) $ Bound 0 $ t13 =>
blanchet@37476
   760
                  if not (loose_bvar1 (t13, 0)) then
blanchet@37476
   761
                    do_term (incr_boundvars ~1 (t11 $ t13)) accum
blanchet@37476
   762
                  else
blanchet@37476
   763
                    raise SAME ()
blanchet@35665
   764
                | _ => raise SAME ())
blanchet@35665
   765
               handle SAME () =>
blanchet@35665
   766
                      let
blanchet@35665
   767
                        val M = mtype_for T
blanchet@35665
   768
                        val (m', accum) = do_term t' (accum |>> push_bound T M)
blanchet@35665
   769
                      in
blanchet@35665
   770
                        (MAbs (s, T, M, S Minus, m'), accum |>> pop_bound)
blanchet@35665
   771
                      end))
blanchet@35385
   772
         | (t0 as Const (@{const_name All}, _))
haftmann@38786
   773
           $ Abs (s', T', (t10 as @{const HOL.implies}) $ (t11 $ Bound 0) $ t12) =>
blanchet@35385
   774
           do_bounded_quantifier t0 s' T' t10 t11 t12 accum
blanchet@35385
   775
         | (t0 as Const (@{const_name Ex}, _))
haftmann@38795
   776
           $ Abs (s', T', (t10 as @{const HOL.conj}) $ (t11 $ Bound 0) $ t12) =>
blanchet@35385
   777
           do_bounded_quantifier t0 s' T' t10 t11 t12 accum
blanchet@33192
   778
         | Const (@{const_name Let}, _) $ t1 $ t2 =>
blanchet@33192
   779
           do_term (betapply (t2, t1)) accum
blanchet@33192
   780
         | t1 $ t2 =>
blanchet@33192
   781
           let
blanchet@35385
   782
             val (m1, accum) = do_term t1 accum
blanchet@35385
   783
             val (m2, accum) = do_term t2 accum
blanchet@33192
   784
           in
blanchet@35812
   785
             let
blanchet@35812
   786
               val M11 = mtype_of_mterm m1 |> dest_MFun |> #1
blanchet@35812
   787
               val M2 = mtype_of_mterm m2
blanchet@35812
   788
             in (MApp (m1, m2), accum ||> add_is_sub_mtype M2 M11) end
blanchet@33192
   789
           end)
blanchet@38179
   790
        |> tap (fn (m, _) => trace_msg (fn () => "  \<Gamma> \<turnstile> " ^
blanchet@38179
   791
                                                 string_for_mterm ctxt m))
blanchet@33192
   792
  in do_term end
blanchet@33192
   793
blanchet@35665
   794
fun force_minus_funs 0 _ = I
blanchet@35665
   795
  | force_minus_funs n (M as MFun (M1, _, M2)) =
blanchet@35665
   796
    add_mtypes_equal M (MFun (M1, S Minus, M2))
blanchet@35665
   797
    #> force_minus_funs (n - 1) M2
blanchet@35665
   798
  | force_minus_funs _ M =
blanchet@35665
   799
    raise MTYPE ("Nitpick_Mono.force_minus_funs", [M], [])
blanchet@35665
   800
fun consider_general_equals mdata def (x as (_, T)) t1 t2 accum =
blanchet@35386
   801
  let
blanchet@35386
   802
    val (m1, accum) = consider_term mdata t1 accum
blanchet@35386
   803
    val (m2, accum) = consider_term mdata t2 accum
blanchet@35386
   804
    val M1 = mtype_of_mterm m1
blanchet@35386
   805
    val M2 = mtype_of_mterm m2
blanchet@35665
   806
    val accum = accum ||> add_mtypes_equal M1 M2
blanchet@35672
   807
    val body_M = fresh_mtype_for_type mdata false (nth_range_type 2 T)
blanchet@35665
   808
    val m = MApp (MApp (MRaw (Const x,
blanchet@35665
   809
                MFun (M1, S Minus, MFun (M2, S Minus, body_M))), m1), m2)
blanchet@35386
   810
  in
blanchet@35665
   811
    (m, if def then
blanchet@35665
   812
          let val (head_m, arg_ms) = strip_mcomb m1 in
blanchet@35665
   813
            accum ||> force_minus_funs (length arg_ms) (mtype_of_mterm head_m)
blanchet@35665
   814
          end
blanchet@35665
   815
        else
blanchet@35665
   816
          accum)
blanchet@35386
   817
  end
blanchet@35386
   818
blanchet@35385
   819
fun consider_general_formula (mdata as {hol_ctxt = {ctxt, ...}, ...}) =
blanchet@33192
   820
  let
blanchet@35672
   821
    val mtype_for = fresh_mtype_for_type mdata false
blanchet@35386
   822
    val do_term = consider_term mdata
blanchet@35812
   823
    fun do_formula sn t accum =
blanchet@33192
   824
        let
blanchet@35386
   825
          fun do_quantifier (quant_x as (quant_s, _)) abs_s abs_T body_t =
blanchet@33192
   826
            let
blanchet@35385
   827
              val abs_M = mtype_for abs_T
blanchet@34982
   828
              val side_cond = ((sn = Minus) = (quant_s = @{const_name Ex}))
blanchet@35386
   829
              val (body_m, accum) =
blanchet@35665
   830
                accum ||> side_cond ? add_mtype_is_complete abs_M
blanchet@35665
   831
                      |>> push_bound abs_T abs_M |> do_formula sn body_t
blanchet@35386
   832
              val body_M = mtype_of_mterm body_m
blanchet@33192
   833
            in
blanchet@35665
   834
              (MApp (MRaw (Const quant_x,
blanchet@35665
   835
                           MFun (MFun (abs_M, S Minus, body_M), S Minus,
blanchet@35665
   836
                                 body_M)),
blanchet@35386
   837
                     MAbs (abs_s, abs_T, abs_M, S Minus, body_m)),
blanchet@35386
   838
               accum |>> pop_bound)
blanchet@33192
   839
            end
blanchet@35386
   840
          fun do_equals x t1 t2 =
blanchet@33192
   841
            case sn of
blanchet@35386
   842
              Plus => do_term t accum
blanchet@35665
   843
            | Minus => consider_general_equals mdata false x t1 t2 accum
blanchet@33192
   844
        in
blanchet@38179
   845
          (trace_msg (fn () => "  \<Gamma> \<turnstile> " ^
blanchet@38179
   846
                               Syntax.string_of_term ctxt t ^ " : o\<^sup>" ^
blanchet@38179
   847
                               string_for_sign sn ^ "?");
blanchet@37704
   848
           case t of
blanchet@37704
   849
             Const (x as (@{const_name all}, _)) $ Abs (s1, T1, t1) =>
blanchet@37704
   850
             do_quantifier x s1 T1 t1
blanchet@37704
   851
           | Const (x as (@{const_name "=="}, _)) $ t1 $ t2 => do_equals x t1 t2
blanchet@37704
   852
           | @{const Trueprop} $ t1 =>
blanchet@37704
   853
             let val (m1, accum) = do_formula sn t1 accum in
blanchet@37704
   854
               (MApp (MRaw (@{const Trueprop}, mtype_for (bool_T --> prop_T)),
blanchet@37704
   855
                      m1), accum)
blanchet@37704
   856
             end
blanchet@37704
   857
           | @{const Not} $ t1 =>
blanchet@37704
   858
             let val (m1, accum) = do_formula (negate sn) t1 accum in
blanchet@37704
   859
               (MApp (MRaw (@{const Not}, mtype_for (bool_T --> bool_T)), m1),
blanchet@37704
   860
                accum)
blanchet@37704
   861
             end
blanchet@37704
   862
           | Const (x as (@{const_name All}, _)) $ Abs (s1, T1, t1) =>
blanchet@37704
   863
             do_quantifier x s1 T1 t1
blanchet@39345
   864
           | Const (x0 as (@{const_name Ex}, T0))
blanchet@37704
   865
             $ (t1 as Abs (s1, T1, t1')) =>
blanchet@37704
   866
             (case sn of
blanchet@37704
   867
                Plus => do_quantifier x0 s1 T1 t1'
blanchet@37704
   868
              | Minus =>
blanchet@37704
   869
                (* FIXME: Move elsewhere *)
blanchet@37704
   870
                do_term (@{const Not}
blanchet@37704
   871
                         $ (HOLogic.eq_const (domain_type T0) $ t1
blanchet@37704
   872
                            $ Abs (Name.uu, T1, @{const False}))) accum)
haftmann@38864
   873
           | Const (x as (@{const_name HOL.eq}, _)) $ t1 $ t2 =>
blanchet@37704
   874
             do_equals x t1 t2
blanchet@37704
   875
           | Const (@{const_name Let}, _) $ t1 $ t2 =>
blanchet@37704
   876
             do_formula sn (betapply (t2, t1)) accum
blanchet@37704
   877
           | (t0 as Const (s0, _)) $ t1 $ t2 =>
blanchet@38199
   878
             if s0 = @{const_name "==>"} orelse
blanchet@38199
   879
                s0 = @{const_name Pure.conjunction} orelse
haftmann@38795
   880
                s0 = @{const_name HOL.conj} orelse
haftmann@38795
   881
                s0 = @{const_name HOL.disj} orelse
haftmann@38786
   882
                s0 = @{const_name HOL.implies} then
blanchet@37704
   883
               let
blanchet@37704
   884
                 val impl = (s0 = @{const_name "==>"} orelse
haftmann@38786
   885
                             s0 = @{const_name HOL.implies})
blanchet@37704
   886
                 val (m1, accum) = do_formula (sn |> impl ? negate) t1 accum
blanchet@37704
   887
                 val (m2, accum) = do_formula sn t2 accum
blanchet@37704
   888
               in
blanchet@37704
   889
                 (MApp (MApp (MRaw (t0, mtype_for (fastype_of t0)), m1), m2),
blanchet@37704
   890
                  accum)
blanchet@39316
   891
               end
blanchet@37704
   892
             else
blanchet@37704
   893
               do_term t accum
blanchet@37704
   894
           | _ => do_term t accum)
blanchet@33192
   895
        end
blanchet@35386
   896
        |> tap (fn (m, _) =>
blanchet@38179
   897
                   trace_msg (fn () => "\<Gamma> \<turnstile> " ^
blanchet@38179
   898
                                       string_for_mterm ctxt m ^ " : o\<^sup>" ^
blanchet@38179
   899
                                       string_for_sign sn))
blanchet@33192
   900
  in do_formula end
blanchet@33192
   901
blanchet@33192
   902
(* The harmless axiom optimization below is somewhat too aggressive in the face
blanchet@33192
   903
   of (rather peculiar) user-defined axioms. *)
blanchet@33192
   904
val harmless_consts =
blanchet@33192
   905
  [@{const_name ord_class.less}, @{const_name ord_class.less_eq}]
blanchet@33192
   906
val bounteous_consts = [@{const_name bisim}]
blanchet@33192
   907
blanchet@35665
   908
fun is_harmless_axiom ({no_harmless = true, ...} : mdata) _ = false
blanchet@39359
   909
  | is_harmless_axiom {hol_ctxt = {thy, stds, ...}, ...} t =
blanchet@35665
   910
    Term.add_consts t []
blanchet@39359
   911
    |> filter_out (is_built_in_const thy stds)
blanchet@35665
   912
    |> (forall (member (op =) harmless_consts o original_name o fst) orf
blanchet@35665
   913
        exists (member (op =) bounteous_consts o fst))
blanchet@33192
   914
blanchet@35665
   915
fun consider_nondefinitional_axiom mdata t =
blanchet@35665
   916
  if is_harmless_axiom mdata t then pair (MRaw (t, dummy_M))
blanchet@35386
   917
  else consider_general_formula mdata Plus t
blanchet@33192
   918
blanchet@37256
   919
fun consider_definitional_axiom (mdata as {hol_ctxt = {ctxt, ...}, ...}) t =
blanchet@37256
   920
  if not (is_constr_pattern_formula ctxt t) then
blanchet@35386
   921
    consider_nondefinitional_axiom mdata t
blanchet@35665
   922
  else if is_harmless_axiom mdata t then
blanchet@35386
   923
    pair (MRaw (t, dummy_M))
blanchet@33192
   924
  else
blanchet@33192
   925
    let
blanchet@35672
   926
      val mtype_for = fresh_mtype_for_type mdata false
blanchet@35386
   927
      val do_term = consider_term mdata
blanchet@35386
   928
      fun do_all quant_t abs_s abs_T body_t accum =
blanchet@35386
   929
        let
blanchet@35386
   930
          val abs_M = mtype_for abs_T
blanchet@35386
   931
          val (body_m, accum) =
blanchet@35665
   932
            accum |>> push_bound abs_T abs_M |> do_formula body_t
blanchet@35386
   933
          val body_M = mtype_of_mterm body_m
blanchet@35386
   934
        in
blanchet@35665
   935
          (MApp (MRaw (quant_t,
blanchet@35665
   936
                       MFun (MFun (abs_M, S Minus, body_M), S Minus, body_M)),
blanchet@35386
   937
                 MAbs (abs_s, abs_T, abs_M, S Minus, body_m)),
blanchet@35386
   938
           accum |>> pop_bound)
blanchet@33192
   939
        end
blanchet@35386
   940
      and do_conjunction t0 t1 t2 accum =
blanchet@33192
   941
        let
blanchet@35386
   942
          val (m1, accum) = do_formula t1 accum
blanchet@35386
   943
          val (m2, accum) = do_formula t2 accum
blanchet@35386
   944
        in
blanchet@35386
   945
          (MApp (MApp (MRaw (t0, mtype_for (fastype_of t0)), m1), m2), accum)
blanchet@35386
   946
        end
blanchet@35386
   947
      and do_implies t0 t1 t2 accum =
blanchet@35386
   948
        let
blanchet@35386
   949
          val (m1, accum) = do_term t1 accum
blanchet@35386
   950
          val (m2, accum) = do_formula t2 accum
blanchet@35386
   951
        in
blanchet@35386
   952
          (MApp (MApp (MRaw (t0, mtype_for (fastype_of t0)), m1), m2), accum)
blanchet@35386
   953
        end
blanchet@35812
   954
      and do_formula t accum =
blanchet@33192
   955
          case t of
blanchet@35386
   956
            (t0 as Const (@{const_name all}, _)) $ Abs (s1, T1, t1) =>
blanchet@35386
   957
            do_all t0 s1 T1 t1 accum
blanchet@35665
   958
          | @{const Trueprop} $ t1 =>
blanchet@35665
   959
            let val (m1, accum) = do_formula t1 accum in
blanchet@35665
   960
              (MApp (MRaw (@{const Trueprop}, mtype_for (bool_T --> prop_T)),
blanchet@35665
   961
                     m1), accum)
blanchet@35665
   962
            end
blanchet@35386
   963
          | Const (x as (@{const_name "=="}, _)) $ t1 $ t2 =>
blanchet@35665
   964
            consider_general_equals mdata true x t1 t2 accum
blanchet@35386
   965
          | (t0 as @{const "==>"}) $ t1 $ t2 => do_implies t0 t1 t2 accum
blanchet@35386
   966
          | (t0 as @{const Pure.conjunction}) $ t1 $ t2 =>
blanchet@35386
   967
            do_conjunction t0 t1 t2 accum
blanchet@35386
   968
          | (t0 as Const (@{const_name All}, _)) $ Abs (s0, T1, t1) =>
blanchet@35386
   969
            do_all t0 s0 T1 t1 accum
haftmann@38864
   970
          | Const (x as (@{const_name HOL.eq}, _)) $ t1 $ t2 =>
blanchet@35665
   971
            consider_general_equals mdata true x t1 t2 accum
haftmann@38795
   972
          | (t0 as @{const HOL.conj}) $ t1 $ t2 => do_conjunction t0 t1 t2 accum
haftmann@38786
   973
          | (t0 as @{const HOL.implies}) $ t1 $ t2 => do_implies t0 t1 t2 accum
blanchet@33232
   974
          | _ => raise TERM ("Nitpick_Mono.consider_definitional_axiom.\
blanchet@33192
   975
                             \do_formula", [t])
blanchet@33192
   976
    in do_formula t end
blanchet@33192
   977
blanchet@35385
   978
fun string_for_mtype_of_term ctxt lits t M =
blanchet@35665
   979
  Syntax.string_of_term ctxt t ^ " : " ^ string_for_mtype (resolve_mtype lits M)
blanchet@33192
   980
blanchet@35385
   981
fun print_mtype_context ctxt lits ({frees, consts, ...} : mtype_context) =
blanchet@38179
   982
  trace_msg (fn () =>
blanchet@37476
   983
      map (fn (x, M) => string_for_mtype_of_term ctxt lits (Free x) M) frees @
blanchet@37476
   984
      map (fn (x, M) => string_for_mtype_of_term ctxt lits (Const x) M) consts
blanchet@37476
   985
      |> cat_lines)
blanchet@33192
   986
blanchet@35665
   987
fun amass f t (ms, accum) =
blanchet@35386
   988
  let val (m, accum) = f t accum in (m :: ms, accum) end
blanchet@35386
   989
blanchet@35665
   990
fun infer which no_harmless (hol_ctxt as {ctxt, ...}) binarize alpha_T
blanchet@35665
   991
          (nondef_ts, def_ts) =
blanchet@33192
   992
  let
blanchet@38179
   993
    val _ = trace_msg (fn () => "****** " ^ which ^ " analysis: " ^
blanchet@38179
   994
                                string_for_mtype MAlpha ^ " is " ^
blanchet@38179
   995
                                Syntax.string_of_typ ctxt alpha_T)
blanchet@35665
   996
    val mdata as {max_fresh, constr_mcache, ...} =
blanchet@35665
   997
      initial_mdata hol_ctxt binarize no_harmless alpha_T
blanchet@35812
   998
    val accum = (initial_gamma, ([], [], []))
blanchet@35386
   999
    val (nondef_ms, accum) =
blanchet@35665
  1000
      ([], accum) |> amass (consider_general_formula mdata Plus) (hd nondef_ts)
blanchet@35665
  1001
                  |> fold (amass (consider_nondefinitional_axiom mdata))
blanchet@35386
  1002
                          (tl nondef_ts)
blanchet@35386
  1003
    val (def_ms, (gamma, cset)) =
blanchet@35665
  1004
      ([], accum) |> fold (amass (consider_definitional_axiom mdata)) def_ts
blanchet@33192
  1005
  in
blanchet@33192
  1006
    case solve (!max_fresh) cset of
blanchet@35665
  1007
      SOME lits => (print_mtype_context ctxt lits gamma;
blanchet@35665
  1008
                    SOME (lits, (nondef_ms, def_ms), !constr_mcache))
blanchet@35665
  1009
    | _ => NONE
blanchet@33192
  1010
  end
blanchet@35812
  1011
  handle UNSOLVABLE () => NONE
blanchet@35812
  1012
       | MTYPE (loc, Ms, Ts) =>
blanchet@35665
  1013
         raise BAD (loc, commas (map string_for_mtype Ms @
blanchet@35665
  1014
                                 map (Syntax.string_of_typ ctxt) Ts))
blanchet@35665
  1015
       | MTERM (loc, ms) =>
blanchet@35665
  1016
         raise BAD (loc, commas (map (string_for_mterm ctxt) ms))
blanchet@35665
  1017
blanchet@35665
  1018
val formulas_monotonic = is_some oooo infer "Monotonicity" false
blanchet@35665
  1019
blanchet@35665
  1020
fun fin_fun_constr T1 T2 =
blanchet@35665
  1021
  (@{const_name FinFun}, (T1 --> T2) --> Type (@{type_name fin_fun}, [T1, T2]))
blanchet@35665
  1022
blanchet@39359
  1023
fun finitize_funs (hol_ctxt as {thy, ctxt, stds, constr_cache, ...})
blanchet@35665
  1024
                  binarize finitizes alpha_T tsp =
blanchet@35665
  1025
  case infer "Finiteness" true hol_ctxt binarize alpha_T tsp of
blanchet@35665
  1026
    SOME (lits, msp, constr_mtypes) =>
blanchet@35812
  1027
    if forall (curry (op =) Minus o snd) lits then
blanchet@35812
  1028
      tsp
blanchet@35812
  1029
    else
blanchet@35812
  1030
      let
blanchet@35812
  1031
        fun should_finitize T a =
blanchet@35812
  1032
          case triple_lookup (type_match thy) finitizes T of
blanchet@35812
  1033
            SOME (SOME false) => false
blanchet@35812
  1034
          | _ => resolve_sign_atom lits a = S Plus
blanchet@35812
  1035
        fun type_from_mtype T M =
blanchet@35812
  1036
          case (M, T) of
blanchet@35812
  1037
            (MAlpha, _) => T
blanchet@35812
  1038
          | (MFun (M1, a, M2), Type (@{type_name fun}, Ts)) =>
blanchet@35812
  1039
            Type (if should_finitize T a then @{type_name fin_fun}
blanchet@35812
  1040
                  else @{type_name fun}, map2 type_from_mtype Ts [M1, M2])
blanchet@38190
  1041
          | (MPair (M1, M2), Type (@{type_name prod}, Ts)) =>
blanchet@38190
  1042
            Type (@{type_name prod}, map2 type_from_mtype Ts [M1, M2])
blanchet@35812
  1043
          | (MType _, _) => T
blanchet@35812
  1044
          | _ => raise MTYPE ("Nitpick_Mono.finitize_funs.type_from_mtype",
blanchet@35812
  1045
                              [M], [T])
blanchet@35812
  1046
        fun finitize_constr (x as (s, T)) =
blanchet@35812
  1047
          (s, case AList.lookup (op =) constr_mtypes x of
blanchet@35812
  1048
                SOME M => type_from_mtype T M
blanchet@35812
  1049
              | NONE => T)
blanchet@37267
  1050
        fun term_from_mterm new_Ts old_Ts m =
blanchet@35812
  1051
          case m of
blanchet@35812
  1052
            MRaw (t, M) =>
blanchet@35812
  1053
            let
blanchet@37267
  1054
              val T = fastype_of1 (old_Ts, t)
blanchet@35812
  1055
              val T' = type_from_mtype T M
blanchet@35812
  1056
            in
blanchet@35812
  1057
              case t of
blanchet@35812
  1058
                Const (x as (s, _)) =>
blanchet@37476
  1059
                if s = @{const_name finite} then
blanchet@35812
  1060
                  case domain_type T' of
blanchet@35812
  1061
                    set_T' as Type (@{type_name fin_fun}, _) =>
blanchet@35812
  1062
                    Abs (Name.uu, set_T', @{const True})
blanchet@35812
  1063
                  | _ => Const (s, T')
blanchet@35812
  1064
                else if s = @{const_name "=="} orelse
haftmann@38864
  1065
                        s = @{const_name HOL.eq} then
blanchet@37476
  1066
                  let
blanchet@37476
  1067
                    val T =
blanchet@37476
  1068
                      case T' of
blanchet@37476
  1069
                        Type (_, [T1, Type (_, [T2, T3])]) =>
blanchet@37476
  1070
                        T1 --> T2 --> T3
blanchet@37476
  1071
                      | _ => raise TYPE ("Nitpick_Mono.finitize_funs.\
blanchet@37476
  1072
                                         \term_from_mterm", [T, T'], [])
blanchet@37476
  1073
                  in coerce_term hol_ctxt new_Ts T' T (Const (s, T)) end
blanchet@39359
  1074
                else if is_built_in_const thy stds x then
blanchet@37267
  1075
                  coerce_term hol_ctxt new_Ts T' T t
blanchet@37256
  1076
                else if is_constr ctxt stds x then
blanchet@35812
  1077
                  Const (finitize_constr x)
blanchet@35812
  1078
                else if is_sel s then
blanchet@35812
  1079
                  let
blanchet@35812
  1080
                    val n = sel_no_from_name s
blanchet@35812
  1081
                    val x' =
blanchet@35812
  1082
                      x |> binarized_and_boxed_constr_for_sel hol_ctxt binarize
blanchet@35812
  1083
                        |> finitize_constr
blanchet@35812
  1084
                    val x'' =
blanchet@35812
  1085
                      binarized_and_boxed_nth_sel_for_constr hol_ctxt binarize
blanchet@35812
  1086
                                                             x' n
blanchet@35812
  1087
                  in Const x'' end
blanchet@35812
  1088
                else
blanchet@35812
  1089
                  Const (s, T')
blanchet@35812
  1090
              | Free (s, T) => Free (s, type_from_mtype T M)
blanchet@35812
  1091
              | Bound _ => t
blanchet@35812
  1092
              | _ => raise MTERM ("Nitpick_Mono.finitize_funs.term_from_mterm",
blanchet@35812
  1093
                                  [m])
blanchet@35812
  1094
            end
blanchet@35812
  1095
          | MApp (m1, m2) =>
blanchet@35812
  1096
            let
blanchet@37267
  1097
              val (t1, t2) = pairself (term_from_mterm new_Ts old_Ts) (m1, m2)
blanchet@37267
  1098
              val (T1, T2) = pairself (curry fastype_of1 new_Ts) (t1, t2)
blanchet@35812
  1099
              val (t1', T2') =
blanchet@35812
  1100
                case T1 of
blanchet@39316
  1101
                  Type (s, [T11, T12]) =>
blanchet@35812
  1102
                  (if s = @{type_name fin_fun} then
blanchet@37256
  1103
                     select_nth_constr_arg ctxt stds (fin_fun_constr T11 T12) t1
blanchet@35812
  1104
                                           0 (T11 --> T12)
blanchet@35812
  1105
                   else
blanchet@35812
  1106
                     t1, T11)
blanchet@35812
  1107
                | _ => raise TYPE ("Nitpick_Mono.finitize_funs.term_from_mterm",
blanchet@35812
  1108
                                   [T1], [])
blanchet@37267
  1109
            in betapply (t1', coerce_term hol_ctxt new_Ts T2' T2 t2) end
blanchet@37267
  1110
          | MAbs (s, old_T, M, a, m') =>
blanchet@35812
  1111
            let
blanchet@37267
  1112
              val new_T = type_from_mtype old_T M
blanchet@37267
  1113
              val t' = term_from_mterm (new_T :: new_Ts) (old_T :: old_Ts) m'
blanchet@37267
  1114
              val T' = fastype_of1 (new_T :: new_Ts, t')
blanchet@35812
  1115
            in
blanchet@37267
  1116
              Abs (s, new_T, t')
blanchet@37267
  1117
              |> should_finitize (new_T --> T') a
blanchet@37267
  1118
                 ? construct_value ctxt stds (fin_fun_constr new_T T') o single
blanchet@35812
  1119
            end
blanchet@35812
  1120
      in
blanchet@35812
  1121
        Unsynchronized.change constr_cache (map (apsnd (map finitize_constr)));
blanchet@37267
  1122
        pairself (map (term_from_mterm [] [])) msp
blanchet@35812
  1123
      end
blanchet@35665
  1124
  | NONE => tsp
blanchet@33192
  1125
blanchet@33192
  1126
end;