src/HOL/Tools/Nitpick/nitpick_mono.ML
author blanchet
Mon Dec 06 13:30:36 2010 +0100 (2010-12-06)
changeset 40997 67e11a73532a
parent 40996 63112be4a469
child 40998 bcd23ddeecef
permissions -rw-r--r--
implemented connectives in new 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@40993
    14
    hol_context -> bool -> int -> typ -> term list * term list -> bool
blanchet@35665
    15
  val finitize_funs :
blanchet@40993
    16
    hol_context -> bool -> (typ option * bool option) list -> int -> 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@35665
   232
fun fin_fun_body _ _ (t as @{term False}) = SOME t
blanchet@35665
   233
  | fin_fun_body _ _ (t as Const (@{const_name None}, _)) = SOME t
blanchet@35665
   234
  | fin_fun_body dom_T ran_T
blanchet@35665
   235
                 ((t0 as Const (@{const_name If}, _))
haftmann@38864
   236
                  $ (t1 as Const (@{const_name HOL.eq}, _) $ Bound 0 $ t1')
blanchet@35665
   237
                  $ t2 $ t3) =
blanchet@35665
   238
    (if loose_bvar1 (t1', 0) then
blanchet@35665
   239
       NONE
blanchet@35665
   240
     else case fin_fun_body dom_T ran_T t3 of
blanchet@35665
   241
       NONE => NONE
blanchet@35665
   242
     | SOME t3 =>
blanchet@35665
   243
       SOME (t0 $ (Const (@{const_name is_unknown}, dom_T --> bool_T) $ t1')
blanchet@35665
   244
                $ (Const (@{const_name unknown}, ran_T)) $ (t0 $ t1 $ t2 $ t3)))
blanchet@35665
   245
  | fin_fun_body _ _ _ = NONE
blanchet@33192
   246
blanchet@35672
   247
fun fresh_mfun_for_fun_type (mdata as {max_fresh, ...} : mdata) all_minus
blanchet@35672
   248
                            T1 T2 =
blanchet@33192
   249
  let
blanchet@35672
   250
    val M1 = fresh_mtype_for_type mdata all_minus T1
blanchet@35672
   251
    val M2 = fresh_mtype_for_type mdata all_minus T2
blanchet@40988
   252
    val aa = if not all_minus andalso exists_alpha_sub_mtype_fresh M1 andalso
blanchet@40988
   253
                is_fin_fun_supported_type (body_type T2) then
blanchet@40988
   254
               V (Unsynchronized.inc max_fresh)
blanchet@40988
   255
             else
blanchet@40988
   256
               A Gen
blanchet@40988
   257
  in (M1, aa, M2) end
blanchet@37256
   258
and fresh_mtype_for_type (mdata as {hol_ctxt as {ctxt, ...}, binarize, alpha_T,
blanchet@35672
   259
                                    datatype_mcache, constr_mcache, ...})
blanchet@35672
   260
                         all_minus =
blanchet@35385
   261
  let
blanchet@35385
   262
    fun do_type T =
blanchet@33192
   263
      if T = alpha_T then
blanchet@35385
   264
        MAlpha
blanchet@33192
   265
      else case T of
blanchet@35665
   266
        Type (@{type_name fun}, [T1, T2]) =>
blanchet@39342
   267
        MFun (fresh_mfun_for_fun_type mdata all_minus T1 T2)
blanchet@38190
   268
      | Type (@{type_name prod}, [T1, T2]) => MPair (pairself do_type (T1, T2))
blanchet@33192
   269
      | Type (z as (s, _)) =>
blanchet@37256
   270
        if could_exist_alpha_sub_mtype ctxt alpha_T T then
blanchet@35665
   271
          case AList.lookup (op =) (!datatype_mcache) z of
blanchet@35385
   272
            SOME M => M
blanchet@33192
   273
          | NONE =>
blanchet@33192
   274
            let
blanchet@35665
   275
              val _ = Unsynchronized.change datatype_mcache (cons (z, MRec z))
blanchet@35219
   276
              val xs = binarized_and_boxed_datatype_constrs hol_ctxt binarize T
blanchet@35385
   277
              val (all_Ms, constr_Ms) =
blanchet@35385
   278
                fold_rev (fn (_, T') => fn (all_Ms, constr_Ms) =>
blanchet@33192
   279
                             let
blanchet@35385
   280
                               val binder_Ms = map do_type (binder_types T')
blanchet@35385
   281
                               val new_Ms = filter exists_alpha_sub_mtype_fresh
blanchet@35385
   282
                                                   binder_Ms
blanchet@35385
   283
                               val constr_M = constr_mtype_for_binders z
blanchet@35385
   284
                                                                       binder_Ms
blanchet@33192
   285
                             in
blanchet@35385
   286
                               (union (op =) new_Ms all_Ms,
blanchet@35385
   287
                                constr_M :: constr_Ms)
blanchet@33192
   288
                             end)
blanchet@33192
   289
                         xs ([], [])
blanchet@35385
   290
              val M = MType (s, all_Ms)
blanchet@35665
   291
              val _ = Unsynchronized.change datatype_mcache
blanchet@35385
   292
                          (AList.update (op =) (z, M))
blanchet@35665
   293
              val _ = Unsynchronized.change constr_mcache
blanchet@35385
   294
                          (append (xs ~~ constr_Ms))
blanchet@33192
   295
            in
blanchet@35665
   296
              if forall (not o is_MRec o snd) (!datatype_mcache) then
blanchet@35665
   297
                (repair_datatype_mcache datatype_mcache;
blanchet@35665
   298
                 repair_constr_mcache (!datatype_mcache) constr_mcache;
blanchet@35665
   299
                 AList.lookup (op =) (!datatype_mcache) z |> the)
blanchet@33192
   300
              else
blanchet@35385
   301
                M
blanchet@33192
   302
            end
blanchet@33192
   303
        else
blanchet@35385
   304
          MType (s, [])
blanchet@37260
   305
      | _ => MType (simple_string_of_typ T, [])
blanchet@33192
   306
  in do_type end
blanchet@33192
   307
blanchet@35385
   308
fun prodM_factors (MPair (M1, M2)) = maps prodM_factors [M1, M2]
blanchet@35385
   309
  | prodM_factors M = [M]
blanchet@35665
   310
fun curried_strip_mtype (MFun (M1, _, M2)) =
blanchet@35385
   311
    curried_strip_mtype M2 |>> append (prodM_factors M1)
blanchet@35385
   312
  | curried_strip_mtype M = ([], M)
blanchet@35385
   313
fun sel_mtype_from_constr_mtype s M =
blanchet@35385
   314
  let val (arg_Ms, dataM) = curried_strip_mtype M in
blanchet@40985
   315
    MFun (dataM, A Gen,
blanchet@35385
   316
          case sel_no_from_name s of ~1 => bool_M | n => nth arg_Ms n)
blanchet@33192
   317
  end
blanchet@33192
   318
blanchet@37256
   319
fun mtype_for_constr (mdata as {hol_ctxt = {ctxt, ...}, alpha_T, constr_mcache,
blanchet@33192
   320
                                ...}) (x as (_, T)) =
blanchet@37256
   321
  if could_exist_alpha_sub_mtype ctxt alpha_T T then
blanchet@35665
   322
    case AList.lookup (op =) (!constr_mcache) x of
blanchet@35385
   323
      SOME M => M
blanchet@35384
   324
    | NONE => if T = alpha_T then
blanchet@35672
   325
                let val M = fresh_mtype_for_type mdata false T in
blanchet@35665
   326
                  (Unsynchronized.change constr_mcache (cons (x, M)); M)
blanchet@35384
   327
                end
blanchet@35384
   328
              else
blanchet@35672
   329
                (fresh_mtype_for_type mdata false (body_type T);
blanchet@35665
   330
                 AList.lookup (op =) (!constr_mcache) x |> the)
blanchet@33192
   331
  else
blanchet@35672
   332
    fresh_mtype_for_type mdata false T
blanchet@35385
   333
fun mtype_for_sel (mdata as {hol_ctxt, binarize, ...}) (x as (s, _)) =
blanchet@35190
   334
  x |> binarized_and_boxed_constr_for_sel hol_ctxt binarize
blanchet@35385
   335
    |> mtype_for_constr mdata |> sel_mtype_from_constr_mtype s
blanchet@33192
   336
blanchet@40989
   337
fun resolve_annotation_atom asgs (V x) =
blanchet@40989
   338
    x |> AList.lookup (op =) asgs |> Option.map A |> the_default (V x)
blanchet@40988
   339
  | resolve_annotation_atom _ aa = aa
blanchet@40989
   340
fun resolve_mtype asgs =
blanchet@33192
   341
  let
blanchet@35385
   342
    fun aux MAlpha = MAlpha
blanchet@40988
   343
      | aux (MFun (M1, aa, M2)) =
blanchet@40989
   344
        MFun (aux M1, resolve_annotation_atom asgs aa, aux M2)
blanchet@35385
   345
      | aux (MPair Mp) = MPair (pairself aux Mp)
blanchet@35385
   346
      | aux (MType (s, Ms)) = MType (s, map aux Ms)
blanchet@35385
   347
      | aux (MRec z) = MRec z
blanchet@33192
   348
  in aux end
blanchet@33192
   349
blanchet@40996
   350
datatype comp_op = Eq | Neq | Leq
blanchet@33192
   351
blanchet@40985
   352
type comp = annotation_atom * annotation_atom * comp_op * var list
blanchet@40995
   353
type assign_clause = assign_literal list
blanchet@33192
   354
blanchet@40994
   355
type constraint_set = comp list * assign_clause list
blanchet@33192
   356
blanchet@33192
   357
fun string_for_comp_op Eq = "="
blanchet@40996
   358
  | string_for_comp_op Neq = "\<noteq>"
blanchet@33192
   359
  | string_for_comp_op Leq = "\<le>"
blanchet@33192
   360
blanchet@40990
   361
fun string_for_comp (aa1, aa2, cmp, xs) =
blanchet@40990
   362
  string_for_annotation_atom aa1 ^ " " ^ string_for_comp_op cmp ^
blanchet@40990
   363
  subscript_string_for_vars " \<and> " xs ^ " " ^ string_for_annotation_atom aa2
blanchet@33192
   364
blanchet@40990
   365
fun string_for_assign_clause [] = "\<bot>"
blanchet@40990
   366
  | string_for_assign_clause asgs =
blanchet@40995
   367
    space_implode " \<or> " (map string_for_assign_literal asgs)
blanchet@40990
   368
blanchet@40996
   369
fun add_assign_literal (x, (sn, a)) clauses =
blanchet@40996
   370
  if exists (fn [(x', (sn', a'))] =>
blanchet@40996
   371
                x = x' andalso ((sn = sn' andalso a <> a') orelse
blanchet@40996
   372
                                (sn <> sn' andalso a = a'))
blanchet@40996
   373
              | _ => false) clauses then
blanchet@40994
   374
    NONE
blanchet@40994
   375
  else
blanchet@40996
   376
    SOME ([(x, a)] :: clauses)
blanchet@33192
   377
blanchet@40991
   378
fun add_assign_disjunct _ NONE = NONE
blanchet@40991
   379
  | add_assign_disjunct asg (SOME asgs) = SOME (insert (op =) asg asgs)
blanchet@40991
   380
blanchet@40997
   381
val add_assign_clause = insert (op =)
blanchet@40997
   382
blanchet@40996
   383
fun annotation_comp Eq a1 a2 = (a1 = a2)
blanchet@40996
   384
  | annotation_comp Neq a1 a2 = (a1 <> a2)
blanchet@40996
   385
  | annotation_comp Leq a1 a2 = (a1 = a2 orelse a2 = Gen)
blanchet@40996
   386
blanchet@40997
   387
fun sign_for_comp_op Eq = Plus
blanchet@40997
   388
  | sign_for_comp_op Neq = Minus
blanchet@40997
   389
  | sign_for_comp_op Leq = raise BAD ("sign_for_comp_op", "unexpected \"Leq\"")
blanchet@40996
   390
blanchet@40996
   391
fun do_annotation_atom_comp Leq [] aa1 aa2 (cset as (comps, clauses)) =
blanchet@40988
   392
    (case (aa1, aa2) of
blanchet@40996
   393
       (A a1, A a2) => if annotation_comp Leq a1 a2 then SOME cset else NONE
blanchet@40996
   394
     | _ => SOME (insert (op =) (aa1, aa2, Leq, []) comps, clauses))
blanchet@40996
   395
  | do_annotation_atom_comp cmp [] aa1 aa2 (cset as (comps, clauses)) =
blanchet@40996
   396
    (case (aa1, aa2) of
blanchet@40996
   397
       (A a1, A a2) => if annotation_comp cmp a1 a2 then SOME cset else NONE
blanchet@40988
   398
     | (V x1, A a2) =>
blanchet@40997
   399
       clauses |> add_assign_literal (x1, (sign_for_comp_op cmp, a2))
blanchet@40996
   400
               |> Option.map (pair comps)
blanchet@40996
   401
     | (A _, V _) => do_annotation_atom_comp cmp [] aa2 aa1 cset
blanchet@40996
   402
     | (V _, V _) => SOME (insert (op =) (aa1, aa2, cmp, []) comps, clauses))
blanchet@40994
   403
  | do_annotation_atom_comp cmp xs aa1 aa2 (comps, clauses) =
blanchet@40994
   404
    SOME (insert (op =) (aa1, aa2, cmp, xs) comps, clauses)
blanchet@33192
   405
blanchet@40997
   406
fun add_annotation_atom_comp cmp xs aa1 aa2 (comps, clauses) =
blanchet@40993
   407
  (trace_msg (fn () => "*** Add " ^ string_for_annotation_atom aa1 ^ " " ^
blanchet@40993
   408
                       string_for_comp_op cmp ^ " " ^
blanchet@40993
   409
                       string_for_annotation_atom aa2);
blanchet@40994
   410
   case do_annotation_atom_comp cmp xs aa1 aa2 (comps, clauses) of
blanchet@40993
   411
     NONE => (trace_msg (K "**** Unsolvable"); raise UNSOLVABLE ())
blanchet@40994
   412
   | SOME cset => cset)
blanchet@40993
   413
blanchet@35385
   414
fun do_mtype_comp _ _ _ _ NONE = NONE
blanchet@40994
   415
  | do_mtype_comp _ _ MAlpha MAlpha cset = cset
blanchet@40988
   416
  | do_mtype_comp Eq xs (MFun (M11, aa1, M12)) (MFun (M21, aa2, M22))
blanchet@40994
   417
                  (SOME cset) =
blanchet@40994
   418
    cset |> do_annotation_atom_comp Eq xs aa1 aa2
blanchet@40994
   419
         |> do_mtype_comp Eq xs M11 M21 |> do_mtype_comp Eq xs M12 M22
blanchet@40988
   420
  | do_mtype_comp Leq xs (MFun (M11, aa1, M12)) (MFun (M21, aa2, M22))
blanchet@40994
   421
                  (SOME cset) =
blanchet@35385
   422
    (if exists_alpha_sub_mtype M11 then
blanchet@40994
   423
       cset |> do_annotation_atom_comp Leq xs aa1 aa2
blanchet@40994
   424
            |> do_mtype_comp Leq xs M21 M11
blanchet@40994
   425
            |> (case aa2 of
blanchet@40994
   426
                  A Gen => I
blanchet@40994
   427
                | A _ => do_mtype_comp Leq xs M11 M21
blanchet@40994
   428
                | V x => do_mtype_comp Leq (x :: xs) M11 M21)
blanchet@33192
   429
     else
blanchet@40994
   430
       SOME cset)
blanchet@35385
   431
    |> do_mtype_comp Leq xs M12 M22
blanchet@35385
   432
  | do_mtype_comp cmp xs (M1 as MPair (M11, M12)) (M2 as MPair (M21, M22))
blanchet@40994
   433
                  cset =
blanchet@40994
   434
    (cset |> fold (uncurry (do_mtype_comp cmp xs)) [(M11, M21), (M12, M22)]
blanchet@40994
   435
     handle Library.UnequalLengths =>
blanchet@35665
   436
            raise MTYPE ("Nitpick_Mono.do_mtype_comp", [M1, M2], []))
blanchet@40994
   437
  | do_mtype_comp _ _ (MType _) (MType _) cset =
blanchet@40994
   438
    cset (* no need to compare them thanks to the cache *)
blanchet@35665
   439
  | do_mtype_comp cmp _ M1 M2 _ =
blanchet@35665
   440
    raise MTYPE ("Nitpick_Mono.do_mtype_comp (" ^ string_for_comp_op cmp ^ ")",
blanchet@35665
   441
                 [M1, M2], [])
blanchet@33192
   442
blanchet@40994
   443
fun add_mtype_comp cmp M1 M2 cset =
blanchet@40991
   444
  (trace_msg (fn () => "*** Add " ^ string_for_mtype M1 ^ " " ^
blanchet@40991
   445
                       string_for_comp_op cmp ^ " " ^ string_for_mtype M2);
blanchet@40994
   446
   case SOME cset |> do_mtype_comp cmp [] M1 M2 of
blanchet@40991
   447
     NONE => (trace_msg (K "**** Unsolvable"); raise UNSOLVABLE ())
blanchet@40994
   448
   | SOME cset => cset)
blanchet@33192
   449
blanchet@35385
   450
val add_mtypes_equal = add_mtype_comp Eq
blanchet@35385
   451
val add_is_sub_mtype = add_mtype_comp Leq
blanchet@33192
   452
blanchet@35385
   453
fun do_notin_mtype_fv _ _ _ NONE = NONE
blanchet@40994
   454
  | do_notin_mtype_fv Minus _ MAlpha cset = cset
blanchet@35385
   455
  | do_notin_mtype_fv Plus [] MAlpha _ = NONE
blanchet@40996
   456
  | do_notin_mtype_fv Plus [asg] MAlpha (SOME clauses) =
blanchet@40996
   457
    clauses |> add_assign_literal asg
blanchet@40994
   458
  | do_notin_mtype_fv Plus clause MAlpha (SOME clauses) =
blanchet@40994
   459
    SOME (insert (op =) clause clauses)
blanchet@40994
   460
  | do_notin_mtype_fv sn clause (MFun (M1, A a, M2)) cset =
blanchet@40994
   461
    cset |> (if a <> Gen andalso sn = Plus then do_notin_mtype_fv Plus clause M1
blanchet@40994
   462
             else I)
blanchet@40994
   463
         |> (if a = Gen orelse sn = Plus then do_notin_mtype_fv Minus clause M1
blanchet@40994
   464
             else I)
blanchet@40994
   465
         |> do_notin_mtype_fv sn clause M2
blanchet@40994
   466
  | do_notin_mtype_fv Plus clause (MFun (M1, V x, M2)) cset =
blanchet@40996
   467
    cset |> (case add_assign_disjunct (x, (Plus, Gen)) (SOME clause) of
blanchet@40994
   468
               NONE => I
blanchet@40994
   469
             | SOME clause' => do_notin_mtype_fv Plus clause' M1)
blanchet@40994
   470
         |> do_notin_mtype_fv Minus clause M1
blanchet@40994
   471
         |> do_notin_mtype_fv Plus clause M2
blanchet@40994
   472
  | do_notin_mtype_fv Minus clause (MFun (M1, V x, M2)) cset =
blanchet@40996
   473
    cset |> (case fold (fn a => add_assign_disjunct (x, (Plus, a))) [Fls, Tru]
blanchet@40994
   474
                       (SOME clause) of
blanchet@40994
   475
               NONE => I
blanchet@40994
   476
             | SOME clause' => do_notin_mtype_fv Plus clause' M1)
blanchet@40994
   477
         |> do_notin_mtype_fv Minus clause M2
blanchet@40994
   478
  | do_notin_mtype_fv sn clause (MPair (M1, M2)) cset =
blanchet@40994
   479
    cset |> fold (do_notin_mtype_fv sn clause) [M1, M2]
blanchet@40994
   480
  | do_notin_mtype_fv sn clause (MType (_, Ms)) cset =
blanchet@40994
   481
    cset |> fold (do_notin_mtype_fv sn clause) Ms
blanchet@40994
   482
 | do_notin_mtype_fv _ _ M _ =
blanchet@40994
   483
   raise MTYPE ("Nitpick_Mono.do_notin_mtype_fv", [M], [])
blanchet@33192
   484
blanchet@40997
   485
fun add_notin_mtype_fv sn M (comps, clauses) =
blanchet@40985
   486
  (trace_msg (fn () => "*** Add " ^ string_for_mtype M ^ " is " ^
blanchet@40985
   487
                       (case sn of Minus => "concrete" | Plus => "complete"));
blanchet@40994
   488
   case SOME clauses |> do_notin_mtype_fv sn [] M of
blanchet@40985
   489
     NONE => (trace_msg (K "**** Unsolvable"); raise UNSOLVABLE ())
blanchet@40994
   490
   | SOME clauses => (comps, clauses))
blanchet@33192
   491
blanchet@35665
   492
val add_mtype_is_concrete = add_notin_mtype_fv Minus
blanchet@35665
   493
val add_mtype_is_complete = add_notin_mtype_fv Plus
blanchet@33192
   494
blanchet@40986
   495
val bool_table =
blanchet@40986
   496
  [(Gen, (false, false)),
blanchet@40986
   497
   (New, (false, true)),
blanchet@40986
   498
   (Fls, (true, false)),
blanchet@40986
   499
   (Tru, (true, true))]
blanchet@40986
   500
blanchet@40993
   501
fun fst_var n = 2 * n
blanchet@40993
   502
fun snd_var n = 2 * n + 1
blanchet@40993
   503
blanchet@40986
   504
val bools_from_annotation = AList.lookup (op =) bool_table #> the
blanchet@40986
   505
val annotation_from_bools = AList.find (op =) bool_table #> the_single
blanchet@33192
   506
blanchet@40990
   507
fun prop_for_bool b = if b then PL.True else PL.False
blanchet@40990
   508
fun prop_for_bool_var_equality (v1, v2) =
blanchet@40990
   509
  PL.And (PL.Or (PL.BoolVar v1, PL.Not (PL.BoolVar v2)),
blanchet@40990
   510
          PL.Or (PL.Not (PL.BoolVar v1), PL.BoolVar v2))
blanchet@40996
   511
fun prop_for_assign (x, a) =
blanchet@40986
   512
  let val (b1, b2) = bools_from_annotation a in
blanchet@40990
   513
    PL.And (PL.BoolVar (fst_var x) |> not b1 ? PL.Not,
blanchet@40990
   514
            PL.BoolVar (snd_var x) |> not b2 ? PL.Not)
blanchet@40986
   515
  end
blanchet@40996
   516
fun prop_for_assign_literal (x, (Plus, a)) = prop_for_assign (x, a)
blanchet@40996
   517
  | prop_for_assign_literal (x, (Minus, a)) = PL.Not (prop_for_assign (x, a))
blanchet@40990
   518
fun prop_for_atom_assign (A a', a) = prop_for_bool (a = a')
blanchet@40996
   519
  | prop_for_atom_assign (V x, a) = prop_for_assign_literal (x, (Plus, a))
blanchet@40990
   520
fun prop_for_atom_equality (aa1, A a2) = prop_for_atom_assign (aa1, a2)
blanchet@40990
   521
  | prop_for_atom_equality (A a1, aa2) = prop_for_atom_assign (aa2, a1)
blanchet@40990
   522
  | prop_for_atom_equality (V x1, V x2) =
blanchet@40990
   523
    PL.And (prop_for_bool_var_equality (pairself fst_var (x1, x2)),
blanchet@40990
   524
            prop_for_bool_var_equality (pairself snd_var (x1, x2)))
blanchet@40995
   525
val prop_for_assign_clause = PL.exists o map prop_for_assign_literal
blanchet@40995
   526
fun prop_for_exists_var_assign_literal xs a =
blanchet@40996
   527
  PL.exists (map (fn x => prop_for_assign_literal (x, (Plus, a))) xs)
blanchet@40988
   528
fun prop_for_comp (aa1, aa2, Eq, []) =
blanchet@40990
   529
    PL.SAnd (prop_for_comp (aa1, aa2, Leq, []),
blanchet@40990
   530
             prop_for_comp (aa2, aa1, Leq, []))
blanchet@40996
   531
  | prop_for_comp (aa1, aa2, Neq, []) =
blanchet@40996
   532
    PL.Not (prop_for_comp (aa1, aa2, Eq, []))
blanchet@40988
   533
  | prop_for_comp (aa1, aa2, Leq, []) =
blanchet@40990
   534
    PL.SOr (prop_for_atom_equality (aa1, aa2), prop_for_atom_assign (aa2, Gen))
blanchet@40988
   535
  | prop_for_comp (aa1, aa2, cmp, xs) =
blanchet@40995
   536
    PL.SOr (prop_for_exists_var_assign_literal xs Gen,
blanchet@40990
   537
            prop_for_comp (aa1, aa2, cmp, []))
blanchet@33192
   538
blanchet@40993
   539
(* The "calculus" parameter may be 1, 2, or 3, corresponding approximately to
blanchet@40993
   540
   the M1, M2, and M3 calculi from Blanchette & Krauss 2011. *)
blanchet@40993
   541
fun variable_domain calculus =
blanchet@40993
   542
  [Gen] @ (if calculus > 1 then [Fls] else [])
blanchet@40993
   543
  @ (if calculus > 2 then [New, Tru] else [])
blanchet@40993
   544
blanchet@40993
   545
fun prop_for_variable_domain calculus x =
blanchet@40996
   546
  PL.exists (map (fn a => prop_for_assign_literal (x, (Plus, a)))
blanchet@40996
   547
                 (variable_domain calculus))
blanchet@40986
   548
blanchet@40990
   549
fun extract_assigns max_var assigns asgs =
blanchet@33192
   550
  fold (fn x => fn accum =>
blanchet@40989
   551
           if AList.defined (op =) asgs x then
blanchet@33192
   552
             accum
blanchet@40986
   553
           else case (fst_var x, snd_var x) |> pairself assigns of
blanchet@40986
   554
             (NONE, NONE) => accum
blanchet@40993
   555
           | bp => (x, annotation_from_bools (pairself (the_default false) bp))
blanchet@40993
   556
                   :: accum)
blanchet@40989
   557
       (max_var downto 1) asgs
blanchet@33192
   558
blanchet@40994
   559
fun print_problem calculus comps clauses =
blanchet@40994
   560
  trace_msg (fn () =>
blanchet@40994
   561
                "*** Problem (calculus M" ^ string_of_int calculus ^ "):\n" ^
blanchet@40994
   562
                cat_lines (map string_for_comp comps @
blanchet@40994
   563
                           map string_for_assign_clause clauses))
blanchet@33192
   564
blanchet@40989
   565
fun print_solution asgs =
blanchet@40989
   566
  trace_msg (fn () => "*** Solution:\n" ^
blanchet@40989
   567
      (asgs
blanchet@40989
   568
       |> map swap
blanchet@40989
   569
       |> AList.group (op =)
blanchet@40989
   570
       |> map (fn (a, xs) => string_for_annotation a ^ ": " ^
blanchet@40989
   571
                             string_for_vars ", " xs)
blanchet@40989
   572
       |> space_implode "\n"))
blanchet@33192
   573
blanchet@40994
   574
fun solve calculus max_var (comps, clauses) =
blanchet@40146
   575
  let
blanchet@40996
   576
    val asgs = map_filter (fn [(x, (_, a))] => SOME (x, a) | _ => NONE) clauses
blanchet@40146
   577
    fun do_assigns assigns =
blanchet@40990
   578
      SOME (extract_assigns max_var assigns asgs |> tap print_solution)
blanchet@40994
   579
    val _ = print_problem calculus comps clauses
blanchet@40993
   580
    val prop =
blanchet@40993
   581
      map prop_for_comp comps @
blanchet@40993
   582
      map prop_for_assign_clause clauses @
blanchet@40993
   583
      (if calculus < 3 then
blanchet@40993
   584
         map (prop_for_variable_domain calculus) (1 upto max_var)
blanchet@40993
   585
       else
blanchet@40993
   586
         [])
blanchet@40993
   587
      |> PL.all
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@40146
   596
        val solvers = !SatSolver.solvers
blanchet@40146
   597
                      |> filter (member (op =) ["dptsat", "dpll"] o fst)
blanchet@40146
   598
      in
blanchet@40146
   599
        case snd (hd solvers) prop of
blanchet@40146
   600
          SatSolver.SATISFIABLE assigns => do_assigns assigns
blanchet@40994
   601
        | _ => (trace_msg (K "*** Unsolvable"); NONE)
blanchet@40146
   602
      end
blanchet@40146
   603
  end
blanchet@33192
   604
blanchet@35385
   605
type mtype_schema = mtyp * constraint_set
blanchet@35385
   606
type mtype_context =
blanchet@35665
   607
  {bound_Ts: typ list,
blanchet@35665
   608
   bound_Ms: mtyp list,
blanchet@40987
   609
   bound_frame: (int * annotation_atom) list,
blanchet@35385
   610
   frees: (styp * mtyp) list,
blanchet@35385
   611
   consts: (styp * mtyp) list}
blanchet@33192
   612
blanchet@35385
   613
type accumulator = mtype_context * constraint_set
blanchet@33192
   614
blanchet@40987
   615
val initial_gamma =
blanchet@40987
   616
  {bound_Ts = [], bound_Ms = [], bound_frame = [], frees = [], consts = []}
blanchet@33192
   617
blanchet@40993
   618
fun push_bound aa T M {bound_Ts, bound_Ms, bound_frame, frees, consts} =
blanchet@40987
   619
  {bound_Ts = T :: bound_Ts, bound_Ms = M :: bound_Ms,
blanchet@40993
   620
   bound_frame = (length bound_Ts, aa) :: bound_frame, frees = frees,
blanchet@40993
   621
   consts = consts}
blanchet@40987
   622
fun pop_bound {bound_Ts, bound_Ms, bound_frame, frees, consts} =
blanchet@40993
   623
  {bound_Ts = tl bound_Ts, bound_Ms = tl bound_Ms,
blanchet@40993
   624
   bound_frame = bound_frame
blanchet@40994
   625
                 |> filter_out (fn (j, _) => j = length bound_Ts - 1),
blanchet@40987
   626
   frees = frees, consts = consts}
blanchet@35665
   627
  handle List.Empty => initial_gamma (* FIXME: needed? *)
blanchet@33192
   628
blanchet@40994
   629
fun set_frame bound_frame ({bound_Ts, bound_Ms, frees, consts, ...}
blanchet@40994
   630
                           : mtype_context) =
blanchet@40994
   631
  {bound_Ts = bound_Ts, bound_Ms = bound_Ms, bound_frame = bound_frame,
blanchet@40994
   632
   frees = frees, consts = consts}
blanchet@40994
   633
blanchet@40994
   634
(* FIXME: make sure tracing messages are complete *)
blanchet@40994
   635
blanchet@40997
   636
fun add_comp_frame a cmp = fold (add_annotation_atom_comp cmp [] (A a) o snd)
blanchet@40994
   637
blanchet@40994
   638
fun add_bound_frame j frame =
blanchet@40994
   639
  let
blanchet@40994
   640
    val (new_frame, gen_frame) = List.partition (curry (op =) j o fst) frame
blanchet@40994
   641
  in
blanchet@40994
   642
    add_comp_frame New Leq new_frame
blanchet@40994
   643
    #> add_comp_frame Gen Eq gen_frame
blanchet@40994
   644
  end
blanchet@40994
   645
blanchet@40997
   646
fun fresh_frame ({max_fresh, ...} : mdata) fls tru =
blanchet@40997
   647
  map (apsnd (fn aa =>
blanchet@40997
   648
                 case (aa, fls, tru) of
blanchet@40997
   649
                   (A Fls, SOME a, _) => A a
blanchet@40997
   650
                 | (A Tru, _, SOME a) => A a
blanchet@40997
   651
                 | (A Gen, _, _) => A Gen
blanchet@40997
   652
                 | _ => V (Unsynchronized.inc max_fresh)))
blanchet@40994
   653
blanchet@40997
   654
fun conj_clauses res_aa aa1 aa2 =
blanchet@40997
   655
  [[(aa1, (Neq, Tru)), (aa2, (Neq, Tru)), (res_aa, (Eq, Tru))],
blanchet@40997
   656
   [(aa1, (Neq, Fls)), (res_aa, (Eq, Fls))],
blanchet@40997
   657
   [(aa2, (Neq, Fls)), (res_aa, (Eq, Fls))],
blanchet@40997
   658
   [(aa1, (Neq, Gen)), (aa2, (Eq, Fls)), (res_aa, (Eq, Gen))],
blanchet@40997
   659
   [(aa1, (Neq, New)), (aa2, (Eq, Fls)), (res_aa, (Eq, Gen))],
blanchet@40997
   660
   [(aa1, (Eq, Fls)), (aa2, (Neq, Gen)), (res_aa, (Eq, Gen))],
blanchet@40997
   661
   [(aa1, (Eq, Fls)), (aa2, (Neq, New)), (res_aa, (Eq, Gen))]]
blanchet@40997
   662
blanchet@40997
   663
fun disj_clauses res_aa aa1 aa2 =
blanchet@40997
   664
  [[(aa1, (Neq, Tru)), (res_aa, (Eq, Tru))],
blanchet@40997
   665
   [(aa2, (Neq, Tru)), (res_aa, (Eq, Tru))],
blanchet@40997
   666
   [(aa1, (Neq, Fls)), (aa2, (Neq, Fls)), (res_aa, (Eq, Fls))],
blanchet@40997
   667
   [(aa1, (Neq, Gen)), (aa2, (Eq, Tru)), (res_aa, (Eq, Gen))],
blanchet@40997
   668
   [(aa1, (Neq, New)), (aa2, (Eq, Tru)), (res_aa, (Eq, Gen))],
blanchet@40997
   669
   [(aa1, (Eq, Tru)), (aa2, (Neq, Gen)), (res_aa, (Eq, Gen))],
blanchet@40997
   670
   [(aa1, (Eq, Tru)), (aa2, (Neq, New)), (res_aa, (Eq, Gen))]]
blanchet@40994
   671
blanchet@40997
   672
fun imp_clauses res_aa aa1 aa2 =
blanchet@40997
   673
  [[(aa1, (Neq, Fls)), (res_aa, (Eq, Tru))],
blanchet@40997
   674
   [(aa2, (Neq, Tru)), (res_aa, (Eq, Tru))],
blanchet@40997
   675
   [(aa1, (Neq, Tru)), (aa2, (Neq, Fls)), (res_aa, (Eq, Fls))],
blanchet@40997
   676
   [(aa1, (Neq, Gen)), (aa2, (Eq, Tru)), (res_aa, (Eq, Gen))],
blanchet@40997
   677
   [(aa1, (Neq, New)), (aa2, (Eq, Tru)), (res_aa, (Eq, Gen))],
blanchet@40997
   678
   [(aa1, (Eq, Fls)), (aa2, (Neq, Gen)), (res_aa, (Eq, Gen))],
blanchet@40997
   679
   [(aa1, (Eq, Fls)), (aa2, (Neq, New)), (res_aa, (Eq, Gen))]]
blanchet@40997
   680
blanchet@40997
   681
fun annotation_literal_from_quasi_literal (aa, (cmp, a)) =
blanchet@40997
   682
  case aa of
blanchet@40997
   683
    A a' => if annotation_comp cmp a' a then NONE
blanchet@40997
   684
            else (trace_msg (K "**** Unsolvable"); raise UNSOLVABLE ())
blanchet@40997
   685
  | V x => SOME (x, (sign_for_comp_op cmp, a))
blanchet@40995
   686
blanchet@40997
   687
val annotation_clause_from_quasi_clause =
blanchet@40997
   688
  map_filter annotation_literal_from_quasi_literal
blanchet@40997
   689
blanchet@40997
   690
val add_quasi_clause = annotation_clause_from_quasi_clause #> add_assign_clause
blanchet@40995
   691
blanchet@40997
   692
fun add_connective_var conn mk_quasi_clauses res_aa aa1 aa2 =
blanchet@40997
   693
  (trace_msg (fn () => "*** Add " ^ string_for_annotation_atom res_aa ^ " = " ^
blanchet@40997
   694
                       string_for_annotation_atom aa1 ^ " " ^ conn ^ " " ^
blanchet@40997
   695
                       string_for_annotation_atom aa2);
blanchet@40997
   696
   fold add_quasi_clause (mk_quasi_clauses res_aa aa1 aa2))
blanchet@40997
   697
blanchet@40997
   698
fun add_connective_frames conn mk_quasi_clauses res_frame frame1 frame2 =
blanchet@40997
   699
  fold I (map3 (fn (_, res_aa) => fn (_, aa1) => fn (_, aa2) =>
blanchet@40997
   700
                   add_connective_var conn mk_quasi_clauses res_aa aa1 aa2)
blanchet@40997
   701
               res_frame frame1 frame2)
blanchet@40995
   702
blanchet@39359
   703
fun consider_term (mdata as {hol_ctxt = {thy, ctxt, stds, ...}, alpha_T,
blanchet@39359
   704
                             max_fresh, ...}) =
blanchet@33192
   705
  let
blanchet@37476
   706
    fun is_enough_eta_expanded t =
blanchet@37476
   707
      case strip_comb t of
blanchet@39359
   708
        (Const x, ts) => the_default 0 (arity_of_built_in_const thy stds x)
blanchet@37476
   709
        <= length ts
blanchet@37476
   710
      | _ => true
blanchet@35672
   711
    val mtype_for = fresh_mtype_for_type mdata false
blanchet@35665
   712
    fun plus_set_mtype_for_dom M =
blanchet@40985
   713
      MFun (M, A (if exists_alpha_sub_mtype M then Fls else Gen), bool_M)
blanchet@35385
   714
    fun do_all T (gamma, cset) =
blanchet@33192
   715
      let
blanchet@35385
   716
        val abs_M = mtype_for (domain_type (domain_type T))
blanchet@35386
   717
        val body_M = mtype_for (body_type T)
blanchet@33192
   718
      in
blanchet@40985
   719
        (MFun (MFun (abs_M, A Gen, body_M), A Gen, body_M),
blanchet@35665
   720
         (gamma, cset |> add_mtype_is_complete abs_M))
blanchet@33192
   721
      end
blanchet@33192
   722
    fun do_equals T (gamma, cset) =
blanchet@40997
   723
      let
blanchet@40997
   724
        val M = mtype_for (domain_type T)
blanchet@40997
   725
        val aa = V (Unsynchronized.inc max_fresh)
blanchet@40997
   726
      in
blanchet@40997
   727
        (MFun (M, A Gen, MFun (M, aa, mtype_for (nth_range_type 2 T))),
blanchet@40997
   728
         (gamma, cset |> add_mtype_is_concrete M
blanchet@40997
   729
                      |> add_annotation_atom_comp Leq [] (A Fls) aa))
blanchet@33192
   730
      end
blanchet@33192
   731
    fun do_robust_set_operation T (gamma, cset) =
blanchet@33192
   732
      let
blanchet@33192
   733
        val set_T = domain_type T
blanchet@35385
   734
        val M1 = mtype_for set_T
blanchet@35385
   735
        val M2 = mtype_for set_T
blanchet@35385
   736
        val M3 = mtype_for set_T
blanchet@33192
   737
      in
blanchet@40985
   738
        (MFun (M1, A Gen, MFun (M2, A Gen, M3)),
blanchet@35385
   739
         (gamma, cset |> add_is_sub_mtype M1 M3 |> add_is_sub_mtype M2 M3))
blanchet@33192
   740
      end
blanchet@33192
   741
    fun do_fragile_set_operation T (gamma, cset) =
blanchet@33192
   742
      let
blanchet@33192
   743
        val set_T = domain_type T
blanchet@35385
   744
        val set_M = mtype_for set_T
blanchet@35665
   745
        fun custom_mtype_for (T as Type (@{type_name fun}, [T1, T2])) =
blanchet@35385
   746
            if T = set_T then set_M
blanchet@40985
   747
            else MFun (custom_mtype_for T1, A Gen, custom_mtype_for T2)
blanchet@35385
   748
          | custom_mtype_for T = mtype_for T
blanchet@33192
   749
      in
blanchet@35665
   750
        (custom_mtype_for T, (gamma, cset |> add_mtype_is_concrete set_M))
blanchet@33192
   751
      end
blanchet@33192
   752
    fun do_pair_constr T accum =
blanchet@35385
   753
      case mtype_for (nth_range_type 2 T) of
blanchet@35385
   754
        M as MPair (a_M, b_M) =>
blanchet@40985
   755
        (MFun (a_M, A Gen, MFun (b_M, A Gen, M)), accum)
blanchet@35665
   756
      | M => raise MTYPE ("Nitpick_Mono.consider_term.do_pair_constr", [M], [])
blanchet@33192
   757
    fun do_nth_pair_sel n T =
blanchet@35385
   758
      case mtype_for (domain_type T) of
blanchet@35385
   759
        M as MPair (a_M, b_M) =>
blanchet@40985
   760
        pair (MFun (M, A Gen, if n = 0 then a_M else b_M))
blanchet@35665
   761
      | M => raise MTYPE ("Nitpick_Mono.consider_term.do_nth_pair_sel", [M], [])
blanchet@35385
   762
    fun do_bounded_quantifier t0 abs_s abs_T connective_t bound_t body_t accum =
blanchet@33192
   763
      let
blanchet@35385
   764
        val abs_M = mtype_for abs_T
blanchet@40993
   765
        val aa = V (Unsynchronized.inc max_fresh)
blanchet@35665
   766
        val (bound_m, accum) =
blanchet@40993
   767
          accum |>> push_bound aa abs_T abs_M |> do_term bound_t
blanchet@35665
   768
        val expected_bound_M = plus_set_mtype_for_dom abs_M
blanchet@35385
   769
        val (body_m, accum) =
blanchet@35385
   770
          accum ||> add_mtypes_equal expected_bound_M (mtype_of_mterm bound_m)
blanchet@35385
   771
                |> do_term body_t ||> apfst pop_bound
blanchet@35385
   772
        val bound_M = mtype_of_mterm bound_m
blanchet@40993
   773
        val (M1, aa', _) = dest_MFun bound_M
blanchet@33192
   774
      in
blanchet@40993
   775
        (MApp (MRaw (t0, MFun (bound_M, aa, bool_M)),
blanchet@40993
   776
               MAbs (abs_s, abs_T, M1, aa',
blanchet@35386
   777
                     MApp (MApp (MRaw (connective_t,
blanchet@35386
   778
                                       mtype_for (fastype_of connective_t)),
blanchet@35386
   779
                                 MApp (bound_m, MRaw (Bound 0, M1))),
blanchet@35385
   780
                           body_m))), accum)
blanchet@33192
   781
      end
blanchet@40997
   782
    and do_connect conn mk_quasi_clauses t0 t1 t2
blanchet@40997
   783
                   (accum as ({bound_frame, ...}, _)) =
blanchet@40995
   784
      let
blanchet@40997
   785
        val frame1 = fresh_frame mdata (SOME Tru) NONE bound_frame
blanchet@40997
   786
        val frame2 = fresh_frame mdata (SOME Fls) NONE bound_frame
blanchet@40995
   787
        val (m1, accum) = accum |>> set_frame frame1 |> do_term t1
blanchet@40995
   788
        val (m2, accum) = accum |>> set_frame frame2 |> do_term t2
blanchet@40995
   789
      in
blanchet@40995
   790
        (MApp (MApp (MRaw (t0, mtype_for (fastype_of t0)), m1), m2),
blanchet@40995
   791
         accum |>> set_frame bound_frame
blanchet@40997
   792
               ||> apsnd (add_connective_frames conn mk_quasi_clauses
blanchet@40997
   793
                                                bound_frame frame1 frame2))
blanchet@40995
   794
      end
blanchet@40987
   795
    and do_term t (accum as ({bound_Ts, bound_Ms, bound_frame, frees, consts},
blanchet@40987
   796
                             cset)) =
blanchet@40993
   797
      (trace_msg (fn () => "  \<Gamma> \<turnstile> " ^
blanchet@40993
   798
                           Syntax.string_of_term ctxt t ^ " : _?");
blanchet@40993
   799
       case t of
blanchet@40994
   800
         @{const False} =>
blanchet@40994
   801
         (MRaw (t, bool_M), accum ||> add_comp_frame Fls Leq bound_frame)
blanchet@40994
   802
       | @{const True} =>
blanchet@40994
   803
         (MRaw (t, bool_M), accum ||> add_comp_frame Tru Leq bound_frame)
blanchet@40994
   804
       | Const (x as (s, T)) =>
blanchet@40993
   805
         (case AList.lookup (op =) consts x of
blanchet@40993
   806
            SOME M => (M, accum)
blanchet@40993
   807
          | NONE =>
blanchet@40994
   808
            if not (could_exist_alpha_subtype alpha_T T) then
blanchet@40994
   809
              (mtype_for T, accum)
blanchet@40994
   810
            else case s of
blanchet@40994
   811
              @{const_name all} => do_all T accum
blanchet@40994
   812
            | @{const_name "=="} => do_equals T accum
blanchet@40994
   813
            | @{const_name All} => do_all T accum
blanchet@40994
   814
            | @{const_name Ex} =>
blanchet@40994
   815
              let val set_T = domain_type T in
blanchet@40994
   816
                do_term (Abs (Name.uu, set_T,
blanchet@40994
   817
                              @{const Not} $ (HOLogic.mk_eq
blanchet@40994
   818
                                  (Abs (Name.uu, domain_type set_T,
blanchet@40994
   819
                                        @{const False}),
blanchet@40994
   820
                                   Bound 0)))) accum
blanchet@40994
   821
                |>> mtype_of_mterm
blanchet@40994
   822
              end
blanchet@40994
   823
            | @{const_name HOL.eq} => do_equals T accum
blanchet@40994
   824
            | @{const_name The} =>
blanchet@40994
   825
              (trace_msg (K "*** The"); raise UNSOLVABLE ())
blanchet@40994
   826
            | @{const_name Eps} =>
blanchet@40994
   827
              (trace_msg (K "*** Eps"); raise UNSOLVABLE ())
blanchet@40994
   828
            | @{const_name If} =>
blanchet@40994
   829
              do_robust_set_operation (range_type T) accum
blanchet@40994
   830
              |>> curry3 MFun bool_M (A Gen)
blanchet@40994
   831
            | @{const_name Pair} => do_pair_constr T accum
blanchet@40994
   832
            | @{const_name fst} => do_nth_pair_sel 0 T accum
blanchet@40994
   833
            | @{const_name snd} => do_nth_pair_sel 1 T accum
blanchet@40994
   834
            | @{const_name Id} =>
blanchet@40994
   835
              (MFun (mtype_for (domain_type T), A Gen, bool_M), accum)
blanchet@40994
   836
            | @{const_name converse} =>
blanchet@40994
   837
              let
blanchet@40994
   838
                val x = Unsynchronized.inc max_fresh
blanchet@40994
   839
                fun mtype_for_set T =
blanchet@40994
   840
                  MFun (mtype_for (domain_type T), V x, bool_M)
blanchet@40994
   841
                val ab_set_M = domain_type T |> mtype_for_set
blanchet@40994
   842
                val ba_set_M = range_type T |> mtype_for_set
blanchet@40994
   843
              in (MFun (ab_set_M, A Gen, ba_set_M), accum) end
blanchet@40994
   844
            | @{const_name trancl} => do_fragile_set_operation T accum
blanchet@40994
   845
            | @{const_name rel_comp} =>
blanchet@40994
   846
              let
blanchet@40994
   847
                val x = Unsynchronized.inc max_fresh
blanchet@40994
   848
                fun mtype_for_set T =
blanchet@40994
   849
                  MFun (mtype_for (domain_type T), V x, bool_M)
blanchet@40994
   850
                val bc_set_M = domain_type T |> mtype_for_set
blanchet@40994
   851
                val ab_set_M = domain_type (range_type T) |> mtype_for_set
blanchet@40994
   852
                val ac_set_M = nth_range_type 2 T |> mtype_for_set
blanchet@40994
   853
              in
blanchet@40994
   854
                (MFun (bc_set_M, A Gen, MFun (ab_set_M, A Gen, ac_set_M)),
blanchet@40994
   855
                 accum)
blanchet@40994
   856
              end
blanchet@40994
   857
            | @{const_name image} =>
blanchet@40994
   858
              let
blanchet@40994
   859
                val a_M = mtype_for (domain_type (domain_type T))
blanchet@40994
   860
                val b_M = mtype_for (range_type (domain_type T))
blanchet@40994
   861
              in
blanchet@40994
   862
                (MFun (MFun (a_M, A Gen, b_M), A Gen,
blanchet@40994
   863
                       MFun (plus_set_mtype_for_dom a_M, A Gen,
blanchet@40994
   864
                             plus_set_mtype_for_dom b_M)), accum)
blanchet@40994
   865
              end
blanchet@40994
   866
            | @{const_name finite} =>
blanchet@40994
   867
              let val M1 = mtype_for (domain_type (domain_type T)) in
blanchet@40994
   868
                (MFun (plus_set_mtype_for_dom M1, A Gen, bool_M), accum)
blanchet@40994
   869
              end
blanchet@40994
   870
            | @{const_name Sigma} =>
blanchet@40994
   871
              let
blanchet@40994
   872
                val x = Unsynchronized.inc max_fresh
blanchet@40994
   873
                fun mtype_for_set T =
blanchet@40994
   874
                  MFun (mtype_for (domain_type T), V x, bool_M)
blanchet@40994
   875
                val a_set_T = domain_type T
blanchet@40994
   876
                val a_M = mtype_for (domain_type a_set_T)
blanchet@40994
   877
                val b_set_M =
blanchet@40994
   878
                  mtype_for_set (range_type (domain_type (range_type T)))
blanchet@40994
   879
                val a_set_M = mtype_for_set a_set_T
blanchet@40994
   880
                val a_to_b_set_M = MFun (a_M, A Gen, b_set_M)
blanchet@40994
   881
                val ab_set_M = mtype_for_set (nth_range_type 2 T)
blanchet@40994
   882
              in
blanchet@40994
   883
                (MFun (a_set_M, A Gen, MFun (a_to_b_set_M, A Gen, ab_set_M)),
blanchet@40994
   884
                 accum)
blanchet@40994
   885
              end
blanchet@40993
   886
            | _ =>
blanchet@40994
   887
              if s = @{const_name safe_The} then
blanchet@33192
   888
                let
blanchet@40994
   889
                  val a_set_M = mtype_for (domain_type T)
blanchet@40994
   890
                  val a_M = dest_MFun a_set_M |> #1
blanchet@40994
   891
                in (MFun (a_set_M, A Gen, a_M), accum) end
blanchet@40994
   892
              else if s = @{const_name ord_class.less_eq} andalso
blanchet@40994
   893
                      is_set_type (domain_type T) then
blanchet@40994
   894
                do_fragile_set_operation T accum
blanchet@40994
   895
              else if is_sel s then
blanchet@40994
   896
                (mtype_for_sel mdata x, accum)
blanchet@40994
   897
              else if is_constr ctxt stds x then
blanchet@40994
   898
                (mtype_for_constr mdata x, accum)
blanchet@40994
   899
              else if is_built_in_const thy stds x then
blanchet@40994
   900
                (fresh_mtype_for_type mdata true T, accum)
blanchet@40994
   901
              else
blanchet@40994
   902
                let val M = mtype_for T in
blanchet@40994
   903
                  (M, ({bound_Ts = bound_Ts, bound_Ms = bound_Ms,
blanchet@40994
   904
                        bound_frame = bound_frame, frees = frees,
blanchet@40994
   905
                        consts = (x, M) :: consts}, cset))
blanchet@40994
   906
                end)
blanchet@40994
   907
           |>> curry MRaw t
blanchet@40994
   908
           ||> apsnd (add_comp_frame Gen Eq bound_frame)
blanchet@33192
   909
         | Free (x as (_, T)) =>
blanchet@33192
   910
           (case AList.lookup (op =) frees x of
blanchet@35385
   911
              SOME M => (M, accum)
blanchet@33192
   912
            | NONE =>
blanchet@35385
   913
              let val M = mtype_for T in
blanchet@35665
   914
                (M, ({bound_Ts = bound_Ts, bound_Ms = bound_Ms,
blanchet@40987
   915
                      bound_frame = bound_frame, frees = (x, M) :: frees,
blanchet@40987
   916
                      consts = consts}, cset))
blanchet@40994
   917
              end)
blanchet@40994
   918
           |>> curry MRaw t ||> apsnd (add_comp_frame Gen Eq bound_frame)
blanchet@38179
   919
         | Var _ => (trace_msg (K "*** Var"); raise UNSOLVABLE ())
blanchet@40994
   920
         | Bound j =>
blanchet@40994
   921
           (MRaw (t, nth bound_Ms j),
blanchet@40994
   922
            accum ||> add_bound_frame (length bound_Ts - j - 1) bound_frame)
blanchet@35385
   923
         | Abs (s, T, t') =>
blanchet@35665
   924
           (case fin_fun_body T (fastype_of1 (T :: bound_Ts, t')) t' of
blanchet@35665
   925
              SOME t' =>
blanchet@35665
   926
              let
blanchet@35665
   927
                val M = mtype_for T
blanchet@40993
   928
                val (m', accum) = do_term t' (accum |>> push_bound (A Fls) T M)
blanchet@40993
   929
              in (MAbs (s, T, M, A Fls, m'), accum |>> pop_bound) end
blanchet@35665
   930
            | NONE =>
blanchet@35665
   931
              ((case t' of
blanchet@35665
   932
                  t1' $ Bound 0 =>
blanchet@37476
   933
                  if not (loose_bvar1 (t1', 0)) andalso
blanchet@37476
   934
                     is_enough_eta_expanded t1' then
blanchet@35665
   935
                    do_term (incr_boundvars ~1 t1') accum
blanchet@35665
   936
                  else
blanchet@35665
   937
                    raise SAME ()
haftmann@38864
   938
                | (t11 as Const (@{const_name HOL.eq}, _)) $ Bound 0 $ t13 =>
blanchet@37476
   939
                  if not (loose_bvar1 (t13, 0)) then
blanchet@37476
   940
                    do_term (incr_boundvars ~1 (t11 $ t13)) accum
blanchet@37476
   941
                  else
blanchet@37476
   942
                    raise SAME ()
blanchet@35665
   943
                | _ => raise SAME ())
blanchet@35665
   944
               handle SAME () =>
blanchet@35665
   945
                      let
blanchet@35665
   946
                        val M = mtype_for T
blanchet@40993
   947
                        val aa = V (Unsynchronized.inc max_fresh)
blanchet@40993
   948
                        val (m', accum) =
blanchet@40993
   949
                          do_term t' (accum |>> push_bound aa T M)
blanchet@40993
   950
                      in (MAbs (s, T, M, aa, m'), accum |>> pop_bound) end))
blanchet@35385
   951
         | (t0 as Const (@{const_name All}, _))
blanchet@40997
   952
           $ Abs (s', T', (t10 as @{const implies}) $ (t11 $ Bound 0) $ t12) =>
blanchet@35385
   953
           do_bounded_quantifier t0 s' T' t10 t11 t12 accum
blanchet@35385
   954
         | (t0 as Const (@{const_name Ex}, _))
blanchet@40997
   955
           $ Abs (s', T', (t10 as @{const conj}) $ (t11 $ Bound 0) $ t12) =>
blanchet@35385
   956
           do_bounded_quantifier t0 s' T' t10 t11 t12 accum
blanchet@40997
   957
         | @{const Not} $ t1 =>
blanchet@40997
   958
           do_connect "\<implies>" imp_clauses @{const implies} t1
blanchet@40997
   959
                      @{const False} accum
blanchet@40995
   960
         | (t0 as @{const conj}) $ t1 $ t2 =>
blanchet@40997
   961
           do_connect "\<and>" conj_clauses t0 t1 t2 accum
blanchet@40995
   962
         | (t0 as @{const disj}) $ t1 $ t2 =>
blanchet@40997
   963
           do_connect "\<or>" disj_clauses t0 t1 t2 accum
blanchet@40995
   964
         | (t0 as @{const implies}) $ t1 $ t2 =>
blanchet@40997
   965
           do_connect "\<implies>" imp_clauses t0 t1 t2 accum
blanchet@33192
   966
         | Const (@{const_name Let}, _) $ t1 $ t2 =>
blanchet@33192
   967
           do_term (betapply (t2, t1)) accum
blanchet@33192
   968
         | t1 $ t2 =>
blanchet@33192
   969
           let
blanchet@35385
   970
             val (m1, accum) = do_term t1 accum
blanchet@35385
   971
             val (m2, accum) = do_term t2 accum
blanchet@33192
   972
           in
blanchet@35812
   973
             let
blanchet@35812
   974
               val M11 = mtype_of_mterm m1 |> dest_MFun |> #1
blanchet@35812
   975
               val M2 = mtype_of_mterm m2
blanchet@35812
   976
             in (MApp (m1, m2), accum ||> add_is_sub_mtype M2 M11) end
blanchet@33192
   977
           end)
blanchet@38179
   978
        |> tap (fn (m, _) => trace_msg (fn () => "  \<Gamma> \<turnstile> " ^
blanchet@38179
   979
                                                 string_for_mterm ctxt m))
blanchet@33192
   980
  in do_term end
blanchet@33192
   981
blanchet@35665
   982
fun force_minus_funs 0 _ = I
blanchet@35665
   983
  | force_minus_funs n (M as MFun (M1, _, M2)) =
blanchet@40985
   984
    add_mtypes_equal M (MFun (M1, A Gen, M2)) #> force_minus_funs (n - 1) M2
blanchet@35665
   985
  | force_minus_funs _ M =
blanchet@35665
   986
    raise MTYPE ("Nitpick_Mono.force_minus_funs", [M], [])
blanchet@35665
   987
fun consider_general_equals mdata def (x as (_, T)) t1 t2 accum =
blanchet@35386
   988
  let
blanchet@35386
   989
    val (m1, accum) = consider_term mdata t1 accum
blanchet@35386
   990
    val (m2, accum) = consider_term mdata t2 accum
blanchet@35386
   991
    val M1 = mtype_of_mterm m1
blanchet@35386
   992
    val M2 = mtype_of_mterm m2
blanchet@35665
   993
    val accum = accum ||> add_mtypes_equal M1 M2
blanchet@35672
   994
    val body_M = fresh_mtype_for_type mdata false (nth_range_type 2 T)
blanchet@35665
   995
    val m = MApp (MApp (MRaw (Const x,
blanchet@40985
   996
                           MFun (M1, A Gen, MFun (M2, A Gen, body_M))), m1), m2)
blanchet@35386
   997
  in
blanchet@35665
   998
    (m, if def then
blanchet@35665
   999
          let val (head_m, arg_ms) = strip_mcomb m1 in
blanchet@35665
  1000
            accum ||> force_minus_funs (length arg_ms) (mtype_of_mterm head_m)
blanchet@35665
  1001
          end
blanchet@35665
  1002
        else
blanchet@35665
  1003
          accum)
blanchet@35386
  1004
  end
blanchet@35386
  1005
blanchet@35385
  1006
fun consider_general_formula (mdata as {hol_ctxt = {ctxt, ...}, ...}) =
blanchet@33192
  1007
  let
blanchet@35672
  1008
    val mtype_for = fresh_mtype_for_type mdata false
blanchet@35386
  1009
    val do_term = consider_term mdata
blanchet@35812
  1010
    fun do_formula sn t accum =
blanchet@33192
  1011
        let
blanchet@35386
  1012
          fun do_quantifier (quant_x as (quant_s, _)) abs_s abs_T body_t =
blanchet@33192
  1013
            let
blanchet@35385
  1014
              val abs_M = mtype_for abs_T
blanchet@40993
  1015
              val a = Gen (* FIXME: strengthen *)
blanchet@34982
  1016
              val side_cond = ((sn = Minus) = (quant_s = @{const_name Ex}))
blanchet@35386
  1017
              val (body_m, accum) =
blanchet@35665
  1018
                accum ||> side_cond ? add_mtype_is_complete abs_M
blanchet@40993
  1019
                      |>> push_bound (A a) abs_T abs_M |> do_formula sn body_t
blanchet@35386
  1020
              val body_M = mtype_of_mterm body_m
blanchet@33192
  1021
            in
blanchet@35665
  1022
              (MApp (MRaw (Const quant_x,
blanchet@40985
  1023
                           MFun (MFun (abs_M, A Gen, body_M), A Gen, body_M)),
blanchet@40985
  1024
                     MAbs (abs_s, abs_T, abs_M, A Gen, body_m)),
blanchet@35386
  1025
               accum |>> pop_bound)
blanchet@33192
  1026
            end
blanchet@35386
  1027
          fun do_equals x t1 t2 =
blanchet@33192
  1028
            case sn of
blanchet@35386
  1029
              Plus => do_term t accum
blanchet@35665
  1030
            | Minus => consider_general_equals mdata false x t1 t2 accum
blanchet@33192
  1031
        in
blanchet@38179
  1032
          (trace_msg (fn () => "  \<Gamma> \<turnstile> " ^
blanchet@38179
  1033
                               Syntax.string_of_term ctxt t ^ " : o\<^sup>" ^
blanchet@38179
  1034
                               string_for_sign sn ^ "?");
blanchet@37704
  1035
           case t of
blanchet@37704
  1036
             Const (x as (@{const_name all}, _)) $ Abs (s1, T1, t1) =>
blanchet@37704
  1037
             do_quantifier x s1 T1 t1
blanchet@37704
  1038
           | Const (x as (@{const_name "=="}, _)) $ t1 $ t2 => do_equals x t1 t2
blanchet@37704
  1039
           | @{const Trueprop} $ t1 =>
blanchet@37704
  1040
             let val (m1, accum) = do_formula sn t1 accum in
blanchet@37704
  1041
               (MApp (MRaw (@{const Trueprop}, mtype_for (bool_T --> prop_T)),
blanchet@37704
  1042
                      m1), accum)
blanchet@37704
  1043
             end
blanchet@37704
  1044
           | @{const Not} $ t1 =>
blanchet@40985
  1045
             let val (m1, accum) = do_formula (negate_sign sn) t1 accum in
blanchet@37704
  1046
               (MApp (MRaw (@{const Not}, mtype_for (bool_T --> bool_T)), m1),
blanchet@37704
  1047
                accum)
blanchet@37704
  1048
             end
blanchet@37704
  1049
           | Const (x as (@{const_name All}, _)) $ Abs (s1, T1, t1) =>
blanchet@37704
  1050
             do_quantifier x s1 T1 t1
blanchet@39345
  1051
           | Const (x0 as (@{const_name Ex}, T0))
blanchet@37704
  1052
             $ (t1 as Abs (s1, T1, t1')) =>
blanchet@37704
  1053
             (case sn of
blanchet@37704
  1054
                Plus => do_quantifier x0 s1 T1 t1'
blanchet@37704
  1055
              | Minus =>
blanchet@37704
  1056
                (* FIXME: Move elsewhere *)
blanchet@37704
  1057
                do_term (@{const Not}
blanchet@37704
  1058
                         $ (HOLogic.eq_const (domain_type T0) $ t1
blanchet@37704
  1059
                            $ Abs (Name.uu, T1, @{const False}))) accum)
haftmann@38864
  1060
           | Const (x as (@{const_name HOL.eq}, _)) $ t1 $ t2 =>
blanchet@37704
  1061
             do_equals x t1 t2
blanchet@37704
  1062
           | Const (@{const_name Let}, _) $ t1 $ t2 =>
blanchet@37704
  1063
             do_formula sn (betapply (t2, t1)) accum
blanchet@37704
  1064
           | (t0 as Const (s0, _)) $ t1 $ t2 =>
blanchet@38199
  1065
             if s0 = @{const_name "==>"} orelse
blanchet@38199
  1066
                s0 = @{const_name Pure.conjunction} orelse
blanchet@40997
  1067
                s0 = @{const_name conj} orelse
blanchet@40997
  1068
                s0 = @{const_name disj} orelse
blanchet@40997
  1069
                s0 = @{const_name implies} then
blanchet@37704
  1070
               let
blanchet@37704
  1071
                 val impl = (s0 = @{const_name "==>"} orelse
blanchet@40997
  1072
                             s0 = @{const_name implies})
blanchet@40985
  1073
                 val (m1, accum) =
blanchet@40985
  1074
                   do_formula (sn |> impl ? negate_sign) t1 accum
blanchet@37704
  1075
                 val (m2, accum) = do_formula sn t2 accum
blanchet@37704
  1076
               in
blanchet@37704
  1077
                 (MApp (MApp (MRaw (t0, mtype_for (fastype_of t0)), m1), m2),
blanchet@37704
  1078
                  accum)
blanchet@39316
  1079
               end
blanchet@37704
  1080
             else
blanchet@37704
  1081
               do_term t accum
blanchet@37704
  1082
           | _ => do_term t accum)
blanchet@33192
  1083
        end
blanchet@35386
  1084
        |> tap (fn (m, _) =>
blanchet@38179
  1085
                   trace_msg (fn () => "\<Gamma> \<turnstile> " ^
blanchet@38179
  1086
                                       string_for_mterm ctxt m ^ " : o\<^sup>" ^
blanchet@38179
  1087
                                       string_for_sign sn))
blanchet@33192
  1088
  in do_formula end
blanchet@33192
  1089
blanchet@33192
  1090
(* The harmless axiom optimization below is somewhat too aggressive in the face
blanchet@33192
  1091
   of (rather peculiar) user-defined axioms. *)
blanchet@33192
  1092
val harmless_consts =
blanchet@33192
  1093
  [@{const_name ord_class.less}, @{const_name ord_class.less_eq}]
blanchet@33192
  1094
val bounteous_consts = [@{const_name bisim}]
blanchet@33192
  1095
blanchet@35665
  1096
fun is_harmless_axiom ({no_harmless = true, ...} : mdata) _ = false
blanchet@39359
  1097
  | is_harmless_axiom {hol_ctxt = {thy, stds, ...}, ...} t =
blanchet@35665
  1098
    Term.add_consts t []
blanchet@39359
  1099
    |> filter_out (is_built_in_const thy stds)
blanchet@35665
  1100
    |> (forall (member (op =) harmless_consts o original_name o fst) orf
blanchet@35665
  1101
        exists (member (op =) bounteous_consts o fst))
blanchet@33192
  1102
blanchet@35665
  1103
fun consider_nondefinitional_axiom mdata t =
blanchet@35665
  1104
  if is_harmless_axiom mdata t then pair (MRaw (t, dummy_M))
blanchet@35386
  1105
  else consider_general_formula mdata Plus t
blanchet@33192
  1106
blanchet@37256
  1107
fun consider_definitional_axiom (mdata as {hol_ctxt = {ctxt, ...}, ...}) t =
blanchet@37256
  1108
  if not (is_constr_pattern_formula ctxt t) then
blanchet@35386
  1109
    consider_nondefinitional_axiom mdata t
blanchet@35665
  1110
  else if is_harmless_axiom mdata t then
blanchet@35386
  1111
    pair (MRaw (t, dummy_M))
blanchet@33192
  1112
  else
blanchet@33192
  1113
    let
blanchet@35672
  1114
      val mtype_for = fresh_mtype_for_type mdata false
blanchet@35386
  1115
      val do_term = consider_term mdata
blanchet@35386
  1116
      fun do_all quant_t abs_s abs_T body_t accum =
blanchet@35386
  1117
        let
blanchet@35386
  1118
          val abs_M = mtype_for abs_T
blanchet@35386
  1119
          val (body_m, accum) =
blanchet@40993
  1120
            accum |>> push_bound (A Gen) abs_T abs_M |> do_formula body_t
blanchet@35386
  1121
          val body_M = mtype_of_mterm body_m
blanchet@35386
  1122
        in
blanchet@40985
  1123
          (MApp (MRaw (quant_t, MFun (MFun (abs_M, A Gen, body_M), A Gen,
blanchet@40985
  1124
                       body_M)),
blanchet@40985
  1125
                 MAbs (abs_s, abs_T, abs_M, A Gen, body_m)),
blanchet@35386
  1126
           accum |>> pop_bound)
blanchet@33192
  1127
        end
blanchet@35386
  1128
      and do_conjunction t0 t1 t2 accum =
blanchet@33192
  1129
        let
blanchet@35386
  1130
          val (m1, accum) = do_formula t1 accum
blanchet@35386
  1131
          val (m2, accum) = do_formula t2 accum
blanchet@35386
  1132
        in
blanchet@35386
  1133
          (MApp (MApp (MRaw (t0, mtype_for (fastype_of t0)), m1), m2), accum)
blanchet@35386
  1134
        end
blanchet@35386
  1135
      and do_implies t0 t1 t2 accum =
blanchet@35386
  1136
        let
blanchet@35386
  1137
          val (m1, accum) = do_term t1 accum
blanchet@35386
  1138
          val (m2, accum) = do_formula t2 accum
blanchet@35386
  1139
        in
blanchet@35386
  1140
          (MApp (MApp (MRaw (t0, mtype_for (fastype_of t0)), m1), m2), accum)
blanchet@35386
  1141
        end
blanchet@35812
  1142
      and do_formula t accum =
blanchet@33192
  1143
          case t of
blanchet@35386
  1144
            (t0 as Const (@{const_name all}, _)) $ Abs (s1, T1, t1) =>
blanchet@35386
  1145
            do_all t0 s1 T1 t1 accum
blanchet@35665
  1146
          | @{const Trueprop} $ t1 =>
blanchet@35665
  1147
            let val (m1, accum) = do_formula t1 accum in
blanchet@35665
  1148
              (MApp (MRaw (@{const Trueprop}, mtype_for (bool_T --> prop_T)),
blanchet@35665
  1149
                     m1), accum)
blanchet@35665
  1150
            end
blanchet@35386
  1151
          | Const (x as (@{const_name "=="}, _)) $ t1 $ t2 =>
blanchet@35665
  1152
            consider_general_equals mdata true x t1 t2 accum
blanchet@35386
  1153
          | (t0 as @{const "==>"}) $ t1 $ t2 => do_implies t0 t1 t2 accum
blanchet@35386
  1154
          | (t0 as @{const Pure.conjunction}) $ t1 $ t2 =>
blanchet@35386
  1155
            do_conjunction t0 t1 t2 accum
blanchet@35386
  1156
          | (t0 as Const (@{const_name All}, _)) $ Abs (s0, T1, t1) =>
blanchet@35386
  1157
            do_all t0 s0 T1 t1 accum
haftmann@38864
  1158
          | Const (x as (@{const_name HOL.eq}, _)) $ t1 $ t2 =>
blanchet@35665
  1159
            consider_general_equals mdata true x t1 t2 accum
blanchet@40997
  1160
          | (t0 as @{const conj}) $ t1 $ t2 => do_conjunction t0 t1 t2 accum
blanchet@40997
  1161
          | (t0 as @{const implies}) $ t1 $ t2 => do_implies t0 t1 t2 accum
blanchet@33232
  1162
          | _ => raise TERM ("Nitpick_Mono.consider_definitional_axiom.\
blanchet@33192
  1163
                             \do_formula", [t])
blanchet@33192
  1164
    in do_formula t end
blanchet@33192
  1165
blanchet@40989
  1166
fun string_for_mtype_of_term ctxt asgs t M =
blanchet@40989
  1167
  Syntax.string_of_term ctxt t ^ " : " ^ string_for_mtype (resolve_mtype asgs M)
blanchet@33192
  1168
blanchet@40989
  1169
fun print_mtype_context ctxt asgs ({frees, consts, ...} : mtype_context) =
blanchet@38179
  1170
  trace_msg (fn () =>
blanchet@40989
  1171
      map (fn (x, M) => string_for_mtype_of_term ctxt asgs (Free x) M) frees @
blanchet@40989
  1172
      map (fn (x, M) => string_for_mtype_of_term ctxt asgs (Const x) M) consts
blanchet@37476
  1173
      |> cat_lines)
blanchet@33192
  1174
blanchet@35665
  1175
fun amass f t (ms, accum) =
blanchet@35386
  1176
  let val (m, accum) = f t accum in (m :: ms, accum) end
blanchet@35386
  1177
blanchet@40993
  1178
fun infer which no_harmless (hol_ctxt as {ctxt, ...}) binarize calculus alpha_T
blanchet@35665
  1179
          (nondef_ts, def_ts) =
blanchet@33192
  1180
  let
blanchet@38179
  1181
    val _ = trace_msg (fn () => "****** " ^ which ^ " analysis: " ^
blanchet@38179
  1182
                                string_for_mtype MAlpha ^ " is " ^
blanchet@38179
  1183
                                Syntax.string_of_typ ctxt alpha_T)
blanchet@35665
  1184
    val mdata as {max_fresh, constr_mcache, ...} =
blanchet@35665
  1185
      initial_mdata hol_ctxt binarize no_harmless alpha_T
blanchet@40994
  1186
    val accum = (initial_gamma, ([], []))
blanchet@35386
  1187
    val (nondef_ms, accum) =
blanchet@35665
  1188
      ([], accum) |> amass (consider_general_formula mdata Plus) (hd nondef_ts)
blanchet@35665
  1189
                  |> fold (amass (consider_nondefinitional_axiom mdata))
blanchet@35386
  1190
                          (tl nondef_ts)
blanchet@35386
  1191
    val (def_ms, (gamma, cset)) =
blanchet@35665
  1192
      ([], accum) |> fold (amass (consider_definitional_axiom mdata)) def_ts
blanchet@33192
  1193
  in
blanchet@40993
  1194
    case solve calculus (!max_fresh) cset of
blanchet@40989
  1195
      SOME asgs => (print_mtype_context ctxt asgs gamma;
blanchet@40989
  1196
                    SOME (asgs, (nondef_ms, def_ms), !constr_mcache))
blanchet@35665
  1197
    | _ => NONE
blanchet@33192
  1198
  end
blanchet@35812
  1199
  handle UNSOLVABLE () => NONE
blanchet@35812
  1200
       | MTYPE (loc, Ms, Ts) =>
blanchet@35665
  1201
         raise BAD (loc, commas (map string_for_mtype Ms @
blanchet@35665
  1202
                                 map (Syntax.string_of_typ ctxt) Ts))
blanchet@35665
  1203
       | MTERM (loc, ms) =>
blanchet@35665
  1204
         raise BAD (loc, commas (map (string_for_mterm ctxt) ms))
blanchet@35665
  1205
blanchet@40993
  1206
fun formulas_monotonic hol_ctxt =
blanchet@40993
  1207
  is_some oooo infer "Monotonicity" false hol_ctxt
blanchet@35665
  1208
blanchet@35665
  1209
fun fin_fun_constr T1 T2 =
blanchet@35665
  1210
  (@{const_name FinFun}, (T1 --> T2) --> Type (@{type_name fin_fun}, [T1, T2]))
blanchet@35665
  1211
blanchet@40993
  1212
fun finitize_funs (hol_ctxt as {thy, ctxt, stds, constr_cache, ...}) binarize
blanchet@40993
  1213
                  finitizes calculus alpha_T tsp =
blanchet@40993
  1214
  case infer "Finiteness" true hol_ctxt binarize calculus alpha_T tsp of
blanchet@40989
  1215
    SOME (asgs, msp, constr_mtypes) =>
blanchet@40989
  1216
    if forall (curry (op =) Gen o snd) asgs then
blanchet@35812
  1217
      tsp
blanchet@35812
  1218
    else
blanchet@35812
  1219
      let
blanchet@40988
  1220
        fun should_finitize T aa =
blanchet@35812
  1221
          case triple_lookup (type_match thy) finitizes T of
blanchet@35812
  1222
            SOME (SOME false) => false
blanchet@40989
  1223
          | _ => resolve_annotation_atom asgs aa = A Fls
blanchet@35812
  1224
        fun type_from_mtype T M =
blanchet@35812
  1225
          case (M, T) of
blanchet@35812
  1226
            (MAlpha, _) => T
blanchet@40988
  1227
          | (MFun (M1, aa, M2), Type (@{type_name fun}, Ts)) =>
blanchet@40988
  1228
            Type (if should_finitize T aa then @{type_name fin_fun}
blanchet@35812
  1229
                  else @{type_name fun}, map2 type_from_mtype Ts [M1, M2])
blanchet@38190
  1230
          | (MPair (M1, M2), Type (@{type_name prod}, Ts)) =>
blanchet@38190
  1231
            Type (@{type_name prod}, map2 type_from_mtype Ts [M1, M2])
blanchet@35812
  1232
          | (MType _, _) => T
blanchet@35812
  1233
          | _ => raise MTYPE ("Nitpick_Mono.finitize_funs.type_from_mtype",
blanchet@35812
  1234
                              [M], [T])
blanchet@35812
  1235
        fun finitize_constr (x as (s, T)) =
blanchet@35812
  1236
          (s, case AList.lookup (op =) constr_mtypes x of
blanchet@35812
  1237
                SOME M => type_from_mtype T M
blanchet@35812
  1238
              | NONE => T)
blanchet@37267
  1239
        fun term_from_mterm new_Ts old_Ts m =
blanchet@35812
  1240
          case m of
blanchet@35812
  1241
            MRaw (t, M) =>
blanchet@35812
  1242
            let
blanchet@37267
  1243
              val T = fastype_of1 (old_Ts, t)
blanchet@35812
  1244
              val T' = type_from_mtype T M
blanchet@35812
  1245
            in
blanchet@35812
  1246
              case t of
blanchet@35812
  1247
                Const (x as (s, _)) =>
blanchet@37476
  1248
                if s = @{const_name finite} then
blanchet@35812
  1249
                  case domain_type T' of
blanchet@35812
  1250
                    set_T' as Type (@{type_name fin_fun}, _) =>
blanchet@35812
  1251
                    Abs (Name.uu, set_T', @{const True})
blanchet@35812
  1252
                  | _ => Const (s, T')
blanchet@35812
  1253
                else if s = @{const_name "=="} orelse
haftmann@38864
  1254
                        s = @{const_name HOL.eq} then
blanchet@37476
  1255
                  let
blanchet@37476
  1256
                    val T =
blanchet@37476
  1257
                      case T' of
blanchet@37476
  1258
                        Type (_, [T1, Type (_, [T2, T3])]) =>
blanchet@37476
  1259
                        T1 --> T2 --> T3
blanchet@37476
  1260
                      | _ => raise TYPE ("Nitpick_Mono.finitize_funs.\
blanchet@37476
  1261
                                         \term_from_mterm", [T, T'], [])
blanchet@37476
  1262
                  in coerce_term hol_ctxt new_Ts T' T (Const (s, T)) end
blanchet@39359
  1263
                else if is_built_in_const thy stds x then
blanchet@37267
  1264
                  coerce_term hol_ctxt new_Ts T' T t
blanchet@37256
  1265
                else if is_constr ctxt stds x then
blanchet@35812
  1266
                  Const (finitize_constr x)
blanchet@35812
  1267
                else if is_sel s then
blanchet@35812
  1268
                  let
blanchet@35812
  1269
                    val n = sel_no_from_name s
blanchet@35812
  1270
                    val x' =
blanchet@35812
  1271
                      x |> binarized_and_boxed_constr_for_sel hol_ctxt binarize
blanchet@35812
  1272
                        |> finitize_constr
blanchet@35812
  1273
                    val x'' =
blanchet@35812
  1274
                      binarized_and_boxed_nth_sel_for_constr hol_ctxt binarize
blanchet@35812
  1275
                                                             x' n
blanchet@35812
  1276
                  in Const x'' end
blanchet@35812
  1277
                else
blanchet@35812
  1278
                  Const (s, T')
blanchet@35812
  1279
              | Free (s, T) => Free (s, type_from_mtype T M)
blanchet@35812
  1280
              | Bound _ => t
blanchet@35812
  1281
              | _ => raise MTERM ("Nitpick_Mono.finitize_funs.term_from_mterm",
blanchet@35812
  1282
                                  [m])
blanchet@35812
  1283
            end
blanchet@35812
  1284
          | MApp (m1, m2) =>
blanchet@35812
  1285
            let
blanchet@37267
  1286
              val (t1, t2) = pairself (term_from_mterm new_Ts old_Ts) (m1, m2)
blanchet@37267
  1287
              val (T1, T2) = pairself (curry fastype_of1 new_Ts) (t1, t2)
blanchet@35812
  1288
              val (t1', T2') =
blanchet@35812
  1289
                case T1 of
blanchet@39316
  1290
                  Type (s, [T11, T12]) =>
blanchet@35812
  1291
                  (if s = @{type_name fin_fun} then
blanchet@37256
  1292
                     select_nth_constr_arg ctxt stds (fin_fun_constr T11 T12) t1
blanchet@35812
  1293
                                           0 (T11 --> T12)
blanchet@35812
  1294
                   else
blanchet@35812
  1295
                     t1, T11)
blanchet@35812
  1296
                | _ => raise TYPE ("Nitpick_Mono.finitize_funs.term_from_mterm",
blanchet@35812
  1297
                                   [T1], [])
blanchet@37267
  1298
            in betapply (t1', coerce_term hol_ctxt new_Ts T2' T2 t2) end
blanchet@40988
  1299
          | MAbs (s, old_T, M, aa, m') =>
blanchet@35812
  1300
            let
blanchet@37267
  1301
              val new_T = type_from_mtype old_T M
blanchet@37267
  1302
              val t' = term_from_mterm (new_T :: new_Ts) (old_T :: old_Ts) m'
blanchet@37267
  1303
              val T' = fastype_of1 (new_T :: new_Ts, t')
blanchet@35812
  1304
            in
blanchet@37267
  1305
              Abs (s, new_T, t')
blanchet@40988
  1306
              |> should_finitize (new_T --> T') aa
blanchet@37267
  1307
                 ? construct_value ctxt stds (fin_fun_constr new_T T') o single
blanchet@35812
  1308
            end
blanchet@35812
  1309
      in
blanchet@35812
  1310
        Unsynchronized.change constr_cache (map (apsnd (map finitize_constr)));
blanchet@37267
  1311
        pairself (map (term_from_mterm [] [])) msp
blanchet@35812
  1312
      end
blanchet@35665
  1313
  | NONE => tsp
blanchet@33192
  1314
blanchet@33192
  1315
end;