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