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