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