src/HOL/Tools/Nitpick/nitpick_mono.ML
author blanchet
Mon Dec 06 13:33:09 2010 +0100 (2010-12-06)
changeset 41011 5c2f16eae066
parent 41009 91495051c2ec
child 41012 e5a23ffb5524
permissions -rw-r--r--
added some missing well-annotatedness constraints to monotonicity calculus
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@41001
    14
    hol_context -> bool -> typ -> term list * term list -> bool
blanchet@35665
    15
  val finitize_funs :
blanchet@41001
    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@40990
    26
structure PL = PropLogic
blanchet@40990
    27
blanchet@40985
    28
datatype sign = Plus | Minus
blanchet@40985
    29
blanchet@33192
    30
type var = int
blanchet@33192
    31
blanchet@40985
    32
datatype annotation = Gen | New | Fls | Tru
blanchet@40985
    33
datatype annotation_atom = A of annotation | V of var
blanchet@33192
    34
blanchet@40996
    35
type assign_literal = var * (sign * annotation)
blanchet@33192
    36
blanchet@35385
    37
datatype mtyp =
blanchet@35385
    38
  MAlpha |
blanchet@40985
    39
  MFun of mtyp * annotation_atom * mtyp |
blanchet@35385
    40
  MPair of mtyp * mtyp |
blanchet@35385
    41
  MType of string * mtyp list |
blanchet@35385
    42
  MRec of string * typ list
blanchet@33192
    43
blanchet@35385
    44
datatype mterm =
blanchet@35386
    45
  MRaw of term * mtyp |
blanchet@40985
    46
  MAbs of string * typ * mtyp * annotation_atom * mterm |
blanchet@35385
    47
  MApp of mterm * mterm
blanchet@35385
    48
blanchet@35385
    49
type mdata =
blanchet@35070
    50
  {hol_ctxt: hol_context,
blanchet@35190
    51
   binarize: bool,
blanchet@33192
    52
   alpha_T: typ,
blanchet@35665
    53
   no_harmless: bool,
blanchet@33192
    54
   max_fresh: int Unsynchronized.ref,
blanchet@35665
    55
   datatype_mcache: ((string * typ list) * mtyp) list Unsynchronized.ref,
blanchet@35665
    56
   constr_mcache: (styp * mtyp) list Unsynchronized.ref}
blanchet@33192
    57
blanchet@35812
    58
exception UNSOLVABLE of unit
blanchet@35665
    59
exception MTYPE of string * mtyp list * typ list
blanchet@35665
    60
exception MTERM of string * mterm list
blanchet@33192
    61
blanchet@38179
    62
val trace = Unsynchronized.ref false
blanchet@38179
    63
fun trace_msg msg = if !trace then tracing (msg ()) else ()
blanchet@33192
    64
blanchet@40985
    65
fun string_for_sign Plus = "+"
blanchet@40985
    66
  | string_for_sign Minus = "-"
blanchet@40985
    67
blanchet@40985
    68
fun negate_sign Plus = Minus
blanchet@40985
    69
  | negate_sign Minus = Plus
blanchet@40985
    70
blanchet@33192
    71
val string_for_var = signed_string_of_int
blanchet@33192
    72
fun string_for_vars sep [] = "0\<^bsub>" ^ sep ^ "\<^esub>"
blanchet@33192
    73
  | string_for_vars sep xs = space_implode sep (map string_for_var xs)
blanchet@33192
    74
fun subscript_string_for_vars sep xs =
blanchet@33192
    75
  if null xs then "" else "\<^bsub>" ^ string_for_vars sep xs ^ "\<^esub>"
blanchet@33192
    76
blanchet@40985
    77
fun string_for_annotation Gen = "G"
blanchet@40985
    78
  | string_for_annotation New = "N"
blanchet@40985
    79
  | string_for_annotation Fls = "F"
blanchet@40985
    80
  | string_for_annotation Tru = "T"
blanchet@33192
    81
blanchet@40985
    82
fun string_for_annotation_atom (A a) = string_for_annotation a
blanchet@40985
    83
  | string_for_annotation_atom (V x) = string_for_var x
blanchet@33192
    84
blanchet@40996
    85
fun string_for_assign_literal (x, (sn, a)) =
blanchet@40996
    86
  string_for_var x ^ (case sn of Plus => " = " | Minus => " \<noteq> ") ^
blanchet@40996
    87
  string_for_annotation a
blanchet@33192
    88
blanchet@35385
    89
val bool_M = MType (@{type_name bool}, [])
blanchet@35386
    90
val dummy_M = MType (nitpick_prefix ^ "dummy", [])
blanchet@33192
    91
blanchet@35385
    92
fun is_MRec (MRec _) = true
blanchet@35385
    93
  | is_MRec _ = false
blanchet@35385
    94
fun dest_MFun (MFun z) = z
blanchet@35665
    95
  | dest_MFun M = raise MTYPE ("Nitpick_Mono.dest_MFun", [M], [])
blanchet@33192
    96
blanchet@33192
    97
val no_prec = 100
blanchet@33192
    98
blanchet@35385
    99
fun precedence_of_mtype (MFun _) = 1
blanchet@35385
   100
  | precedence_of_mtype (MPair _) = 2
blanchet@35385
   101
  | precedence_of_mtype _ = no_prec
blanchet@33192
   102
blanchet@35385
   103
val string_for_mtype =
blanchet@33192
   104
  let
blanchet@35385
   105
    fun aux outer_prec M =
blanchet@33192
   106
      let
blanchet@35385
   107
        val prec = precedence_of_mtype M
blanchet@33192
   108
        val need_parens = (prec < outer_prec)
blanchet@33192
   109
      in
blanchet@33192
   110
        (if need_parens then "(" else "") ^
blanchet@35386
   111
        (if M = dummy_M then
blanchet@35386
   112
           "_"
blanchet@35386
   113
         else case M of
blanchet@35386
   114
             MAlpha => "\<alpha>"
blanchet@40988
   115
           | MFun (M1, aa, M2) =>
blanchet@35386
   116
             aux (prec + 1) M1 ^ " \<Rightarrow>\<^bsup>" ^
blanchet@40988
   117
             string_for_annotation_atom aa ^ "\<^esup> " ^ aux prec M2
blanchet@35386
   118
           | MPair (M1, M2) => aux (prec + 1) M1 ^ " \<times> " ^ aux prec M2
blanchet@35386
   119
           | MType (s, []) =>
blanchet@35386
   120
             if s = @{type_name prop} orelse s = @{type_name bool} then "o"
blanchet@35386
   121
             else s
blanchet@35386
   122
           | MType (s, Ms) => "(" ^ commas (map (aux 0) Ms) ^ ") " ^ s
blanchet@35386
   123
           | MRec (s, _) => "[" ^ s ^ "]") ^
blanchet@33192
   124
        (if need_parens then ")" else "")
blanchet@33192
   125
      end
blanchet@33192
   126
  in aux 0 end
blanchet@33192
   127
blanchet@35385
   128
fun flatten_mtype (MPair (M1, M2)) = maps flatten_mtype [M1, M2]
blanchet@35385
   129
  | flatten_mtype (MType (_, Ms)) = maps flatten_mtype Ms
blanchet@35385
   130
  | flatten_mtype M = [M]
blanchet@35385
   131
blanchet@35386
   132
fun precedence_of_mterm (MRaw _) = no_prec
blanchet@35385
   133
  | precedence_of_mterm (MAbs _) = 1
blanchet@35385
   134
  | precedence_of_mterm (MApp _) = 2
blanchet@33192
   135
blanchet@35385
   136
fun string_for_mterm ctxt =
blanchet@35385
   137
  let
blanchet@35385
   138
    fun mtype_annotation M = "\<^bsup>" ^ string_for_mtype M ^ "\<^esup>"
blanchet@35385
   139
    fun aux outer_prec m =
blanchet@35385
   140
      let
blanchet@35385
   141
        val prec = precedence_of_mterm m
blanchet@35385
   142
        val need_parens = (prec < outer_prec)
blanchet@35385
   143
      in
blanchet@35385
   144
        (if need_parens then "(" else "") ^
blanchet@35385
   145
        (case m of
blanchet@35386
   146
           MRaw (t, M) => Syntax.string_of_term ctxt t ^ mtype_annotation M
blanchet@40988
   147
         | MAbs (s, _, M, aa, m) =>
blanchet@35385
   148
           "\<lambda>" ^ s ^ mtype_annotation M ^ ".\<^bsup>" ^
blanchet@40988
   149
           string_for_annotation_atom aa ^ "\<^esup> " ^ aux prec m
blanchet@35385
   150
         | MApp (m1, m2) => aux prec m1 ^ " " ^ aux (prec + 1) m2) ^
blanchet@35385
   151
        (if need_parens then ")" else "")
blanchet@35385
   152
      end
blanchet@35385
   153
  in aux 0 end
blanchet@35385
   154
blanchet@35386
   155
fun mtype_of_mterm (MRaw (_, M)) = M
blanchet@40988
   156
  | mtype_of_mterm (MAbs (_, _, M, aa, m)) = MFun (M, aa, mtype_of_mterm m)
blanchet@35385
   157
  | mtype_of_mterm (MApp (m1, _)) =
blanchet@35385
   158
    case mtype_of_mterm m1 of
blanchet@35385
   159
      MFun (_, _, M12) => M12
blanchet@35665
   160
    | M1 => raise MTYPE ("Nitpick_Mono.mtype_of_mterm", [M1], [])
blanchet@35665
   161
blanchet@35665
   162
fun strip_mcomb (MApp (m1, m2)) = strip_mcomb m1 ||> (fn ms => append ms [m2])
blanchet@35665
   163
  | strip_mcomb m = (m, [])
blanchet@35385
   164
blanchet@35665
   165
fun initial_mdata hol_ctxt binarize no_harmless alpha_T =
blanchet@35190
   166
  ({hol_ctxt = hol_ctxt, binarize = binarize, alpha_T = alpha_T,
blanchet@35665
   167
    no_harmless = no_harmless, max_fresh = Unsynchronized.ref 0,
blanchet@35665
   168
    datatype_mcache = Unsynchronized.ref [],
blanchet@35665
   169
    constr_mcache = Unsynchronized.ref []} : mdata)
blanchet@33192
   170
blanchet@33192
   171
fun could_exist_alpha_subtype alpha_T (T as Type (_, Ts)) =
blanchet@34936
   172
    T = alpha_T orelse (not (is_fp_iterator_type T) andalso
blanchet@34936
   173
                        exists (could_exist_alpha_subtype alpha_T) Ts)
blanchet@33192
   174
  | could_exist_alpha_subtype alpha_T T = (T = alpha_T)
blanchet@35385
   175
fun could_exist_alpha_sub_mtype _ (alpha_T as TFree _) T =
blanchet@34121
   176
    could_exist_alpha_subtype alpha_T T
blanchet@37256
   177
  | could_exist_alpha_sub_mtype ctxt alpha_T T =
blanchet@37256
   178
    (T = alpha_T orelse is_datatype ctxt [(NONE, true)] T)
blanchet@33192
   179
blanchet@35385
   180
fun exists_alpha_sub_mtype MAlpha = true
blanchet@35385
   181
  | exists_alpha_sub_mtype (MFun (M1, _, M2)) =
blanchet@35385
   182
    exists exists_alpha_sub_mtype [M1, M2]
blanchet@35385
   183
  | exists_alpha_sub_mtype (MPair (M1, M2)) =
blanchet@35385
   184
    exists exists_alpha_sub_mtype [M1, M2]
blanchet@35385
   185
  | exists_alpha_sub_mtype (MType (_, Ms)) = exists exists_alpha_sub_mtype Ms
blanchet@35385
   186
  | exists_alpha_sub_mtype (MRec _) = true
blanchet@33192
   187
blanchet@35385
   188
fun exists_alpha_sub_mtype_fresh MAlpha = true
blanchet@35385
   189
  | exists_alpha_sub_mtype_fresh (MFun (_, V _, _)) = true
blanchet@35385
   190
  | exists_alpha_sub_mtype_fresh (MFun (_, _, M2)) =
blanchet@35385
   191
    exists_alpha_sub_mtype_fresh M2
blanchet@35385
   192
  | exists_alpha_sub_mtype_fresh (MPair (M1, M2)) =
blanchet@35385
   193
    exists exists_alpha_sub_mtype_fresh [M1, M2]
blanchet@35385
   194
  | exists_alpha_sub_mtype_fresh (MType (_, Ms)) =
blanchet@35385
   195
    exists exists_alpha_sub_mtype_fresh Ms
blanchet@35385
   196
  | exists_alpha_sub_mtype_fresh (MRec _) = true
blanchet@33192
   197
blanchet@35385
   198
fun constr_mtype_for_binders z Ms =
blanchet@40985
   199
  fold_rev (fn M => curry3 MFun M (A Gen)) Ms (MRec z)
blanchet@33192
   200
