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