blanchet@35385
   201
fun repair_mtype _ _ MAlpha = MAlpha
blanchet@40988
   202
  | repair_mtype cache seen (MFun (M1, aa, M2)) =
blanchet@40988
   203
    MFun (repair_mtype cache seen M1, aa, repair_mtype cache seen M2)
blanchet@35385
   204
  | repair_mtype cache seen (MPair Mp) =
blanchet@35385
   205
    MPair (pairself (repair_mtype cache seen) Mp)
blanchet@35385
   206
  | repair_mtype cache seen (MType (s, Ms)) =
blanchet@35385
   207
    MType (s, maps (flatten_mtype o repair_mtype cache seen) Ms)
blanchet@35385
   208
  | repair_mtype cache seen (MRec (z as (s, _))) =
blanchet@33192
   209
    case AList.lookup (op =) cache z |> the of
blanchet@35385
   210
      MRec _ => MType (s, [])
blanchet@35385
   211
    | M => if member (op =) seen M then MType (s, [])
blanchet@35385
   212
           else repair_mtype cache (M :: seen) M
blanchet@33192
   213
blanchet@35665
   214
fun repair_datatype_mcache cache =
blanchet@33192
   215
  let
blanchet@35385
   216
    fun repair_one (z, M) =
blanchet@33192
   217
      Unsynchronized.change cache
blanchet@35385
   218
          (AList.update (op =) (z, repair_mtype (!cache) [] M))
blanchet@33192
   219
  in List.app repair_one (rev (!cache)) end
blanchet@33192
   220
blanchet@35665
   221
fun repair_constr_mcache dtype_cache constr_mcache =
blanchet@33192
   222
  let
blanchet@35385
   223
    fun repair_one (x, M) =
blanchet@35665
   224
      Unsynchronized.change constr_mcache
blanchet@35385
   225
          (AList.update (op =) (x, repair_mtype dtype_cache [] M))
blanchet@35665
   226
  in List.app repair_one (!constr_mcache) end
blanchet@35665
   227
blanchet@35665
   228
fun is_fin_fun_supported_type @{typ prop} = true
blanchet@35665
   229
  | is_fin_fun_supported_type @{typ bool} = true
blanchet@35665
   230
  | is_fin_fun_supported_type (Type (@{type_name option}, _)) = true
blanchet@35665
   231
  | is_fin_fun_supported_type _ = false
blanchet@41009
   232
blanchet@41009
   233
(* TODO: clean this up *)
blanchet@35665
   234
fun fin_fun_body _ _ (t as @{term False}) = SOME t
blanchet@35665
   235
  | fin_fun_body _ _ (t as Const (@{const_name None}, _)) = SOME t
blanchet@35665
   236
  | fin_fun_body dom_T ran_T
blanchet@35665
   237
                 ((t0 as Const (@{const_name If}, _))
haftmann@38864
   238
                  $ (t1 as Const (@{const_name HOL.eq}, _) $ Bound 0 $ t1')
blanchet@35665
   239
                  $ t2 $ t3) =
blanchet@35665
   240
    (if loose_bvar1 (t1', 0) then
blanchet@35665
   241
       NONE
blanchet@35665
   242
     else case fin_fun_body dom_T ran_T t3 of
blanchet@35665
   243
       NONE => NONE
blanchet@35665
   244
     | SOME t3 =>
blanchet@35665
   245
       SOME (t0 $ (Const (@{const_name is_unknown}, dom_T --> bool_T) $ t1')
blanchet@35665
   246
                $ (Const (@{const_name unknown}, ran_T)) $ (t0 $ t1 $ t2 $ t3)))
blanchet@35665
   247
  | fin_fun_body _ _ _ = NONE
blanchet@33192
   248
blanchet@41011
   249
(* ### FIXME: make sure well-annotated! *)
blanchet@40998
   250
blanchet@35672
   251
fun fresh_mfun_for_fun_type (mdata as {max_fresh, ...} : mdata) all_minus
blanchet@35672
   252
                            T1 T2 =
blanchet@33192
   253
  let
blanchet@35672
   254
    val M1 = fresh_mtype_for_type mdata all_minus T1
blanchet@35672
   255
    val M2 = fresh_mtype_for_type mdata all_minus T2
blanchet@40988
   256
    val aa = if not all_minus andalso exists_alpha_sub_mtype_fresh M1 andalso
blanchet@40988
   257
                is_fin_fun_supported_type (body_type T2) then
blanchet@40988
   258
               V (Unsynchronized.inc max_fresh)
blanchet@40988
   259
             else
blanchet@40988
   260
               A Gen
blanchet@40988
   261
  in (M1, aa, M2) end
blanchet@37256
   262
and fresh_mtype_for_type (mdata as {hol_ctxt as {ctxt, ...}, binarize, alpha_T,
blanchet@35672
   263
                                    datatype_mcache, constr_mcache, ...})
blanchet@35672
   264
                         all_minus =
blanchet@35385
   265
  let
blanchet@35385
   266
    fun do_type T =
blanchet@33192
   267
      if T = alpha_T then
blanchet@35385
   268
        MAlpha
blanchet@33192
   269
      else case T of
blanchet@35665
   270
        Type (@{type_name fun}, [T1, T2]) =>
blanchet@39342
   271
        MFun (fresh_mfun_for_fun_type mdata all_minus T1 T2)
blanchet@38190
   272
      | Type (@{type_name prod}, [T1, T2]) => MPair (pairself do_type (T1, T2))
blanchet@33192
   273
      | Type (z as (s, _)) =>
blanchet@37256
   274
        if could_exist_alpha_sub_mtype ctxt alpha_T T then
blanchet@35665
   275
          case AList.lookup (op =) (!datatype_mcache) z of
blanchet@35385
   276
            SOME M => M
blanchet@33192
   277
          | NONE =>
blanchet@33192
   278
            let
blanchet@35665
   279
              val _ = Unsynchronized.change datatype_mcache (cons (z, MRec z))
blanchet@35219
   280
              val xs = binarized_and_boxed_datatype_constrs hol_ctxt binarize T
blanchet@35385
   281
              val (all_Ms, constr_Ms) =
blanchet@35385
   282
                fold_rev (fn (_, T') => fn (all_Ms, constr_Ms) =>
blanchet@33192
   283
                             let
blanchet@35385
   284
                               val binder_Ms = map do_type (binder_types T')
blanchet@35385
   285
                               val new_Ms = filter exists_alpha_sub_mtype_fresh
blanchet@35385
   286
                                                   binder_Ms
blanchet@35385
   287
                               val constr_M = constr_mtype_for_binders z
blanchet@35385
   288
                                                                       binder_Ms
blanchet@33192
   289
                             in
blanchet@35385
   290
                               (union (op =) new_Ms all_Ms,
blanchet@35385
   291
                                constr_M :: constr_Ms)
blanchet@33192
   292
                             end)
blanchet@33192
   293
                         xs ([], [])
blanchet@35385
   294
              val M = MType (s, all_Ms)
blanchet@35665
   295
              val _ = Unsynchronized.change datatype_mcache
blanchet@35385
   296
                          (AList.update (op =) (z, M))
blanchet@35665
   297
              val _ = Unsynchronized.change constr_mcache
blanchet@35385
   298
                          (append (xs ~~ constr_Ms))
blanchet@33192
   299
            in
blanchet@35665
   300
              if forall (not o is_MRec o snd) (!datatype_mcache) then
blanchet@35665
   301
                (repair_datatype_mcache datatype_mcache;
blanchet@35665
   302
                 repair_constr_mcache (!datatype_mcache) constr_mcache;
blanchet@35665
   303
                 AList.lookup (op =) (!datatype_mcache) z |> the)
blanchet@33192
   304
              else
blanchet@35385
   305
                M
blanchet@33192
   306
            end
blanchet@33192
   307
        else
blanchet@35385
   308
          MType (s, [])
blanchet@37260
   309
      | _ => MType (simple_string_of_typ T, [])
blanchet@33192
   310
  in do_type end
blanchet@33192
   311
blanchet@41009
   312
val ground_and_sole_base_constrs = [@{const_name Nil}, @{const_name None}]
blanchet@41009
   313
blanchet@35385
   314
fun prodM_factors (MPair (M1, M2)) = maps prodM_factors [M1, M2]
blanchet@35385
   315
  | prodM_factors M = [M]
blanchet@35665
   316
fun curried_strip_mtype (MFun (M1, _, M2)) =
blanchet@35385
   317
    curried_strip_mtype M2 |>> append (prodM_factors M1)
blanchet@35385
   318
  | curried_strip_mtype M = ([], M)
blanchet@35385
   319
fun sel_mtype_from_constr_mtype s M =
blanchet@41009
   320
  let
blanchet@41009
   321
    val (arg_Ms, dataM) = curried_strip_mtype M
blanchet@41009
   322
    val a = if member (op =) ground_and_sole_base_constrs
blanchet@41009
   323
                             (constr_name_for_sel_like s) then
blanchet@41009
   324
              Fls
blanchet@41009
   325
            else
blanchet@41009
   326
              Gen
blanchet@41009
   327
  in
blanchet@41009
   328
    MFun (dataM, A a,
blanchet@35385
   329
          case sel_no_from_name s of ~1 => bool_M | n => nth arg_Ms n)
blanchet@33192
   330
  end
blanchet@33192
   331
blanchet@37256
   332
fun mtype_for_constr (mdata as {hol_ctxt = {ctxt, ...}, alpha_T, constr_mcache,
blanchet@33192
   333
                                ...}) (x as (_, T)) =
blanchet@37256
   334
  if could_exist_alpha_sub_mtype ctxt alpha_T T then
blanchet@35665
   335
    case AList.lookup (op =) (!constr_mcache) x of
blanchet@35385
   336
      SOME M => M
blanchet@35384
   337
    | NONE => if T = alpha_T then
blanchet@35672
   338
                let val M = fresh_mtype_for_type mdata false T in
blanchet@35665
   339
                  (Unsynchronized.change constr_mcache (cons (x, M)); M)
blanchet@35384
   340
                end
blanchet@35384
   341
              else
blanchet@35672
   342
                (fresh_mtype_for_type mdata false (body_type T);
blanchet@35665
   343
                 AList.lookup (op =) (!constr_mcache) x |> the)
blanchet@33192
   344
  else
blanchet@35672
   345
    fresh_mtype_for_type mdata false T
blanchet@35385
   346
fun mtype_for_sel (mdata as {hol_ctxt, binarize, ...}) (x as (s, _)) =
blanchet@35190
   347
  x |> binarized_and_boxed_constr_for_sel hol_ctxt binarize
blanchet@35385
   348
    |> mtype_for_constr mdata |> sel_mtype_from_constr_mtype s
blanchet@33192
   349
blanchet@40989
   350
fun resolve_annotation_atom asgs (V x) =
blanchet@40989
   351
    x |> AList.lookup (op =) asgs |> Option.map A |> the_default (V x)
blanchet@40988
   352
  | resolve_annotation_atom _ aa = aa
blanchet@40989
   353
fun resolve_mtype asgs =
blanchet@33192
   354
  let
blanchet@35385
   355
    fun aux MAlpha = MAlpha
blanchet@40988
   356
      | aux (MFun (M1, aa, M2)) =
blanchet@40989
   357
        MFun (aux M1, resolve_annotation_atom asgs aa, aux M2)
blanchet@35385
   358
      | aux (MPair Mp) = MPair (pairself aux Mp)
blanchet@35385
   359
      | aux (MType (s, Ms)) = MType (s, map aux Ms)
blanchet@35385
   360
      | aux (MRec z) = MRec z
blanchet@33192
   361
  in aux end
blanchet@33192
   362
blanchet@40996
   363
datatype comp_op = Eq | Neq | Leq
blanchet@33192
   364
blanchet@40985
   365
type comp = annotation_atom * annotation_atom * comp_op * var list
blanchet@40995
   366
type assign_clause = assign_literal list
blanchet@33192
   367
blanchet@40994
   368
type constraint_set = comp list * assign_clause list
blanchet@33192
   369
blanchet@33192
   370
fun string_for_comp_op Eq = "="
blanchet@40996
   371
  | string_for_comp_op Neq = "\<noteq>"
blanchet@33192
   372
  | string_for_comp_op Leq = "\<le>"
blanchet@33192
   373
blanchet@40990
   374
fun string_for_comp (aa1, aa2, cmp, xs) =
blanchet@40990
   375
  string_for_annotation_atom aa1 ^ " " ^ string_for_comp_op cmp ^
blanchet@40990
   376
  subscript_string_for_vars " \<and> " xs ^ " " ^ string_for_annotation_atom aa2
blanchet@33192
   377
blanchet@40999
   378
fun string_for_assign_clause NONE = "\<top>"
blanchet@40999
   379
  | string_for_assign_clause (SOME []) = "\<bot>"
blanchet@40999
   380
  | string_for_assign_clause (SOME asgs) =
blanchet@40995
   381
    space_implode " \<or> " (map string_for_assign_literal asgs)
blanchet@40990
   382
blanchet@40996
   383
fun add_assign_literal (x, (sn, a)) clauses =
blanchet@40996
   384
  if exists (fn [(x', (sn', a'))] =>
blanchet@40996
   385
                x = x' andalso ((sn = sn' andalso a <> a') orelse
blanchet@40996
   386
                                (sn <> sn' andalso a = a'))
blanchet@40996
   387
              | _ => false) clauses then
blanchet@40994
   388
    NONE
blanchet@40994
   389
  else
blanchet@40996
   390
    SOME ([(x, a)] :: clauses)
blanchet@33192
   391
blanchet@40991
   392
fun add_assign_disjunct _ NONE = NONE
blanchet@40991
   393
  | add_assign_disjunct asg (SOME asgs) = SOME (insert (op =) asg asgs)
blanchet@40991
   394
blanchet@40999
   395
fun add_assign_clause NONE = I
blanchet@40999
   396
  | add_assign_clause (SOME clause) = insert (op =) clause
blanchet@40997
   397
blanchet@40996
   398
fun annotation_comp Eq a1 a2 = (a1 = a2)
blanchet@40996
   399
  | annotation_comp Neq a1 a2 = (a1 <> a2)
blanchet@40996
   400
  | annotation_comp Leq a1 a2 = (a1 = a2 orelse a2 = Gen)
blanchet@40996
   401
blanchet@40997
   402
fun sign_for_comp_op Eq = Plus
blanchet@40997
   403
  | sign_for_comp_op Neq = Minus
blanchet@40997
   404
  | sign_for_comp_op Leq = raise BAD ("sign_for_comp_op", "unexpected \"Leq\"")
blanchet@40996
   405
blanchet@40996
   406
fun do_annotation_atom_comp Leq [] aa1 aa2 (cset as (comps, clauses)) =
blanchet@40988
   407
    (case (aa1, aa2) of
blanchet@40996
   408
       (A a1, A a2) => if annotation_comp Leq a1 a2 then SOME cset else NONE
blanchet@40996
   409
     | _ => SOME (insert (op =) (aa1, aa2, Leq, []) comps, clauses))
blanchet@40996
   410
  | do_annotation_atom_comp cmp [] aa1 aa2 (cset as (comps, clauses)) =
blanchet@40996
   411
    (case (aa1, aa2) of
blanchet@40996
   412
       (A a1, A a2) => if annotation_comp cmp a1 a2 then SOME cset else NONE
blanchet@40988
   413
     | (V x1, A a2) =>
blanchet@40997
   414
       clauses |> add_assign_literal (x1, (sign_for_comp_op cmp, a2))
blanchet@40996
   415
               |> Option.map (pair comps)
blanchet@40996
   416
     | (A _, V _) => do_annotation_atom_comp cmp [] aa2 aa1 cset
blanchet@40996
   417
     | (V _, V _) => SOME (insert (op =) (aa1, aa2, cmp, []) comps, clauses))
blanchet@40994
   418
  | do_annotation_atom_comp cmp xs aa1 aa2 (comps, clauses) =
blanchet@40994
   419
    SOME (insert (op =) (aa1, aa2, cmp, xs) comps, clauses)
blanchet@33192
   420
blanchet@40997
   421
fun add_annotation_atom_comp cmp xs aa1 aa2 (comps, clauses) =
blanchet@40998
   422
  (trace_msg (fn () => "*** Add " ^ string_for_comp (aa1, aa2, cmp, xs));
blanchet@40994
   423
   case do_annotation_atom_comp cmp xs aa1 aa2 (comps, clauses) of
blanchet@40993
   424
     NONE => (trace_msg (K "**** Unsolvable"); raise UNSOLVABLE ())
blanchet@40994
   425
   | SOME cset => cset)
blanchet@40993
   426
blanchet@35385
   427
fun do_mtype_comp _ _ _ _ NONE = NONE
blanchet@40994
   428
  | do_mtype_comp _ _ MAlpha MAlpha cset = cset
blanchet@40988
   429
  | do_mtype_comp Eq xs (MFun (M11, aa1, M12)) (MFun (M21, aa2, M22))
blanchet@40994
   430
                  (SOME cset) =
blanchet@40994
   431
    cset |> do_annotation_atom_comp Eq xs aa1 aa2
blanchet@40994
   432
         |> do_mtype_comp Eq xs M11 M21 |> do_mtype_comp Eq xs M12 M22
blanchet@40988
   433
  | do_mtype_comp Leq xs (MFun (M11, aa1, M12)) (MFun (M21, aa2, M22))
blanchet@40994
   434
                  (SOME cset) =
blanchet@35385
   435
    (if exists_alpha_sub_mtype M11 then
blanchet@40994
   436
       cset |> do_annotation_atom_comp Leq xs aa1 aa2
blanchet@40994
   437
            |> do_mtype_comp Leq xs M21 M11
blanchet@40994
   438
            |> (case aa2 of
blanchet@40994
   439
                  A Gen => I
blanchet@40994
   440
                | A _ => do_mtype_comp Leq xs M11 M21
blanchet@40994
   441
                | V x => do_mtype_comp Leq (x :: xs) M11 M21)
blanchet@33192
   442
     else
blanchet@40994
   443
       SOME cset)
blanchet@35385
   444
    |> do_mtype_comp Leq xs M12 M22
blanchet@35385
   445
  | do_mtype_comp cmp xs (M1 as MPair (M11, M12)) (M2 as MPair (M21, M22))
blanchet@40994
   446
                  cset =
blanchet@40994
   447
    (cset |> fold (uncurry (do_mtype_comp cmp xs)) [(M11, M21), (M12, M22)]
blanchet@40994
   448
     handle Library.UnequalLengths =>
blanchet@35665
   449
            raise MTYPE ("Nitpick_Mono.do_mtype_comp", [M1, M2], []))
blanchet@40994
   450
  | do_mtype_comp _ _ (MType _) (MType _) cset =
blanchet@40994
   451
    cset (* no need to compare them thanks to the cache *)
blanchet@35665
   452
  | do_mtype_comp cmp _ M1 M2 _ =
blanchet@35665
   453
    raise MTYPE ("Nitpick_Mono.do_mtype_comp (" ^ string_for_comp_op cmp ^ ")",
blanchet@35665
   454
                 [M1, M2], [])
blanchet@33192
   455
blanchet@40994
   456
fun add_mtype_comp cmp M1 M2 cset =
blanchet@40991
   457
  (trace_msg (fn () => "*** Add " ^ string_for_mtype M1 ^ " " ^
blanchet@40991
   458
                       string_for_comp_op cmp ^ " " ^ string_for_mtype M2);
blanchet@40994
   459
   case SOME cset |> do_mtype_comp cmp [] M1 M2 of
blanchet@40991
   460
     NONE => (trace_msg (K "**** Unsolvable"); raise UNSOLVABLE ())
blanchet@40994
   461
   | SOME cset => cset)
blanchet@33192
   462
blanchet@35385
   463
val add_mtypes_equal = add_mtype_comp Eq
blanchet@35385
   464
val add_is_sub_mtype = add_mtype_comp Leq
blanchet@33192
   465
blanchet@35385
   466
fun do_notin_mtype_fv _ _ _ NONE = NONE
blanchet@40994
   467
  | do_notin_mtype_fv Minus _ MAlpha cset = cset
blanchet@35385
   468
  | do_notin_mtype_fv Plus [] MAlpha _ = NONE
blanchet@40996
   469
  | do_notin_mtype_fv Plus [asg] MAlpha (SOME clauses) =
blanchet@40996
   470
    clauses |> add_assign_literal asg
blanchet@41000
   471
  | do_notin_mtype_fv Plus unless MAlpha (SOME clauses) =
blanchet@41000
   472
    SOME (insert (op =) unless clauses)
blanchet@41000
   473
  | do_notin_mtype_fv sn unless (MFun (M1, A a, M2)) cset =
blanchet@41000
   474
    cset |> (if a <> Gen andalso sn = Plus then do_notin_mtype_fv Plus unless M1
blanchet@40994
   475
             else I)
blanchet@41000
   476
         |> (if a = Gen orelse sn = Plus then do_notin_mtype_fv Minus unless M1
blanchet@40994
   477
             else I)
blanchet@41000
   478
         |> do_notin_mtype_fv sn unless M2
blanchet@41000
   479
  | do_notin_mtype_fv Plus unless (MFun (M1, V x, M2)) cset =
blanchet@41000
   480
    cset |> (case add_assign_disjunct (x, (Plus, Gen)) (SOME unless) of
blanchet@40994
   481
               NONE => I
blanchet@41000
   482
             | SOME unless' => do_notin_mtype_fv Plus unless' M1)
blanchet@41000
   483
         |> do_notin_mtype_fv Minus unless M1
blanchet@41000
   484
         |> do_notin_mtype_fv Plus unless M2
blanchet@41000
   485
  | do_notin_mtype_fv Minus unless (MFun (M1, V x, M2)) cset =
blanchet@40996
   486
    cset |> (case fold (fn a => add_assign_disjunct (x, (Plus, a))) [Fls, Tru]
blanchet@41000
   487
                       (SOME unless) of
blanchet@40994
   488
               NONE => I
blanchet@41000
   489
             | SOME unless' => do_notin_mtype_fv Plus unless' M1)
blanchet@41000
   490
         |> do_notin_mtype_fv Minus unless M2
blanchet@41000
   491
  | do_notin_mtype_fv sn unless (MPair (M1, M2)) cset =
blanchet@41000
   492
    cset |> fold (do_notin_mtype_fv sn unless) [M1, M2]
blanchet@41000
   493
  | do_notin_mtype_fv sn unless (MType (_, Ms)) cset =
blanchet@41000
   494
    cset |> fold (do_notin_mtype_fv sn unless) Ms
blanchet@40994
   495
 | do_notin_mtype_fv _ _ M _ =
blanchet@40994
   496
   raise MTYPE ("Nitpick_Mono.do_notin_mtype_fv", [M], [])
blanchet@33192
   497
blanchet@41000
   498
fun add_notin_mtype_fv sn unless M (comps, clauses) =
blanchet@40985
   499
  (trace_msg (fn () => "*** Add " ^ string_for_mtype M ^ " is " ^
blanchet@40985
   500
                       (case sn of Minus => "concrete" | Plus => "complete"));
blanchet@41000
   501
   case SOME clauses |> do_notin_mtype_fv sn unless M of
blanchet@40985
   502
     NONE => (trace_msg (K "**** Unsolvable"); raise UNSOLVABLE ())
blanchet@40994
   503
   | SOME clauses => (comps, clauses))
blanchet@33192
   504
blanchet@35665
   505
val add_mtype_is_concrete = add_notin_mtype_fv Minus
blanchet@35665
   506
val add_mtype_is_complete = add_notin_mtype_fv Plus
blanchet@33192
   507
blanchet@40986
   508
val bool_table =
blanchet@40986
   509
  [(Gen, (false, false)),
blanchet@40986
   510
   (New, (false, true)),
blanchet@40986
   511
   (Fls, (true, false)),
blanchet@40986
   512
   (Tru, (true, true))]
blanchet@40986
   513
blanchet@40993
   514
fun fst_var n = 2 * n
blanchet@40993
   515
fun snd_var n = 2 * n + 1
blanchet@40993
   516
blanchet@40986
   517
val bools_from_annotation = AList.lookup (op =) bool_table #> the
blanchet@40986
   518
val annotation_from_bools = AList.find (op =) bool_table #> the_single
blanchet@33192
   519
blanchet@40990
   520
fun prop_for_bool b = if b then PL.True else PL.False
blanchet@40990
   521
fun prop_for_bool_var_equality (v1, v2) =
blanchet@40999
   522
  PL.SAnd (PL.SOr (PL.BoolVar v1, PL.SNot (PL.BoolVar v2)),
blanchet@40999
   523
           PL.SOr (PL.SNot (PL.BoolVar v1), PL.BoolVar v2))
blanchet@40996
   524
fun prop_for_assign (x, a) =
blanchet@40986
   525
  let val (b1, b2) = bools_from_annotation a in
blanchet@40999
   526
    PL.SAnd (PL.BoolVar (fst_var x) |> not b1 ? PL.SNot,
blanchet@40999
   527
             PL.BoolVar (snd_var x) |> not b2 ? PL.SNot)
blanchet@40986
   528
  end
blanchet@40996
   529
fun prop_for_assign_literal (x, (Plus, a)) = prop_for_assign (x, a)
blanchet@40999
   530
  | prop_for_assign_literal (x, (Minus, a)) = PL.SNot (prop_for_assign (x, a))
blanchet@40990
   531
fun prop_for_atom_assign (A a', a) = prop_for_bool (a = a')
blanchet@40996
   532
  | prop_for_atom_assign (V x, a) = prop_for_assign_literal (x, (Plus, a))
blanchet@40990
   533
fun prop_for_atom_equality (aa1, A a2) = prop_for_atom_assign (aa1, a2)
blanchet@40990
   534
  | prop_for_atom_equality (A a1, aa2) = prop_for_atom_assign (aa2, a1)
blanchet@40990
   535
  | prop_for_atom_equality (V x1, V x2) =
blanchet@40999
   536
    PL.SAnd (prop_for_bool_var_equality (pairself fst_var (x1, x2)),
blanchet@40999
   537
             prop_for_bool_var_equality (pairself snd_var (x1, x2)))
blanchet@40995
   538
val prop_for_assign_clause = PL.exists o map prop_for_assign_literal
blanchet@40995
   539
fun prop_for_exists_var_assign_literal xs a =
blanchet@40996
   540
  PL.exists (map (fn x => prop_for_assign_literal (x, (Plus, a))) xs)
blanchet@40988
   541
fun prop_for_comp (aa1, aa2, Eq, []) =
blanchet@40990
   542
    PL.SAnd (prop_for_comp (aa1, aa2, Leq, []),
blanchet@40990
   543
             prop_for_comp (aa2, aa1, Leq, []))
blanchet@40996
   544
  | prop_for_comp (aa1, aa2, Neq, []) =
blanchet@40999
   545
    PL.SNot (prop_for_comp (aa1, aa2, Eq, []))
blanchet@40988
   546
  | prop_for_comp (aa1, aa2, Leq, []) =
blanchet@40990
   547
    PL.SOr (prop_for_atom_equality (aa1, aa2), prop_for_atom_assign (aa2, Gen))
blanchet@40988
   548
  | prop_for_comp (aa1, aa2, cmp, xs) =
blanchet@40995
   549
    PL.SOr (prop_for_exists_var_assign_literal xs Gen,
blanchet@40990
   550
            prop_for_comp (aa1, aa2, cmp, []))
blanchet@33192
   551
blanchet@40990
   552
fun extract_assigns max_var assigns asgs =
blanchet@33192
   553
  fold (fn x => fn accum =>
blanchet@40989
   554
           if AList.defined (op =) asgs x then
blanchet@33192
   555
             accum
blanchet@40986
   556
           else case (fst_var x, snd_var x) |> pairself assigns of
blanchet@40986
   557
             (NONE, NONE) => accum
blanchet@40993
   558
           | bp => (x, annotation_from_bools (pairself (the_default false) bp))
blanchet@40993
   559
                   :: accum)
blanchet@40989
   560
       (max_var downto 1) asgs
blanchet@33192
   561
blanchet@41001
   562
fun print_problem comps clauses =
blanchet@41001
   563
  trace_msg (fn () => "*** Problem:\n" ^
blanchet@41001
   564
                      cat_lines (map string_for_comp comps @
blanchet@41001
   565
                                 map (string_for_assign_clause o SOME) clauses))
blanchet@33192
   566
blanchet@40989
   567
fun print_solution asgs =
blanchet@40989
   568
  trace_msg (fn () => "*** Solution:\n" ^
blanchet@40989
   569
      (asgs
blanchet@40989
   570
       |> map swap
blanchet@40989
   571
       |> AList.group (op =)
blanchet@40989
   572
       |> map (fn (a, xs) => string_for_annotation a ^ ": " ^
blanchet@41005
   573
                             string_for_vars ", " (sort int_ord xs))
blanchet@40989
   574
       |> space_implode "\n"))
blanchet@33192
   575
blanchet@41007
   576
(* The ML solver timeout should correspond more or less to the overhead of
blanchet@41007
   577
   invoking an external prover. *)
blanchet@41007
   578
val ml_solver_timeout = SOME (seconds 0.02)
blanchet@41007
   579
blanchet@41007
   580
fun solve tac_timeout max_var (comps, clauses) =
blanchet@40146
   581
  let
blanchet@40996
   582
    val asgs = map_filter (fn [(x, (_, a))] => SOME (x, a) | _ => NONE) clauses
blanchet@40146
   583
    fun do_assigns assigns =
blanchet@40990
   584
      SOME (extract_assigns max_var assigns asgs |> tap print_solution)
blanchet@41001
   585
    val _ = print_problem comps clauses
blanchet@40993
   586
    val prop =
blanchet@41001
   587
      PL.all (map prop_for_comp comps @ map prop_for_assign_clause clauses)
blanchet@40146
   588
  in
blanchet@40990
   589
    if PL.eval (K false) prop then
blanchet@40990
   590
      do_assigns (K (SOME false))
blanchet@40990
   591
    else if PL.eval (K true) prop then
blanchet@40990
   592
      do_assigns (K (SOME true))
blanchet@40146
   593
    else
blanchet@40146
   594
      let
blanchet@40146
   595
        (* use the first ML solver (to avoid startup overhead) *)
blanchet@41007
   596
        val (ml_solvers, nonml_solvers) =
blanchet@41007
   597
          !SatSolver.solvers
blanchet@41007
   598
          |> List.partition (member (op =) ["dptsat", "dpll"] o fst)
blanchet@41007
   599
        val res =
blanchet@41007
   600
          if null nonml_solvers then
blanchet@41007
   601
            time_limit tac_timeout (snd (hd ml_solvers)) prop
blanchet@41007
   602
          else
blanchet@41007
   603
            time_limit ml_solver_timeout (snd (hd ml_solvers)) prop
blanchet@41007
   604
            handle TimeLimit.TimeOut =>
blanchet@41007
   605
                   time_limit tac_timeout (SatSolver.invoke_solver "auto") prop
blanchet@40146
   606
      in
blanchet@41007
   607
        case res of
blanchet@40146
   608
          SatSolver.SATISFIABLE assigns => do_assigns assigns
blanchet@40994
   609
        | _ => (trace_msg (K "*** Unsolvable"); NONE)
blanchet@40146
   610
      end
blanchet@41007
   611
      handle TimeLimit.TimeOut => (trace_msg (K "*** Timed out"); NONE)
blanchet@40146
   612
  end
blanchet@33192
   613
blanchet@40998
   614
type mcontext =
blanchet@35665
   615
  {bound_Ts: typ list,
blanchet@35665
   616
   bound_Ms: mtyp list,
blanchet@40998
   617
   frame: (int * annotation_atom) list,
blanchet@35385
   618
   frees: (styp * mtyp) list,
blanchet@35385
   619
   consts: (styp * mtyp) list}
blanchet@33192
   620
blanchet@40998
   621
fun string_for_bound ctxt Ms (j, aa) =
blanchet@40998
   622
  Syntax.string_of_term ctxt (Bound (length Ms - j - 1)) ^ " :\<^bsup>" ^
blanchet@40998
   623
  string_for_annotation_atom aa ^ "\<^esup> " ^
blanchet@40998
   624
  string_for_mtype (nth Ms (length Ms - j - 1))
blanchet@40998
   625
fun string_for_free relevant_frees ((s, _), M) =
blanchet@40998
   626
  if member (op =) relevant_frees s then SOME (s ^ " : " ^ string_for_mtype M)
blanchet@40998
   627
  else NONE
blanchet@40998
   628
fun string_for_mcontext ctxt t {bound_Ms, frame, frees, ...} =
blanchet@40998
   629
  (map_filter (string_for_free (Term.add_free_names t [])) frees @
blanchet@40998
   630
   map (string_for_bound ctxt bound_Ms) frame)
blanchet@40998
   631
  |> commas |> enclose "[" "]"
blanchet@33192
   632
blanchet@40987
   633
val initial_gamma =
blanchet@40998
   634
  {bound_Ts = [], bound_Ms = [], frame = [], frees = [], consts = []}
blanchet@33192
   635
blanchet@40998
   636
fun push_bound aa T M {bound_Ts, bound_Ms, frame, frees, consts} =
blanchet@40987
   637
  {bound_Ts = T :: bound_Ts, bound_Ms = M :: bound_Ms,
blanchet@40998
   638
   frame = frame @ [(length bound_Ts, aa)], frees = frees, consts = consts}
blanchet@40998
   639
fun pop_bound {bound_Ts, bound_Ms, frame, frees, consts} =
blanchet@40993
   640
  {bound_Ts = tl bound_Ts, bound_Ms = tl bound_Ms,
blanchet@40998
   641
   frame = frame |> filter_out (fn (j, _) => j = length bound_Ts - 1),
blanchet@40987
   642
   frees = frees, consts = consts}
blanchet@35665
   643
  handle List.Empty => initial_gamma (* FIXME: needed? *)
blanchet@33192
   644
blanchet@40998
   645
fun set_frame frame ({bound_Ts, bound_Ms, frees, consts, ...} : mcontext) =
blanchet@40998
   646
  {bound_Ts = bound_Ts, bound_Ms = bound_Ms, frame = frame, frees = frees,
blanchet@40998
   647
   consts = consts}
blanchet@40994
   648
blanchet@40994
   649
(* FIXME: make sure tracing messages are complete *)
blanchet@40994
   650
blanchet@40998
   651
fun add_comp_frame aa cmp = fold (add_annotation_atom_comp cmp [] aa o snd)
blanchet@40994
   652
blanchet@40994
   653
fun add_bound_frame j frame =
blanchet@40994
   654
  let
blanchet@40994
   655
    val (new_frame, gen_frame) = List.partition (curry (op =) j o fst) frame
blanchet@40994
   656
  in
blanchet@40998
   657
    add_comp_frame (A New) Leq new_frame
blanchet@40998
   658
    #> add_comp_frame (A Gen) Eq gen_frame
blanchet@40994
   659
  end
blanchet@40994
   660
blanchet@40997
   661
fun fresh_frame ({max_fresh, ...} : mdata) fls tru =
blanchet@40997
   662
  map (apsnd (fn aa =>
blanchet@40997
   663
                 case (aa, fls, tru) of
blanchet@40997
   664
                   (A Fls, SOME a, _) => A a
blanchet@40997
   665
                 | (A Tru, _, SOME a) => A a
blanchet@40997
   666
                 | (A Gen, _, _) => A Gen
blanchet@40997
   667
                 | _ => V (Unsynchronized.inc max_fresh)))
blanchet@40994
   668
blanchet@40997
   669
fun conj_clauses res_aa aa1 aa2 =
blanchet@40997
   670
  [[(aa1, (Neq, Tru)), (aa2, (Neq, Tru)), (res_aa, (Eq, Tru))],
blanchet@40997
   671
   [(aa1, (Neq, Fls)), (res_aa, (Eq, Fls))],
blanchet@40997
   672
   [(aa2, (Neq, Fls)), (res_aa, (Eq, Fls))],
blanchet@40997
   673
   [(aa1, (Neq, Gen)), (aa2, (Eq, Fls)), (res_aa, (Eq, Gen))],
blanchet@40997
   674
   [(aa1, (Neq, New)), (aa2, (Eq, Fls)), (res_aa, (Eq, Gen))],
blanchet@40997
   675
   [(aa1, (Eq, Fls)), (aa2, (Neq, Gen)), (res_aa, (Eq, Gen))],
blanchet@40997
   676
   [(aa1, (Eq, Fls)), (aa2, (Neq, New)), (res_aa, (Eq, Gen))]]
blanchet@40997
   677
blanchet@40997
   678
fun disj_clauses res_aa aa1 aa2 =
blanchet@40997
   679
  [[(aa1, (Neq, Tru)), (res_aa, (Eq, Tru))],
blanchet@40997
   680
   [(aa2, (Neq, Tru)), (res_aa, (Eq, Tru))],
blanchet@40997
   681
   [(aa1, (Neq, Fls)), (aa2, (Neq, Fls)), (res_aa, (Eq, Fls))],
blanchet@40997
   682
   [(aa1, (Neq, Gen)), (aa2, (Eq, Tru)), (res_aa, (Eq, Gen))],
blanchet@40997
   683
   [(aa1, (Neq, New)), (aa2, (Eq, Tru)), (res_aa, (Eq, Gen))],
blanchet@40997
   684
   [(aa1, (Eq, Tru)), (aa2, (Neq, Gen)), (res_aa, (Eq, Gen))],
blanchet@40997
   685
   [(aa1, (Eq, Tru)), (aa2, (Neq, New)), (res_aa, (Eq, Gen))]]
blanchet@40994
   686
blanchet@40997
   687
fun imp_clauses res_aa aa1 aa2 =
blanchet@40997
   688
  [[(aa1, (Neq, Fls)), (res_aa, (Eq, Tru))],
blanchet@40997
   689
   [(aa2, (Neq, Tru)), (res_aa, (Eq, Tru))],
blanchet@40997
   690
   [(aa1, (Neq, Tru)), (aa2, (Neq, Fls)), (res_aa, (Eq, Fls))],
blanchet@40997
   691
   [(aa1, (Neq, Gen)), (aa2, (Eq, Tru)), (res_aa, (Eq, Gen))],
blanchet@40997
   692
   [(aa1, (Neq, New)), (aa2, (Eq, Tru)), (res_aa, (Eq, Gen))],
blanchet@40997
   693
   [(aa1, (Eq, Fls)), (aa2, (Neq, Gen)), (res_aa, (Eq, Gen))],
blanchet@40997
   694
   [(aa1, (Eq, Fls)), (aa2, (Neq, New)), (res_aa, (Eq, Gen))]]
blanchet@40997
   695
blanchet@41003
   696
val meta_conj_triple = ("\<and>", conj_clauses, @{const Pure.conjunction})
blanchet@41003
   697
val meta_imp_triple = ("\<implies>", imp_clauses, @{const "==>"})
blanchet@41003
   698
val conj_triple = ("\<and>", conj_clauses, @{const conj})
blanchet@41003
   699
val disj_triple = ("\<or>", disj_clauses, @{const disj})
blanchet@41003
   700
val imp_triple = ("\<implies>", imp_clauses, @{const implies})
blanchet@41003
   701
blanchet@40999
   702
fun add_annotation_clause_from_quasi_clause _ NONE = NONE
blanchet@40999
   703
  | add_annotation_clause_from_quasi_clause [] accum = accum
blanchet@40999
   704
  | add_annotation_clause_from_quasi_clause ((aa, (cmp, a)) :: rest) accum =
blanchet@40999
   705
    case aa of
blanchet@40999
   706
      A a' => if annotation_comp cmp a' a then NONE
blanchet@40999
   707
              else add_annotation_clause_from_quasi_clause rest accum
blanchet@40999
   708
    | V x => add_annotation_clause_from_quasi_clause rest accum
blanchet@40999
   709
             |> Option.map (cons (x, (sign_for_comp_op cmp, a)))
blanchet@40995
   710
blanchet@41000
   711
fun assign_clause_from_quasi_clause unless =
blanchet@41000
   712
  add_annotation_clause_from_quasi_clause unless (SOME [])
blanchet@40995
   713
blanchet@40997
   714
fun add_connective_var conn mk_quasi_clauses res_aa aa1 aa2 =
blanchet@40997
   715
  (trace_msg (fn () => "*** Add " ^ string_for_annotation_atom res_aa ^ " = " ^
blanchet@40997
   716
                       string_for_annotation_atom aa1 ^ " " ^ conn ^ " " ^
blanchet@40997
   717
                       string_for_annotation_atom aa2);
blanchet@40999
   718
   fold (add_assign_clause o assign_clause_from_quasi_clause)
blanchet@40999
   719
        (mk_quasi_clauses res_aa aa1 aa2))
blanchet@40997
   720
fun add_connective_frames conn mk_quasi_clauses res_frame frame1 frame2 =
blanchet@40997
   721
  fold I (map3 (fn (_, res_aa) => fn (_, aa1) => fn (_, aa2) =>
blanchet@40997
   722
                   add_connective_var conn mk_quasi_clauses res_aa aa1 aa2)
blanchet@40997
   723
               res_frame frame1 frame2)
blanchet@40995
   724
blanchet@40998
   725
fun kill_unused_in_frame is_in (accum as ({frame, ...}, _)) =
blanchet@40998
   726
  let val (used_frame, unused_frame) = List.partition is_in frame in
blanchet@40998
   727
    accum |>> set_frame used_frame
blanchet@40998
   728
          ||> add_comp_frame (A Gen) Eq unused_frame
blanchet@40998
   729
  end
blanchet@40998
   730
blanchet@40998
   731
fun split_frame is_in_fun (gamma as {frame, ...}, cset) =
blanchet@40998
   732
  let
blanchet@40998
   733
    fun bubble fun_frame arg_frame [] cset =
blanchet@40998
   734
        ((rev fun_frame, rev arg_frame), cset)
blanchet@40998
   735
      | bubble fun_frame arg_frame ((bound as (_, aa)) :: rest) cset =
blanchet@40998
   736
        if is_in_fun bound then
blanchet@40998
   737
          bubble (bound :: fun_frame) arg_frame rest
blanchet@40998
   738
                 (cset |> add_comp_frame aa Leq arg_frame)
blanchet@40998
   739
        else
blanchet@40998
   740
          bubble fun_frame (bound :: arg_frame) rest cset
blanchet@40998
   741
  in cset |> bubble [] [] frame ||> pair gamma end
blanchet@40998
   742
blanchet@40998
   743
fun add_annotation_atom_comp_alt _ (A Gen) _ _ = I
blanchet@40998
   744
  | add_annotation_atom_comp_alt _ (A _) _ _ =
blanchet@40998
   745
    (trace_msg (K "*** Expected G"); raise UNSOLVABLE ())
blanchet@40998
   746
  | add_annotation_atom_comp_alt cmp (V x) aa1 aa2 =
blanchet@40998
   747
    add_annotation_atom_comp cmp [x] aa1 aa2
blanchet@40998
   748
blanchet@40999
   749
fun add_arg_order1 ((_, aa), (_, prev_aa)) = I
blanchet@40998
   750
  add_annotation_atom_comp_alt Neq prev_aa (A Gen) aa
blanchet@40999
   751
fun add_app1 fun_aa ((_, res_aa), (_, arg_aa)) = I
blanchet@40999
   752
  let
blanchet@40999
   753
    val clause = [(arg_aa, (Eq, New)), (res_aa, (Eq, Gen))]
blanchet@40999
   754
                 |> assign_clause_from_quasi_clause
blanchet@40999
   755
  in
blanchet@40999
   756
    trace_msg (fn () => "*** Add " ^ string_for_assign_clause clause);
blanchet@40999
   757
    apsnd (add_assign_clause clause)
blanchet@40999
   758
    #> add_annotation_atom_comp_alt Leq arg_aa fun_aa res_aa
blanchet@40999
   759
  end
blanchet@40998
   760
fun add_app _ [] [] = I
blanchet@40998
   761
  | add_app fun_aa res_frame arg_frame =
blanchet@40998
   762
    add_comp_frame (A New) Leq arg_frame
blanchet@40998
   763
    #> fold add_arg_order1 (tl arg_frame ~~ (fst (split_last arg_frame)))
blanchet@40998
   764
    #> fold (add_app1 fun_aa) (res_frame ~~ arg_frame)
blanchet@40998
   765
blanchet@41003
   766
fun consider_connective mdata (conn, mk_quasi_clauses, t0) do_t1 do_t2
blanchet@41003
   767
                        (accum as ({frame, ...}, _)) =
blanchet@41003
   768
  let
blanchet@41003
   769
    val mtype_for = fresh_mtype_for_type mdata false
blanchet@41003
   770
    val frame1 = fresh_frame mdata (SOME Tru) NONE frame
blanchet@41003
   771
    val frame2 = fresh_frame mdata (SOME Fls) NONE frame
blanchet@41003
   772
    val (m1, accum) = accum |>> set_frame frame1 |> do_t1
blanchet@41003
   773
    val (m2, accum) = accum |>> set_frame frame2 |> do_t2
blanchet@41003
   774
  in
blanchet@41003
   775
    (MApp (MApp (MRaw (t0, mtype_for (fastype_of t0)), m1), m2),
blanchet@41003
   776
     accum |>> set_frame frame
blanchet@41003
   777
           ||> apsnd (add_connective_frames conn mk_quasi_clauses frame frame1
blanchet@41003
   778
                                            frame2))
blanchet@41003
   779
  end
blanchet@41003
   780
blanchet@39359
   781
fun consider_term (mdata as {hol_ctxt = {thy, ctxt, stds, ...}, alpha_T,
blanchet@39359
   782
                             max_fresh, ...}) =
blanchet@33192
   783
  let
blanchet@37476
   784
    fun is_enough_eta_expanded t =
blanchet@37476
   785
      case strip_comb t of
blanchet@39359
   786
        (Const x, ts) => the_default 0 (arity_of_built_in_const thy stds x)
blanchet@37476
   787
        <= length ts
blanchet@37476
   788
      | _ => true
blanchet@35672
   789
    val mtype_for = fresh_mtype_for_type mdata false
blanchet@35385
   790
    fun do_all T (gamma, cset) =
blanchet@33192
   791
      let
blanchet@35385
   792
        val abs_M = mtype_for (domain_type (domain_type T))
blanchet@35386
   793
        val body_M = mtype_for (body_type T)
blanchet@33192
   794
      in
blanchet@40985
   795
        (MFun (MFun (abs_M, A Gen, body_M), A Gen, body_M),
blanchet@41000
   796
         (gamma, cset |> add_mtype_is_complete [] abs_M))
blanchet@33192
   797
      end
blanchet@33192
   798
    fun do_equals T (gamma, cset) =
blanchet@40997
   799
      let
blanchet@40997
   800
        val M = mtype_for (domain_type T)
blanchet@40997
   801
        val aa = V (Unsynchronized.inc max_fresh)
blanchet@40997
   802
      in
blanchet@40997
   803
        (MFun (M, A Gen, MFun (M, aa, mtype_for (nth_range_type 2 T))),
blanchet@41000
   804
         (gamma, cset |> add_mtype_is_concrete [] M
blanchet@40997
   805
                      |> add_annotation_atom_comp Leq [] (A Fls) aa))
blanchet@33192
   806
      end
blanchet@33192
   807
    fun do_robust_set_operation T (gamma, cset) =
blanchet@33192
   808
      let
blanchet@33192
   809
        val set_T = domain_type T
blanchet@35385
   810
        val M1 = mtype_for set_T
blanchet@35385
   811
        val M2 = mtype_for set_T
blanchet@35385
   812
        val M3 = mtype_for set_T
blanchet@33192
   813
      in
blanchet@40985
   814
        (MFun (M1, A Gen, MFun (M2, A Gen, M3)),
blanchet@35385
   815
         (gamma, cset |> add_is_sub_mtype M1 M3 |> add_is_sub_mtype M2 M3))
blanchet@33192
   816
      end
blanchet@33192
   817
    fun do_fragile_set_operation T (gamma, cset) =
blanchet@33192
   818
      let
blanchet@33192
   819
        val set_T = domain_type T
blanchet@35385
   820
        val set_M = mtype_for set_T
blanchet@35665
   821
        fun custom_mtype_for (T as Type (@{type_name fun}, [T1, T2])) =
blanchet@35385
   822
            if T = set_T then set_M
blanchet@40985
   823
            else MFun (custom_mtype_for T1, A Gen, custom_mtype_for T2)
blanchet@35385
   824
          | custom_mtype_for T = mtype_for T
blanchet@33192
   825
      in
blanchet@41000
   826
        (custom_mtype_for T, (gamma, cset |> add_mtype_is_concrete [] set_M))
blanchet@33192
   827
      end
blanchet@33192
   828
    fun do_pair_constr T accum =
blanchet@35385
   829
      case mtype_for (nth_range_type 2 T) of
blanchet@35385
   830
        M as MPair (a_M, b_M) =>
blanchet@40985
   831
        (MFun (a_M, A Gen, MFun (b_M, A Gen, M)), accum)
blanchet@35665
   832
      | M => raise MTYPE ("Nitpick_Mono.consider_term.do_pair_constr", [M], [])
blanchet@33192
   833
    fun do_nth_pair_sel n T =
blanchet@35385
   834
      case mtype_for (domain_type T) of
blanchet@35385
   835
        M as MPair (a_M, b_M) =>
blanchet@40985
   836
        pair (MFun (M, A Gen, if n = 0 then a_M else b_M))
blanchet@35665
   837
      | M => raise MTYPE ("Nitpick_Mono.consider_term.do_nth_pair_sel", [M], [])
blanchet@41003
   838
    and do_connect triple t1 t2 =
blanchet@41003
   839
      consider_connective mdata triple (do_term t1) (do_term t2)
blanchet@40998
   840
    and do_term t
blanchet@40998
   841
            (accum as (gamma as {bound_Ts, bound_Ms, frame, frees, consts},
blanchet@40998
   842
                       cset)) =
blanchet@40998
   843
      (trace_msg (fn () => "  " ^ string_for_mcontext ctxt t gamma ^
blanchet@40998
   844
                           " \<turnstile> " ^ Syntax.string_of_term ctxt t ^
blanchet@40998
   845
                           " : _?");
blanchet@40993
   846
       case t of
blanchet@40994
   847
         @{const False} =>
blanchet@40998
   848
         (MRaw (t, bool_M), accum ||> add_comp_frame (A Fls) Leq frame)
blanchet@41009
   849
       | Const (@{const_name None}, _) =>
blanchet@41009
   850
         (MRaw (t, bool_M), accum ||> add_comp_frame (A Fls) Leq frame)
blanchet@40994
   851
       | @{const True} =>
blanchet@40998
   852
         (MRaw (t, bool_M), accum ||> add_comp_frame (A Tru) Leq frame)
blanchet@40994
   853
       | Const (x as (s, T)) =>
blanchet@40993
   854
         (case AList.lookup (op =) consts x of
blanchet@40993
   855
            SOME M => (M, accum)
blanchet@40993
   856
          | NONE =>
blanchet@40994
   857
            if not (could_exist_alpha_subtype alpha_T T) then
blanchet@40994
   858
              (mtype_for T, accum)
blanchet@40994
   859
            else case s of
blanchet@40994
   860
              @{const_name all} => do_all T accum
blanchet@40994
   861
            | @{const_name "=="} => do_equals T accum
blanchet@40994
   862
            | @{const_name All} => do_all T accum
blanchet@40994
   863
            | @{const_name Ex} =>
blanchet@40994
   864
              let val set_T = domain_type T in
blanchet@40994
   865
                do_term (Abs (Name.uu, set_T,
blanchet@40994
   866
                              @{const Not} $ (HOLogic.mk_eq
blanchet@40994
   867
                                  (Abs (Name.uu, domain_type set_T,
blanchet@40994
   868
                                        @{const False}),
blanchet@40994
   869
                                   Bound 0)))) accum
blanchet@40994
   870
                |>> mtype_of_mterm
blanchet@40994
   871
              end
blanchet@40994
   872
            | @{const_name HOL.eq} => do_equals T accum
blanchet@40994
   873
            | @{const_name The} =>
blanchet@40994
   874
              (trace_msg (K "*** The"); raise UNSOLVABLE ())
blanchet@40994
   875
            | @{const_name Eps} =>
blanchet@40994
   876
              (trace_msg (K "*** Eps"); raise UNSOLVABLE ())
blanchet@40994
   877
            | @{const_name If} =>
blanchet@40994
   878
              do_robust_set_operation (range_type T) accum
blanchet@40994
   879
              |>> curry3 MFun bool_M (A Gen)
blanchet@40994
   880
            | @{const_name Pair} => do_pair_constr T accum
blanchet@40994
   881
            | @{const_name fst} => do_nth_pair_sel 0 T accum
blanchet@40994
   882
            | @{const_name snd} => do_nth_pair_sel 1 T accum
blanchet@40994
   883
            | @{const_name Id} =>
blanchet@40994
   884
              (MFun (mtype_for (domain_type T), A Gen, bool_M), accum)
blanchet@40994
   885
            | @{const_name converse} =>
blanchet@40994
   886
              let
blanchet@40994
   887
                val x = Unsynchronized.inc max_fresh
blanchet@40994
   888
                fun mtype_for_set T =
blanchet@40994
   889
                  MFun (mtype_for (domain_type T), V x, bool_M)
blanchet@40994
   890
                val ab_set_M = domain_type T |> mtype_for_set
blanchet@40994
   891
                val ba_set_M = range_type T |> mtype_for_set
blanchet@41011
   892
              in
blanchet@41011
   893
                (MFun (ab_set_M, A Gen, ba_set_M),
blanchet@41011
   894
                 accum ||> add_annotation_atom_comp Neq [] (V x) (A New))
blanchet@41011
   895
              end
blanchet@40994
   896
            | @{const_name trancl} => do_fragile_set_operation T accum
blanchet@40994
   897
            | @{const_name rel_comp} =>
blanchet@40994
   898
              let
blanchet@40994
   899
                val x = Unsynchronized.inc max_fresh
blanchet@40994
   900
                fun mtype_for_set T =
blanchet@40994
   901
                  MFun (mtype_for (domain_type T), V x, bool_M)
blanchet@40994
   902
                val bc_set_M = domain_type T |> mtype_for_set
blanchet@40994
   903
                val ab_set_M = domain_type (range_type T) |> mtype_for_set
blanchet@40994
   904
                val ac_set_M = nth_range_type 2 T |> mtype_for_set
blanchet@40994
   905
              in
blanchet@40994
   906
                (MFun (bc_set_M, A Gen, MFun (ab_set_M, A Gen, ac_set_M)),
blanchet@41011
   907
                 accum ||> add_annotation_atom_comp Neq [] (V x) (A New))
blanchet@40994
   908
              end
blanchet@40994
   909
            | @{const_name image} =>
blanchet@40994
   910
              let
blanchet@41011
   911
                val x = Unsynchronized.inc max_fresh
blanchet@40994
   912
                val a_M = mtype_for (domain_type (domain_type T))
blanchet@40994
   913
                val b_M = mtype_for (range_type (domain_type T))
blanchet@40994
   914
              in
blanchet@40994
   915
                (MFun (MFun (a_M, A Gen, b_M), A Gen,
blanchet@41011
   916
                       MFun (MFun (a_M, V x, bool_M), A Gen,
blanchet@41011
   917
                             MFun (b_M, V x, bool_M))),
blanchet@41011
   918
                 accum ||> add_annotation_atom_comp Neq [] (V x) (A New))
blanchet@40994
   919
              end
blanchet@40994
   920
            | @{const_name finite} =>
blanchet@41011
   921
              let
blanchet@41011
   922
                val M1 = mtype_for (domain_type (domain_type T))
blanchet@41011
   923
                val a = if exists_alpha_sub_mtype M1 then Fls else Gen
blanchet@41011
   924
              in (MFun (MFun (M1, A a, bool_M), A Gen, bool_M), accum) end
blanchet@40994
   925
            | @{const_name Sigma} =>
blanchet@40994
   926
              let
blanchet@40994
   927
                val x = Unsynchronized.inc max_fresh
blanchet@40994
   928
                fun mtype_for_set T =
blanchet@40994
   929
                  MFun (mtype_for (domain_type T), V x, bool_M)
blanchet@40994
   930
                val a_set_T = domain_type T
blanchet@40994
   931
                val a_M = mtype_for (domain_type a_set_T)
blanchet@40994
   932
                val b_set_M =
blanchet@40994
   933
                  mtype_for_set (range_type (domain_type (range_type T)))
blanchet@40994
   934
                val a_set_M = mtype_for_set a_set_T
blanchet@40994
   935
                val a_to_b_set_M = MFun (a_M, A Gen, b_set_M)
blanchet@40994
   936
                val ab_set_M = mtype_for_set (nth_range_type 2 T)
blanchet@40994
   937
              in
blanchet@40994
   938
                (MFun (a_set_M, A Gen, MFun (a_to_b_set_M, A Gen, ab_set_M)),
blanchet@41011
   939
                 accum ||> add_annotation_atom_comp Neq [] (V x) (A New))
blanchet@40994
   940
              end
blanchet@40993
   941
            | _ =>
blanchet@40994
   942
              if s = @{const_name safe_The} then
blanchet@33192
   943
                let
blanchet@40994
   944
                  val a_set_M = mtype_for (domain_type T)
blanchet@40994
   945
                  val a_M = dest_MFun a_set_M |> #1
blanchet@40994
   946
                in (MFun (a_set_M, A Gen, a_M), accum) end
blanchet@40994
   947
              else if s = @{const_name ord_class.less_eq} andalso
blanchet@40994
   948
                      is_set_type (domain_type T) then
blanchet@40994
   949
                do_fragile_set_operation T accum
blanchet@40994
   950
              else if is_sel s then
blanchet@40994
   951
                (mtype_for_sel mdata x, accum)
blanchet@40994
   952
              else if is_constr ctxt stds x then
blanchet@40994
   953
                (mtype_for_constr mdata x, accum)
blanchet@40994
   954
              else if is_built_in_const thy stds x then
blanchet@40994
   955
                (fresh_mtype_for_type mdata true T, accum)
blanchet@40994
   956
              else
blanchet@40994
   957
                let val M = mtype_for T in
blanchet@40998
   958
                  (M, ({bound_Ts = bound_Ts, bound_Ms = bound_Ms, frame = frame,
blanchet@40998
   959
                        frees = frees, consts = (x, M) :: consts}, cset))
blanchet@40994
   960
                end)
blanchet@40994
   961
           |>> curry MRaw t
blanchet@40998
   962
           ||> apsnd (add_comp_frame (A Gen) Eq frame)
blanchet@33192
   963
         | Free (x as (_, T)) =>
blanchet@33192
   964
           (case AList.lookup (op =) frees x of
blanchet@35385
   965
              SOME M => (M, accum)
blanchet@33192
   966
            | NONE =>
blanchet@35385
   967
              let val M = mtype_for T in
blanchet@40998
   968
                (M, ({bound_Ts = bound_Ts, bound_Ms = bound_Ms, frame = frame,
blanchet@40998
   969
                      frees = (x, M) :: frees, consts = consts}, cset))
blanchet@40994
   970
              end)
blanchet@40998
   971
           |>> curry MRaw t ||> apsnd (add_comp_frame (A Gen) Eq frame)
blanchet@38179
   972
         | Var _ => (trace_msg (K "*** Var"); raise UNSOLVABLE ())
blanchet@40994
   973
         | Bound j =>
blanchet@40994
   974
           (MRaw (t, nth bound_Ms j),
blanchet@40998
   975
            accum ||> add_bound_frame (length bound_Ts - j - 1) frame)
blanchet@35385
   976
         | Abs (s, T, t') =>
blanchet@35665
   977
           (case fin_fun_body T (fastype_of1 (T :: bound_Ts, t')) t' of
blanchet@35665
   978
              SOME t' =>
blanchet@35665
   979
              let
blanchet@35665
   980
                val M = mtype_for T
blanchet@40993
   981
                val (m', accum) = do_term t' (accum |>> push_bound (A Fls) T M)
blanchet@40993
   982
              in (MAbs (s, T, M, A Fls, m'), accum |>> pop_bound) end
blanchet@35665
   983
            | NONE =>
blanchet@35665
   984
              ((case t' of
blanchet@35665
   985
                  t1' $ Bound 0 =>
blanchet@37476
   986
                  if not (loose_bvar1 (t1', 0)) andalso
blanchet@37476
   987
                     is_enough_eta_expanded t1' then
blanchet@35665
   988
                    do_term (incr_boundvars ~1 t1') accum
blanchet@35665
   989
                  else
blanchet@35665
   990
                    raise SAME ()
haftmann@38864
   991
                | (t11 as Const (@{const_name HOL.eq}, _)) $ Bound 0 $ t13 =>
blanchet@37476
   992
                  if not (loose_bvar1 (t13, 0)) then
blanchet@37476
   993
                    do_term (incr_boundvars ~1 (t11 $ t13)) accum
blanchet@37476
   994
                  else
blanchet@37476
   995
                    raise SAME ()
blanchet@35665
   996
                | _ => raise SAME ())
blanchet@35665
   997
               handle SAME () =>
blanchet@35665
   998
                      let
blanchet@35665
   999
                        val M = mtype_for T
blanchet@40993
  1000
                        val aa = V (Unsynchronized.inc max_fresh)
blanchet@40993
  1001
                        val (m', accum) =
blanchet@40993
  1002
                          do_term t' (accum |>> push_bound aa T M)
blanchet@40993
  1003
                      in (MAbs (s, T, M, aa, m'), accum |>> pop_bound) end))
blanchet@41003
  1004
         | @{const Not} $ t1 => do_connect imp_triple t1 @{const False} accum
blanchet@41003
  1005
         | @{const conj} $ t1 $ t2 => do_connect conj_triple t1 t2 accum
blanchet@41003
  1006
         | @{const disj} $ t1 $ t2 => do_connect disj_triple t1 t2 accum
blanchet@41003
  1007
         | @{const implies} $ t1 $ t2 => do_connect imp_triple t1 t2 accum
blanchet@33192
  1008
         | Const (@{const_name Let}, _) $ t1 $ t2 =>
blanchet@33192
  1009
           do_term (betapply (t2, t1)) accum
blanchet@33192
  1010
         | t1 $ t2 =>
blanchet@33192
  1011
           let
blanchet@40998
  1012
             fun is_in t (j, _) = loose_bvar1 (t, length bound_Ts - j - 1)
blanchet@40998
  1013
             val accum as ({frame, ...}, _) =
blanchet@40998
  1014
               accum |> kill_unused_in_frame (is_in t)
blanchet@40998
  1015
             val ((frame1a, frame1b), accum) = accum |> split_frame (is_in t1)
blanchet@40998
  1016
             val frame2a = frame1a |> map (apsnd (K (A Gen)))
blanchet@40998
  1017
             val frame2b =
blanchet@40998
  1018
               frame1b |> map (apsnd (fn _ => V (Unsynchronized.inc max_fresh)))
blanchet@40998
  1019
             val frame2 = frame2a @ frame2b
blanchet@40998
  1020
             val (m1, accum) = accum |>> set_frame frame1a |> do_term t1
blanchet@40998
  1021
             val (m2, accum) = accum |>> set_frame frame2 |> do_term t2
blanchet@33192
  1022
           in
blanchet@35812
  1023
             let
blanchet@40998
  1024
               val (M11, aa, _) = mtype_of_mterm m1 |> dest_MFun
blanchet@35812
  1025
               val M2 = mtype_of_mterm m2
blanchet@40998
  1026
             in
blanchet@40998
  1027
               (MApp (m1, m2),
blanchet@40998
  1028
                accum |>> set_frame frame
blanchet@40998
  1029
                      ||> add_is_sub_mtype M2 M11
blanchet@40998
  1030
                      ||> add_app aa frame1b frame2b)
blanchet@40998
  1031
             end
blanchet@33192
  1032
           end)
blanchet@40998
  1033
        |> tap (fn (m, (gamma, _)) =>
blanchet@40998
  1034
                   trace_msg (fn () => "  " ^ string_for_mcontext ctxt t gamma ^
blanchet@40998
  1035
                                       " \<turnstile> " ^
blanchet@40998
  1036
                                       string_for_mterm ctxt m))
blanchet@33192
  1037
  in do_term end
blanchet@33192
  1038
blanchet@41001
  1039
fun force_gen_funs 0 _ = I
blanchet@41001
  1040
  | force_gen_funs n (M as MFun (M1, _, M2)) =
blanchet@41001
  1041
    add_mtypes_equal M (MFun (M1, A Gen, M2)) #> force_gen_funs (n - 1) M2
blanchet@41001
  1042
  | force_gen_funs _ M = raise MTYPE ("Nitpick_Mono.force_gen_funs", [M], [])
blanchet@35665
  1043
fun consider_general_equals mdata def (x as (_, T)) t1 t2 accum =
blanchet@35386
  1044
  let
blanchet@35386
  1045
    val (m1, accum) = consider_term mdata t1 accum
blanchet@35386
  1046
    val (m2, accum) = consider_term mdata t2 accum
blanchet@35386
  1047
    val M1 = mtype_of_mterm m1
blanchet@35386
  1048
    val M2 = mtype_of_mterm m2
blanchet@35665
  1049
    val accum = accum ||> add_mtypes_equal M1 M2
blanchet@35672
  1050
    val body_M = fresh_mtype_for_type mdata false (nth_range_type 2 T)
blanchet@35665
  1051
    val m = MApp (MApp (MRaw (Const x,
blanchet@41001
  1052
                           MFun (M1, A Gen, MFun (M2, A Fls, body_M))), m1), m2)
blanchet@35386
  1053
  in
blanchet@35665
  1054
    (m, if def then
blanchet@35665
  1055
          let val (head_m, arg_ms) = strip_mcomb m1 in
blanchet@41001
  1056
            accum ||> force_gen_funs (length arg_ms) (mtype_of_mterm head_m)
blanchet@35665
  1057
          end
blanchet@35665
  1058
        else
blanchet@35665
  1059
          accum)
blanchet@35386
  1060
  end
blanchet@35386
  1061
blanchet@41000
  1062
fun consider_general_formula (mdata as {hol_ctxt = {ctxt, ...}, max_fresh,
blanchet@41000
  1063
                                        ...}) =
blanchet@33192
  1064
  let
blanchet@35672
  1065
    val mtype_for = fresh_mtype_for_type mdata false
blanchet@35386
  1066
    val do_term = consider_term mdata
blanchet@40998
  1067
    fun do_formula sn t (accum as (gamma, _)) =
blanchet@41000
  1068
      let
blanchet@41000
  1069
        fun do_quantifier (quant_x as (quant_s, _)) abs_s abs_T body_t =
blanchet@41000
  1070
          let
blanchet@41000
  1071
            val abs_M = mtype_for abs_T
blanchet@41000
  1072
            val x = Unsynchronized.inc max_fresh
blanchet@41000
  1073
            val side_cond = ((sn = Minus) = (quant_s = @{const_name Ex}))
blanchet@41001
  1074
            fun ann () = if quant_s = @{const_name Ex} then Fls else Tru
blanchet@41000
  1075
            val (body_m, accum) =
blanchet@41000
  1076
              accum ||> side_cond
blanchet@41005
  1077
                        ? add_mtype_is_complete [(x, (Plus, ann ()))] abs_M
blanchet@41000
  1078
                    |>> push_bound (V x) abs_T abs_M |> do_formula sn body_t
blanchet@41000
  1079
            val body_M = mtype_of_mterm body_m
blanchet@41000
  1080
          in
blanchet@41000
  1081
            (MApp (MRaw (Const quant_x,
blanchet@41000
  1082
                         MFun (MFun (abs_M, A Gen, body_M), A Gen, body_M)),
blanchet@41000
  1083
                   MAbs (abs_s, abs_T, abs_M, A Gen, body_m)),
blanchet@41000
  1084
             accum |>> pop_bound)
blanchet@41000
  1085
          end
blanchet@41003
  1086
        fun do_connect triple neg1 t1 t2 =
blanchet@41003
  1087
          consider_connective mdata triple
blanchet@41003
  1088
              (do_formula (sn |> neg1 ? negate_sign) t1) (do_formula sn t2)
blanchet@41000
  1089
        fun do_equals x t1 t2 =
blanchet@41000
  1090
          case sn of
blanchet@41000
  1091
            Plus => do_term t accum
blanchet@41000
  1092
          | Minus => consider_general_equals mdata false x t1 t2 accum
blanchet@41000
  1093
      in
blanchet@41004
  1094
        trace_msg (fn () => "  " ^ string_for_mcontext ctxt t gamma ^
blanchet@41004
  1095
                            " \<turnstile> " ^ Syntax.string_of_term ctxt t ^
blanchet@41004
  1096
                            " : o\<^sup>" ^ string_for_sign sn ^ "?");
blanchet@41004
  1097
        case t of
blanchet@41004
  1098
          Const (x as (@{const_name all}, _)) $ Abs (s1, T1, t1) =>
blanchet@41004
  1099
          do_quantifier x s1 T1 t1
blanchet@41004
  1100
        | Const (x as (@{const_name "=="}, _)) $ t1 $ t2 => do_equals x t1 t2
blanchet@41004
  1101
        | @{const Trueprop} $ t1 =>
blanchet@41004
  1102
          let val (m1, accum) = do_formula sn t1 accum in
blanchet@41004
  1103
            (MApp (MRaw (@{const Trueprop}, mtype_for (bool_T --> prop_T)), m1),
blanchet@41004
  1104
             accum)
blanchet@41004
  1105
          end
blanchet@41004
  1106
        | Const (x as (@{const_name All}, _)) $ Abs (s1, T1, t1) =>
blanchet@41004
  1107
          do_quantifier x s1 T1 t1
blanchet@41004
  1108
        | Const (x0 as (@{const_name Ex}, T0)) $ (t1 as Abs (s1, T1, t1')) =>
blanchet@41004
  1109
          (case sn of
blanchet@41004
  1110
             Plus => do_quantifier x0 s1 T1 t1'
blanchet@41004
  1111
           | Minus =>
blanchet@41004
  1112
             (* FIXME: Move elsewhere *)
blanchet@41004
  1113
             do_term (@{const Not}
blanchet@41004
  1114
                      $ (HOLogic.eq_const (domain_type T0) $ t1
blanchet@41004
  1115
                         $ Abs (Name.uu, T1, @{const False}))) accum)
blanchet@41004
  1116
        | Const (x as (@{const_name HOL.eq}, _)) $ t1 $ t2 => do_equals x t1 t2
blanchet@41004
  1117
        | Const (@{const_name Let}, _) $ t1 $ t2 =>
blanchet@41004
  1118
          do_formula sn (betapply (t2, t1)) accum
blanchet@41004
  1119
        | @{const Pure.conjunction} $ t1 $ t2 =>
blanchet@41004
  1120
          do_connect meta_conj_triple false t1 t2 accum
blanchet@41004
  1121
        | @{const "==>"} $ t1 $ t2 =>
blanchet@41004
  1122
          do_connect meta_imp_triple true t1 t2 accum
blanchet@41004
  1123
        | @{const Not} $ t1 =>
blanchet@41004
  1124
          do_connect imp_triple true t1 @{const False} accum
blanchet@41004
  1125
        | @{const conj} $ t1 $ t2 => do_connect conj_triple false t1 t2 accum
blanchet@41004
  1126
        | @{const disj} $ t1 $ t2 => do_connect disj_triple false t1 t2 accum
blanchet@41004
  1127
        | @{const implies} $ t1 $ t2 => do_connect imp_triple true t1 t2 accum
blanchet@41004
  1128
        | _ => do_term t accum
blanchet@41000
  1129
      end
blanchet@41000
  1130
      |> tap (fn (m, (gamma, _)) =>
blanchet@41000
  1131
                 trace_msg (fn () => string_for_mcontext ctxt t gamma ^
blanchet@41000
  1132
                                     " \<turnstile> " ^
blanchet@41000
  1133
                                     string_for_mterm ctxt m ^ " : o\<^sup>" ^
blanchet@41000
  1134
                                     string_for_sign sn))
blanchet@33192
  1135
  in do_formula end
blanchet@33192
  1136
blanchet@33192
  1137
(* The harmless axiom optimization below is somewhat too aggressive in the face
blanchet@33192
  1138
   of (rather peculiar) user-defined axioms. *)
blanchet@33192
  1139
val harmless_consts =
blanchet@33192
  1140
  [@{const_name ord_class.less}, @{const_name ord_class.less_eq}]
blanchet@33192
  1141
val bounteous_consts = [@{const_name bisim}]
blanchet@33192
  1142
blanchet@35665
  1143
fun is_harmless_axiom ({no_harmless = true, ...} : mdata) _ = false
blanchet@39359
  1144
  | is_harmless_axiom {hol_ctxt = {thy, stds, ...}, ...} t =
blanchet@35665
  1145
    Term.add_consts t []
blanchet@39359
  1146
    |> filter_out (is_built_in_const thy stds)
blanchet@35665
  1147
    |> (forall (member (op =) harmless_consts o original_name o fst) orf
blanchet@35665
  1148
        exists (member (op =) bounteous_consts o fst))
blanchet@33192
  1149
blanchet@35665
  1150
fun consider_nondefinitional_axiom mdata t =
blanchet@35665
  1151
  if is_harmless_axiom mdata t then pair (MRaw (t, dummy_M))
blanchet@35386
  1152
  else consider_general_formula mdata Plus t
blanchet@33192
  1153
blanchet@37256
  1154
fun consider_definitional_axiom (mdata as {hol_ctxt = {ctxt, ...}, ...}) t =
blanchet@37256
  1155
  if not (is_constr_pattern_formula ctxt t) then
blanchet@35386
  1156
    consider_nondefinitional_axiom mdata t
blanchet@35665
  1157
  else if is_harmless_axiom mdata t then
blanchet@35386
  1158
    pair (MRaw (t, dummy_M))
blanchet@33192
  1159
  else
blanchet@33192
  1160
    let
blanchet@35672
  1161
      val mtype_for = fresh_mtype_for_type mdata false
blanchet@35386
  1162
      val do_term = consider_term mdata
blanchet@35386
  1163
      fun do_all quant_t abs_s abs_T body_t accum =
blanchet@35386
  1164
        let
blanchet@35386
  1165
          val abs_M = mtype_for abs_T
blanchet@35386
  1166
          val (body_m, accum) =
blanchet@40993
  1167
            accum |>> push_bound (A Gen) abs_T abs_M |> do_formula body_t
blanchet@35386
  1168
          val body_M = mtype_of_mterm body_m
blanchet@35386
  1169
        in
blanchet@40985
  1170
          (MApp (MRaw (quant_t, MFun (MFun (abs_M, A Gen, body_M), A Gen,
blanchet@40985
  1171
                       body_M)),
blanchet@40985
  1172
                 MAbs (abs_s, abs_T, abs_M, A Gen, body_m)),
blanchet@35386
  1173
           accum |>> pop_bound)
blanchet@33192
  1174
        end
blanchet@35386
  1175
      and do_conjunction t0 t1 t2 accum =
blanchet@33192
  1176
        let
blanchet@35386
  1177
          val (m1, accum) = do_formula t1 accum
blanchet@35386
  1178
          val (m2, accum) = do_formula t2 accum
blanchet@35386
  1179
        in
blanchet@35386
  1180
          (MApp (MApp (MRaw (t0, mtype_for (fastype_of t0)), m1), m2), accum)
blanchet@35386
  1181
        end
blanchet@35386
  1182
      and do_implies t0 t1 t2 accum =
blanchet@35386
  1183
        let
blanchet@35386
  1184
          val (m1, accum) = do_term t1 accum
blanchet@35386
  1185
          val (m2, accum) = do_formula t2 accum
blanchet@35386
  1186
        in
blanchet@35386
  1187
          (MApp (MApp (MRaw (t0, mtype_for (fastype_of t0)), m1), m2), accum)
blanchet@35386
  1188
        end
blanchet@35812
  1189
      and do_formula t accum =
blanchet@41002
  1190
        case t of
blanchet@41002
  1191
          (t0 as Const (@{const_name all}, _)) $ Abs (s1, T1, t1) =>
blanchet@41002
  1192
          do_all t0 s1 T1 t1 accum
blanchet@41002
  1193
        | @{const Trueprop} $ t1 =>
blanchet@41002
  1194
          let val (m1, accum) = do_formula t1 accum in
blanchet@41002
  1195
            (MApp (MRaw (@{const Trueprop}, mtype_for (bool_T --> prop_T)), m1),
blanchet@41002
  1196
             accum)
blanchet@41002
  1197
          end
blanchet@41002
  1198
        | Const (x as (@{const_name "=="}, _)) $ t1 $ t2 =>
blanchet@41002
  1199
          consider_general_equals mdata true x t1 t2 accum
blanchet@41002
  1200
        | (t0 as @{const "==>"}) $ t1 $ t2 => do_implies t0 t1 t2 accum
blanchet@41002
  1201
        | (t0 as @{const Pure.conjunction}) $ t1 $ t2 =>
blanchet@41002
  1202
          do_conjunction t0 t1 t2 accum
blanchet@41002
  1203
        | (t0 as Const (@{const_name All}, _)) $ Abs (s0, T1, t1) =>
blanchet@41002
  1204
          do_all t0 s0 T1 t1 accum
blanchet@41002
  1205
        | Const (x as (@{const_name HOL.eq}, _)) $ t1 $ t2 =>
blanchet@41002
  1206
          consider_general_equals mdata true x t1 t2 accum
blanchet@41002
  1207
        | (t0 as @{const conj}) $ t1 $ t2 => do_conjunction t0 t1 t2 accum
blanchet@41002
  1208
        | (t0 as @{const implies}) $ t1 $ t2 => do_implies t0 t1 t2 accum
blanchet@41002
  1209
        | _ => raise TERM ("Nitpick_Mono.consider_definitional_axiom.\
blanchet@41002
  1210
                           \do_formula", [t])
blanchet@33192
  1211
    in do_formula t end
blanchet@33192
  1212
blanchet@40989
  1213
fun string_for_mtype_of_term ctxt asgs t M =
blanchet@40989
  1214
  Syntax.string_of_term ctxt t ^ " : " ^ string_for_mtype (resolve_mtype asgs M)
blanchet@33192
  1215
blanchet@40998
  1216
fun print_mcontext ctxt asgs ({frees, consts, ...} : mcontext) =
blanchet@38179
  1217
  trace_msg (fn () =>
blanchet@40989
  1218
      map (fn (x, M) => string_for_mtype_of_term ctxt asgs (Free x) M) frees @
blanchet@40989
  1219
      map (fn (x, M) => string_for_mtype_of_term ctxt asgs (Const x) M) consts
blanchet@37476
  1220
      |> cat_lines)
blanchet@33192
  1221
blanchet@35665
  1222
fun amass f t (ms, accum) =
blanchet@35386
  1223
  let val (m, accum) = f t accum in (m :: ms, accum) end
blanchet@35386
  1224
blanchet@41007
  1225
fun infer which no_harmless (hol_ctxt as {ctxt, tac_timeout, ...}) binarize
blanchet@41007
  1226
          alpha_T (nondef_ts, def_ts) =
blanchet@33192
  1227
  let
blanchet@38179
  1228
    val _ = trace_msg (fn () => "****** " ^ which ^ " analysis: " ^
blanchet@38179
  1229
                                string_for_mtype MAlpha ^ " is " ^
blanchet@38179
  1230
                                Syntax.string_of_typ ctxt alpha_T)
blanchet@35665
  1231
    val mdata as {max_fresh, constr_mcache, ...} =
blanchet@35665
  1232
      initial_mdata hol_ctxt binarize no_harmless alpha_T
blanchet@40994
  1233
    val accum = (initial_gamma, ([], []))
blanchet@35386
  1234
    val (nondef_ms, accum) =
blanchet@35665
  1235
      ([], accum) |> amass (consider_general_formula mdata Plus) (hd nondef_ts)
blanchet@35665
  1236
                  |> fold (amass (consider_nondefinitional_axiom mdata))
blanchet@35386
  1237
                          (tl nondef_ts)
blanchet@35386
  1238
    val (def_ms, (gamma, cset)) =
blanchet@35665
  1239
      ([], accum) |> fold (amass (consider_definitional_axiom mdata)) def_ts
blanchet@33192
  1240
  in
blanchet@41007
  1241
    case solve tac_timeout (!max_fresh) cset of
blanchet@40998
  1242
      SOME asgs => (print_mcontext ctxt asgs gamma;
blanchet@40989
  1243
                    SOME (asgs, (nondef_ms, def_ms), !constr_mcache))
blanchet@35665
  1244
    | _ => NONE
blanchet@33192
  1245
  end
blanchet@35812
  1246
  handle UNSOLVABLE () => NONE
blanchet@35812
  1247
       | MTYPE (loc, Ms, Ts) =>
blanchet@35665
  1248
         raise BAD (loc, commas (map string_for_mtype Ms @
blanchet@35665
  1249
                                 map (Syntax.string_of_typ ctxt) Ts))
blanchet@35665
  1250
       | MTERM (loc, ms) =>
blanchet@35665
  1251
         raise BAD (loc, commas (map (string_for_mterm ctxt) ms))
blanchet@35665
  1252
blanchet@41001
  1253
val formulas_monotonic = is_some oooo infer "Monotonicity" false
blanchet@35665
  1254
blanchet@35665
  1255
fun fin_fun_constr T1 T2 =
blanchet@35665
  1256
  (@{const_name FinFun}, (T1 --> T2) --> Type (@{type_name fin_fun}, [T1, T2]))
blanchet@35665
  1257
blanchet@40993
  1258
fun finitize_funs (hol_ctxt as {thy, ctxt, stds, constr_cache, ...}) binarize
blanchet@41001
  1259
                  finitizes alpha_T tsp =
blanchet@41001
  1260
  case infer "Finiteness" true hol_ctxt binarize alpha_T tsp of
blanchet@40989
  1261
    SOME (asgs, msp, constr_mtypes) =>
blanchet@40989
  1262
    if forall (curry (op =) Gen o snd) asgs then
blanchet@35812
  1263
      tsp
blanchet@35812
  1264
    else
blanchet@35812
  1265
      let
blanchet@40988
  1266
        fun should_finitize T aa =
blanchet@35812
  1267
          case triple_lookup (type_match thy) finitizes T of
blanchet@35812
  1268
            SOME (SOME false) => false
blanchet@40989
  1269
          | _ => resolve_annotation_atom asgs aa = A Fls
blanchet@35812
  1270
        fun type_from_mtype T M =
blanchet@35812
  1271
          case (M, T) of
blanchet@35812
  1272
            (MAlpha, _) => T
blanchet@40988
  1273
          | (MFun (M1, aa, M2), Type (@{type_name fun}, Ts)) =>
blanchet@40988
  1274
            Type (if should_finitize T aa then @{type_name fin_fun}
blanchet@35812
  1275
                  else @{type_name fun}, map2 type_from_mtype Ts [M1, M2])
blanchet@38190
  1276
          | (MPair (M1, M2), Type (@{type_name prod}, Ts)) =>
blanchet@38190
  1277
            Type (@{type_name prod}, map2 type_from_mtype Ts [M1, M2])
blanchet@35812
  1278
          | (MType _, _) => T
blanchet@35812
  1279
          | _ => raise MTYPE ("Nitpick_Mono.finitize_funs.type_from_mtype",
blanchet@35812
  1280
                              [M], [T])
blanchet@35812
  1281
        fun finitize_constr (x as (s, T)) =
blanchet@35812
  1282
          (s, case AList.lookup (op =) constr_mtypes x of
blanchet@35812
  1283
                SOME M => type_from_mtype T M
blanchet@35812
  1284
              | NONE => T)
blanchet@37267
  1285
        fun term_from_mterm new_Ts old_Ts m =
blanchet@35812
  1286
          case m of
blanchet@35812
  1287
            MRaw (t, M) =>
blanchet@35812
  1288
            let
blanchet@37267
  1289
              val T = fastype_of1 (old_Ts, t)
blanchet@35812
  1290
              val T' = type_from_mtype T M
blanchet@35812
  1291
            in
blanchet@35812
  1292
              case t of
blanchet@35812
  1293
                Const (x as (s, _)) =>
blanchet@37476
  1294
                if s = @{const_name finite} then
blanchet@35812
  1295
                  case domain_type T' of
blanchet@35812
  1296
                    set_T' as Type (@{type_name fin_fun}, _) =>
blanchet@35812
  1297
                    Abs (Name.uu, set_T', @{const True})
blanchet@35812
  1298
                  | _ => Const (s, T')
blanchet@35812
  1299
                else if s = @{const_name "=="} orelse
haftmann@38864
  1300
                        s = @{const_name HOL.eq} then
blanchet@37476
  1301
                  let
blanchet@37476
  1302
                    val T =
blanchet@37476
  1303
                      case T' of
blanchet@37476
  1304
                        Type (_, [T1, Type (_, [T2, T3])]) =>
blanchet@37476
  1305
                        T1 --> T2 --> T3
blanchet@37476
  1306
                      | _ => raise TYPE ("Nitpick_Mono.finitize_funs.\
blanchet@37476
  1307
                                         \term_from_mterm", [T, T'], [])
blanchet@37476
  1308
                  in coerce_term hol_ctxt new_Ts T' T (Const (s, T)) end
blanchet@39359
  1309
                else if is_built_in_const thy stds x then
blanchet@37267
  1310
                  coerce_term hol_ctxt new_Ts T' T t
blanchet@37256
  1311
                else if is_constr ctxt stds x then
blanchet@35812
  1312
                  Const (finitize_constr x)
blanchet@35812
  1313
                else if is_sel s then
blanchet@35812
  1314
                  let
blanchet@35812
  1315
                    val n = sel_no_from_name s
blanchet@35812
  1316
                    val x' =
blanchet@35812
  1317
                      x |> binarized_and_boxed_constr_for_sel hol_ctxt binarize
blanchet@35812
  1318
                        |> finitize_constr
blanchet@35812
  1319
                    val x'' =
blanchet@35812
  1320
                      binarized_and_boxed_nth_sel_for_constr hol_ctxt binarize
blanchet@35812
  1321
                                                             x' n
blanchet@35812
  1322
                  in Const x'' end
blanchet@35812
  1323
                else
blanchet@35812
  1324
                  Const (s, T')
blanchet@35812
  1325
              | Free (s, T) => Free (s, type_from_mtype T M)
blanchet@35812
  1326
              | Bound _ => t
blanchet@35812
  1327
              | _ => raise MTERM ("Nitpick_Mono.finitize_funs.term_from_mterm",
blanchet@35812
  1328
                                  [m])
blanchet@35812
  1329
            end
blanchet@35812
  1330
          | MApp (m1, m2) =>
blanchet@35812
  1331
            let
blanchet@37267
  1332
              val (t1, t2) = pairself (term_from_mterm new_Ts old_Ts) (m1, m2)
blanchet@37267
  1333
              val (T1, T2) = pairself (curry fastype_of1 new_Ts) (t1, t2)
blanchet@35812
  1334
              val (t1', T2') =
blanchet@35812
  1335
                case T1 of
blanchet@39316
  1336
                  Type (s, [T11, T12]) =>
blanchet@35812
  1337
                  (if s = @{type_name fin_fun} then
blanchet@37256
  1338
                     select_nth_constr_arg ctxt stds (fin_fun_constr T11 T12) t1
blanchet@35812
  1339
                                           0 (T11 --> T12)
blanchet@35812
  1340
                   else
blanchet@35812
  1341
                     t1, T11)
blanchet@35812
  1342
                | _ => raise TYPE ("Nitpick_Mono.finitize_funs.term_from_mterm",
blanchet@35812
  1343
                                   [T1], [])
blanchet@37267
  1344
            in betapply (t1', coerce_term hol_ctxt new_Ts T2' T2 t2) end
blanchet@40988
  1345
          | MAbs (s, old_T, M, aa, m') =>
blanchet@35812
  1346
            let
blanchet@37267
  1347
              val new_T = type_from_mtype old_T M
blanchet@37267
  1348
              val t' = term_from_mterm (new_T :: new_Ts) (old_T :: old_Ts) m'
blanchet@37267
  1349
              val T' = fastype_of1 (new_T :: new_Ts, t')
blanchet@35812
  1350
            in
blanchet@37267
  1351
              Abs (s, new_T, t')
blanchet@40988
  1352
              |> should_finitize (new_T --> T') aa
blanchet@37267
  1353
                 ? construct_value ctxt stds (fin_fun_constr new_T T') o single
blanchet@35812
  1354
            end
blanchet@35812
  1355
      in
blanchet@35812
  1356
        Unsynchronized.change constr_cache (map (apsnd (map finitize_constr)));
blanchet@37267
  1357
        pairself (map (term_from_mterm [] [])) msp
blanchet@35812
  1358
      end
blanchet@35665
  1359
  | NONE => tsp
blanchet@33192
  1360
blanchet@33192
  1361
end;