src/HOL/Tools/Nitpick/nitpick_mono.ML
author blanchet
Thu Feb 25 16:33:39 2010 +0100 (2010-02-25)
changeset 35385 29f81babefd7
parent 35384 88dbcfe75c45
child 35386 45a4e19d3ebd
permissions -rw-r--r--
improved precision of infinite "shallow" datatypes in Nitpick;
e.g. strings used for variable names, instead of an opaque type
     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 * term -> bool
    14 end;
    15 
    16 structure Nitpick_Mono : NITPICK_MONO =
    17 struct
    18 
    19 open Nitpick_Util
    20 open Nitpick_HOL
    21 
    22 type var = int
    23 
    24 datatype sign = Plus | Minus
    25 datatype sign_atom = S of sign | V of var
    26 
    27 type literal = var * sign
    28 
    29 datatype mtyp =
    30   MAlpha |
    31   MFun of mtyp * sign_atom * mtyp |
    32   MPair of mtyp * mtyp |
    33   MType of string * mtyp list |
    34   MRec of string * typ list
    35 
    36 datatype mterm =
    37   MAtom of term * mtyp |
    38   MAbs of string * typ * mtyp * sign_atom * mterm |
    39   MApp of mterm * mterm
    40 
    41 type mdata =
    42   {hol_ctxt: hol_context,
    43    binarize: bool,
    44    alpha_T: typ,
    45    max_fresh: int Unsynchronized.ref,
    46    datatype_cache: ((string * typ list) * mtyp) list Unsynchronized.ref,
    47    constr_cache: (styp * mtyp) list Unsynchronized.ref}
    48 
    49 exception MTYPE of string * mtyp list
    50 
    51 (* string -> unit *)
    52 fun print_g (_ : string) = ()
    53 
    54 (* var -> string *)
    55 val string_for_var = signed_string_of_int
    56 (* string -> var list -> string *)
    57 fun string_for_vars sep [] = "0\<^bsub>" ^ sep ^ "\<^esub>"
    58   | string_for_vars sep xs = space_implode sep (map string_for_var xs)
    59 fun subscript_string_for_vars sep xs =
    60   if null xs then "" else "\<^bsub>" ^ string_for_vars sep xs ^ "\<^esub>"
    61 
    62 (* sign -> string *)
    63 fun string_for_sign Plus = "+"
    64   | string_for_sign Minus = "-"
    65 
    66 (* sign -> sign -> sign *)
    67 fun xor sn1 sn2 = if sn1 = sn2 then Plus else Minus
    68 (* sign -> sign *)
    69 val negate = xor Minus
    70 
    71 (* sign_atom -> string *)
    72 fun string_for_sign_atom (S sn) = string_for_sign sn
    73   | string_for_sign_atom (V j) = string_for_var j
    74 
    75 (* literal -> string *)
    76 fun string_for_literal (x, sn) = string_for_var x ^ " = " ^ string_for_sign sn
    77 
    78 val bool_M = MType (@{type_name bool}, [])
    79 val irrelevant_M = MType (nitpick_prefix ^ "irrelevant", [])
    80 
    81 (* mtyp -> bool *)
    82 fun is_MRec (MRec _) = true
    83   | is_MRec _ = false
    84 (* mtyp -> mtyp * sign_atom * mtyp *)
    85 fun dest_MFun (MFun z) = z
    86   | dest_MFun M = raise MTYPE ("Nitpick_Mono.dest_MFun", [M])
    87 
    88 val no_prec = 100
    89 
    90 (* mtyp -> int *)
    91 fun precedence_of_mtype (MFun _) = 1
    92   | precedence_of_mtype (MPair _) = 2
    93   | precedence_of_mtype _ = no_prec
    94 
    95 (* mtyp -> string *)
    96 val string_for_mtype =
    97   let
    98     (* int -> mtyp -> string *)
    99     fun aux outer_prec M =
   100       let
   101         val prec = precedence_of_mtype M
   102         val need_parens = (prec < outer_prec)
   103       in
   104         (if need_parens then "(" else "") ^
   105         (case M of
   106            MAlpha => "\<alpha>"
   107          | MFun (M1, a, M2) =>
   108            aux (prec + 1) M1 ^ " \<Rightarrow>\<^bsup>" ^
   109            string_for_sign_atom a ^ "\<^esup> " ^ aux prec M2
   110          | MPair (M1, M2) => aux (prec + 1) M1 ^ " \<times> " ^ aux prec M2
   111          | MType (s, []) =>
   112            if s = @{type_name prop} orelse s = @{type_name bool} then "o" else s
   113          | MType (s, Ms) => "(" ^ commas (map (aux 0) Ms) ^ ") " ^ s
   114          | MRec (s, _) => "[" ^ s ^ "]") ^
   115         (if need_parens then ")" else "")
   116       end
   117   in aux 0 end
   118 
   119 (* mtyp -> mtyp list *)
   120 fun flatten_mtype (MPair (M1, M2)) = maps flatten_mtype [M1, M2]
   121   | flatten_mtype (MType (_, Ms)) = maps flatten_mtype Ms
   122   | flatten_mtype M = [M]
   123 
   124 (* mterm -> bool *)
   125 fun precedence_of_mterm (MAtom _) = no_prec
   126   | precedence_of_mterm (MAbs _) = 1
   127   | precedence_of_mterm (MApp _) = 2
   128 
   129 (* Proof.context -> mterm -> string *)
   130 fun string_for_mterm ctxt =
   131   let
   132     (* mtype -> string *)
   133     fun mtype_annotation M = "\<^bsup>" ^ string_for_mtype M ^ "\<^esup>"
   134     (* int -> mterm -> string *)
   135     fun aux outer_prec m =
   136       let
   137         val prec = precedence_of_mterm m
   138         val need_parens = (prec < outer_prec)
   139       in
   140         (if need_parens then "(" else "") ^
   141         (case m of
   142            MAtom (t, M) => Syntax.string_of_term ctxt t ^ mtype_annotation M
   143          | MAbs (s, _, M, a, m) =>
   144            "\<lambda>" ^ s ^ mtype_annotation M ^ ".\<^bsup>" ^
   145            string_for_sign_atom a ^ "\<^esup> " ^ aux prec m
   146          | MApp (m1, m2) => aux prec m1 ^ " " ^ aux (prec + 1) m2) ^
   147         (if need_parens then ")" else "")
   148       end
   149   in aux 0 end
   150 
   151 (* mterm -> mtyp *)
   152 fun mtype_of_mterm (MAtom (_, M)) = M
   153   | mtype_of_mterm (MAbs (_, _, M, a, m)) = MFun (M, a, mtype_of_mterm m)
   154   | mtype_of_mterm (MApp (m1, _)) =
   155     case mtype_of_mterm m1 of
   156       MFun (_, _, M12) => M12
   157     | M1 => raise MTYPE ("Nitpick_Mono.mtype_of_mterm", [M1])
   158 
   159 (* hol_context -> bool -> typ -> mdata *)
   160 fun initial_mdata hol_ctxt binarize alpha_T =
   161   ({hol_ctxt = hol_ctxt, binarize = binarize, alpha_T = alpha_T,
   162     max_fresh = Unsynchronized.ref 0, datatype_cache = Unsynchronized.ref [],
   163     constr_cache = Unsynchronized.ref []} : mdata)
   164 
   165 (* typ -> typ -> bool *)
   166 fun could_exist_alpha_subtype alpha_T (T as Type (_, Ts)) =
   167     T = alpha_T orelse (not (is_fp_iterator_type T) andalso
   168                         exists (could_exist_alpha_subtype alpha_T) Ts)
   169   | could_exist_alpha_subtype alpha_T T = (T = alpha_T)
   170 (* theory -> typ -> typ -> bool *)
   171 fun could_exist_alpha_sub_mtype _ (alpha_T as TFree _) T =
   172     could_exist_alpha_subtype alpha_T T
   173   | could_exist_alpha_sub_mtype thy alpha_T T =
   174     (T = alpha_T orelse is_datatype thy [(NONE, true)] T)
   175 
   176 (* mtyp -> bool *)
   177 fun exists_alpha_sub_mtype MAlpha = true
   178   | exists_alpha_sub_mtype (MFun (M1, _, M2)) =
   179     exists exists_alpha_sub_mtype [M1, M2]
   180   | exists_alpha_sub_mtype (MPair (M1, M2)) =
   181     exists exists_alpha_sub_mtype [M1, M2]
   182   | exists_alpha_sub_mtype (MType (_, Ms)) = exists exists_alpha_sub_mtype Ms
   183   | exists_alpha_sub_mtype (MRec _) = true
   184 
   185 (* mtyp -> bool *)
   186 fun exists_alpha_sub_mtype_fresh MAlpha = true
   187   | exists_alpha_sub_mtype_fresh (MFun (_, V _, _)) = true
   188   | exists_alpha_sub_mtype_fresh (MFun (_, _, M2)) =
   189     exists_alpha_sub_mtype_fresh M2
   190   | exists_alpha_sub_mtype_fresh (MPair (M1, M2)) =
   191     exists exists_alpha_sub_mtype_fresh [M1, M2]
   192   | exists_alpha_sub_mtype_fresh (MType (_, Ms)) =
   193     exists exists_alpha_sub_mtype_fresh Ms
   194   | exists_alpha_sub_mtype_fresh (MRec _) = true
   195 
   196 (* string * typ list -> mtyp list -> mtyp *)
   197 fun constr_mtype_for_binders z Ms =
   198   fold_rev (fn M => curry3 MFun M (S Minus)) Ms (MRec z)
   199 
   200 (* ((string * typ list) * mtyp) list -> mtyp list -> mtyp -> mtyp *)
   201 fun repair_mtype _ _ MAlpha = MAlpha
   202   | repair_mtype cache seen (MFun (M1, a, M2)) =
   203     MFun (repair_mtype cache seen M1, a, repair_mtype cache seen M2)
   204   | repair_mtype cache seen (MPair Mp) =
   205     MPair (pairself (repair_mtype cache seen) Mp)
   206   | repair_mtype cache seen (MType (s, Ms)) =
   207     MType (s, maps (flatten_mtype o repair_mtype cache seen) Ms)
   208   | repair_mtype cache seen (MRec (z as (s, _))) =
   209     case AList.lookup (op =) cache z |> the of
   210       MRec _ => MType (s, [])
   211     | M => if member (op =) seen M then MType (s, [])
   212            else repair_mtype cache (M :: seen) M
   213 
   214 (* ((string * typ list) * mtyp) list Unsynchronized.ref -> unit *)
   215 fun repair_datatype_cache cache =
   216   let
   217     (* (string * typ list) * mtyp -> unit *)
   218     fun repair_one (z, M) =
   219       Unsynchronized.change cache
   220           (AList.update (op =) (z, repair_mtype (!cache) [] M))
   221   in List.app repair_one (rev (!cache)) end
   222 
   223 (* (typ * mtyp) list -> (styp * mtyp) list Unsynchronized.ref -> unit *)
   224 fun repair_constr_cache dtype_cache constr_cache =
   225   let
   226     (* styp * mtyp -> unit *)
   227     fun repair_one (x, M) =
   228       Unsynchronized.change constr_cache
   229           (AList.update (op =) (x, repair_mtype dtype_cache [] M))
   230   in List.app repair_one (!constr_cache) end
   231 
   232 (* mdata -> typ -> typ -> mtyp * sign_atom * mtyp *)
   233 fun fresh_mfun_for_fun_type (mdata as {max_fresh, ...} : mdata) T1 T2 =
   234   let
   235     val M1 = fresh_mtype_for_type mdata T1
   236     val M2 = fresh_mtype_for_type mdata T2
   237     val a = if is_boolean_type (body_type T2) andalso
   238                exists_alpha_sub_mtype_fresh M1 then
   239               V (Unsynchronized.inc max_fresh)
   240             else
   241               S Minus
   242   in (M1, a, M2) end
   243 (* mdata -> typ -> mtyp *)
   244 and fresh_mtype_for_type (mdata as {hol_ctxt as {thy, ...}, binarize, alpha_T,
   245                                     datatype_cache, constr_cache, ...}) =
   246   let
   247     (* typ -> typ -> mtyp *)
   248     val do_fun = MFun oo fresh_mfun_for_fun_type mdata
   249     (* typ -> mtyp *)
   250     fun do_type T =
   251       if T = alpha_T then
   252         MAlpha
   253       else case T of
   254         Type ("fun", [T1, T2]) => do_fun T1 T2
   255       | Type (@{type_name fun_box}, [T1, T2]) => do_fun T1 T2
   256       | Type ("*", [T1, T2]) => MPair (pairself do_type (T1, T2))
   257       | Type (z as (s, _)) =>
   258         if could_exist_alpha_sub_mtype thy alpha_T T then
   259           case AList.lookup (op =) (!datatype_cache) z of
   260             SOME M => M
   261           | NONE =>
   262             let
   263               val _ = Unsynchronized.change datatype_cache (cons (z, MRec z))
   264               val xs = binarized_and_boxed_datatype_constrs hol_ctxt binarize T
   265               val (all_Ms, constr_Ms) =
   266                 fold_rev (fn (_, T') => fn (all_Ms, constr_Ms) =>
   267                              let
   268                                val binder_Ms = map do_type (binder_types T')
   269                                val new_Ms = filter exists_alpha_sub_mtype_fresh
   270                                                    binder_Ms
   271                                val constr_M = constr_mtype_for_binders z
   272                                                                        binder_Ms
   273                              in
   274                                (union (op =) new_Ms all_Ms,
   275                                 constr_M :: constr_Ms)
   276                              end)
   277                          xs ([], [])
   278               val M = MType (s, all_Ms)
   279               val _ = Unsynchronized.change datatype_cache
   280                           (AList.update (op =) (z, M))
   281               val _ = Unsynchronized.change constr_cache
   282                           (append (xs ~~ constr_Ms))
   283             in
   284               if forall (not o is_MRec o snd) (!datatype_cache) then
   285                 (repair_datatype_cache datatype_cache;
   286                  repair_constr_cache (!datatype_cache) constr_cache;
   287                  AList.lookup (op =) (!datatype_cache) z |> the)
   288               else
   289                 M
   290             end
   291         else
   292           MType (s, [])
   293       | _ => MType (Refute.string_of_typ T, [])
   294   in do_type end
   295 
   296 (* mtyp -> mtyp list *)
   297 fun prodM_factors (MPair (M1, M2)) = maps prodM_factors [M1, M2]
   298   | prodM_factors M = [M]
   299 (* mtyp -> mtyp list * mtyp *)
   300 fun curried_strip_mtype (MFun (M1, S Minus, M2)) =
   301     curried_strip_mtype M2 |>> append (prodM_factors M1)
   302   | curried_strip_mtype M = ([], M)
   303 (* string -> mtyp -> mtyp *)
   304 fun sel_mtype_from_constr_mtype s M =
   305   let val (arg_Ms, dataM) = curried_strip_mtype M in
   306     MFun (dataM, S Minus,
   307           case sel_no_from_name s of ~1 => bool_M | n => nth arg_Ms n)
   308   end
   309 
   310 (* mdata -> styp -> mtyp *)
   311 fun mtype_for_constr (mdata as {hol_ctxt = {thy, ...}, alpha_T, constr_cache,
   312                                 ...}) (x as (_, T)) =
   313   if could_exist_alpha_sub_mtype thy alpha_T T then
   314     case AList.lookup (op =) (!constr_cache) x of
   315       SOME M => M
   316     | NONE => if T = alpha_T then
   317                 let val M = fresh_mtype_for_type mdata T in
   318                   (Unsynchronized.change constr_cache (cons (x, M)); M)
   319                 end
   320               else
   321                 (fresh_mtype_for_type mdata (body_type T);
   322                  AList.lookup (op =) (!constr_cache) x |> the)
   323   else
   324     fresh_mtype_for_type mdata T
   325 fun mtype_for_sel (mdata as {hol_ctxt, binarize, ...}) (x as (s, _)) =
   326   x |> binarized_and_boxed_constr_for_sel hol_ctxt binarize
   327     |> mtype_for_constr mdata |> sel_mtype_from_constr_mtype s
   328 
   329 (* literal list -> mtyp -> mtyp *)
   330 fun instantiate_mtype lits =
   331   let
   332     (* mtyp -> mtyp *)
   333     fun aux MAlpha = MAlpha
   334       | aux (MFun (M1, V x, M2)) =
   335         let
   336           val a = case AList.lookup (op =) lits x of
   337                     SOME sn => S sn
   338                   | NONE => V x
   339         in MFun (aux M1, a, aux M2) end
   340       | aux (MFun (M1, a, M2)) = MFun (aux M1, a, aux M2)
   341       | aux (MPair Mp) = MPair (pairself aux Mp)
   342       | aux (MType (s, Ms)) = MType (s, map aux Ms)
   343       | aux (MRec z) = MRec z
   344   in aux end
   345 
   346 datatype comp_op = Eq | Leq
   347 
   348 type comp = sign_atom * sign_atom * comp_op * var list
   349 type sign_expr = literal list
   350 
   351 datatype constraint_set =
   352   UnsolvableCSet |
   353   CSet of literal list * comp list * sign_expr list
   354 
   355 (* comp_op -> string *)
   356 fun string_for_comp_op Eq = "="
   357   | string_for_comp_op Leq = "\<le>"
   358 
   359 (* sign_expr -> string *)
   360 fun string_for_sign_expr [] = "\<bot>"
   361   | string_for_sign_expr lits =
   362     space_implode " \<or> " (map string_for_literal lits)
   363 
   364 (* constraint_set *)
   365 val slack = CSet ([], [], [])
   366 
   367 (* literal -> literal list option -> literal list option *)
   368 fun do_literal _ NONE = NONE
   369   | do_literal (x, sn) (SOME lits) =
   370     case AList.lookup (op =) lits x of
   371       SOME sn' => if sn = sn' then SOME lits else NONE
   372     | NONE => SOME ((x, sn) :: lits)
   373 
   374 (* comp_op -> var list -> sign_atom -> sign_atom -> literal list * comp list
   375    -> (literal list * comp list) option *)
   376 fun do_sign_atom_comp Eq [] a1 a2 (accum as (lits, comps)) =
   377     (case (a1, a2) of
   378        (S sn1, S sn2) => if sn1 = sn2 then SOME accum else NONE
   379      | (V x1, S sn2) =>
   380        Option.map (rpair comps) (do_literal (x1, sn2) (SOME lits))
   381      | (V _, V _) => SOME (lits, insert (op =) (a1, a2, Eq, []) comps)
   382      | _ => do_sign_atom_comp Eq [] a2 a1 accum)
   383   | do_sign_atom_comp Leq [] a1 a2 (accum as (lits, comps)) =
   384     (case (a1, a2) of
   385        (_, S Minus) => SOME accum
   386      | (S Plus, _) => SOME accum
   387      | (S Minus, S Plus) => NONE
   388      | (V _, V _) => SOME (lits, insert (op =) (a1, a2, Leq, []) comps)
   389      | _ => do_sign_atom_comp Eq [] a1 a2 accum)
   390   | do_sign_atom_comp cmp xs a1 a2 (lits, comps) =
   391     SOME (lits, insert (op =) (a1, a2, cmp, xs) comps)
   392 
   393 (* comp -> var list -> mtyp -> mtyp -> (literal list * comp list) option
   394    -> (literal list * comp list) option *)
   395 fun do_mtype_comp _ _ _ _ NONE = NONE
   396   | do_mtype_comp _ _ MAlpha MAlpha accum = accum
   397   | do_mtype_comp Eq xs (MFun (M11, a1, M12)) (MFun (M21, a2, M22))
   398                   (SOME accum) =
   399      accum |> do_sign_atom_comp Eq xs a1 a2 |> do_mtype_comp Eq xs M11 M21
   400            |> do_mtype_comp Eq xs M12 M22
   401   | do_mtype_comp Leq xs (MFun (M11, a1, M12)) (MFun (M21, a2, M22))
   402                   (SOME accum) =
   403     (if exists_alpha_sub_mtype M11 then
   404        accum |> do_sign_atom_comp Leq xs a1 a2
   405              |> do_mtype_comp Leq xs M21 M11
   406              |> (case a2 of
   407                    S Minus => I
   408                  | S Plus => do_mtype_comp Leq xs M11 M21
   409                  | V x => do_mtype_comp Leq (x :: xs) M11 M21)
   410      else
   411        SOME accum)
   412     |> do_mtype_comp Leq xs M12 M22
   413   | do_mtype_comp cmp xs (M1 as MPair (M11, M12)) (M2 as MPair (M21, M22))
   414                   accum =
   415     (accum |> fold (uncurry (do_mtype_comp cmp xs)) [(M11, M21), (M12, M22)]
   416      handle Library.UnequalLengths =>
   417             raise MTYPE ("Nitpick_Mono.do_mtype_comp", [M1, M2]))
   418   | do_mtype_comp _ _ (MType _) (MType _) accum =
   419     accum (* no need to compare them thanks to the cache *)
   420   | do_mtype_comp _ _ M1 M2 _ =
   421     raise MTYPE ("Nitpick_Mono.do_mtype_comp", [M1, M2])
   422 
   423 (* comp_op -> mtyp -> mtyp -> constraint_set -> constraint_set *)
   424 fun add_mtype_comp _ _ _ UnsolvableCSet = UnsolvableCSet
   425   | add_mtype_comp cmp M1 M2 (CSet (lits, comps, sexps)) =
   426     (print_g ("*** Add " ^ string_for_mtype M1 ^ " " ^ string_for_comp_op cmp ^
   427               " " ^ string_for_mtype M2);
   428      case do_mtype_comp cmp [] M1 M2 (SOME (lits, comps)) of
   429        NONE => (print_g "**** Unsolvable"; UnsolvableCSet)
   430      | SOME (lits, comps) => CSet (lits, comps, sexps))
   431 
   432 (* mtyp -> mtyp -> constraint_set -> constraint_set *)
   433 val add_mtypes_equal = add_mtype_comp Eq
   434 val add_is_sub_mtype = add_mtype_comp Leq
   435 
   436 (* sign -> sign_expr -> mtyp -> (literal list * sign_expr list) option
   437    -> (literal list * sign_expr list) option *)
   438 fun do_notin_mtype_fv _ _ _ NONE = NONE
   439   | do_notin_mtype_fv Minus _ MAlpha accum = accum
   440   | do_notin_mtype_fv Plus [] MAlpha _ = NONE
   441   | do_notin_mtype_fv Plus [(x, sn)] MAlpha (SOME (lits, sexps)) =
   442     SOME lits |> do_literal (x, sn) |> Option.map (rpair sexps)
   443   | do_notin_mtype_fv Plus sexp MAlpha (SOME (lits, sexps)) =
   444     SOME (lits, insert (op =) sexp sexps)
   445   | do_notin_mtype_fv sn sexp (MFun (M1, S sn', M2)) accum =
   446     accum |> (if sn' = Plus andalso sn = Plus then
   447                 do_notin_mtype_fv Plus sexp M1
   448               else
   449                 I)
   450           |> (if sn' = Minus orelse sn = Plus then
   451                 do_notin_mtype_fv Minus sexp M1
   452               else
   453                 I)
   454           |> do_notin_mtype_fv sn sexp M2
   455   | do_notin_mtype_fv Plus sexp (MFun (M1, V x, M2)) accum =
   456     accum |> (case do_literal (x, Minus) (SOME sexp) of
   457                 NONE => I
   458               | SOME sexp' => do_notin_mtype_fv Plus sexp' M1)
   459           |> do_notin_mtype_fv Minus sexp M1
   460           |> do_notin_mtype_fv Plus sexp M2
   461   | do_notin_mtype_fv Minus sexp (MFun (M1, V x, M2)) accum =
   462     accum |> (case do_literal (x, Plus) (SOME sexp) of
   463                 NONE => I
   464               | SOME sexp' => do_notin_mtype_fv Plus sexp' M1)
   465           |> do_notin_mtype_fv Minus sexp M2
   466   | do_notin_mtype_fv sn sexp (MPair (M1, M2)) accum =
   467     accum |> fold (do_notin_mtype_fv sn sexp) [M1, M2]
   468   | do_notin_mtype_fv sn sexp (MType (_, Ms)) accum =
   469     accum |> fold (do_notin_mtype_fv sn sexp) Ms
   470   | do_notin_mtype_fv _ _ M _ =
   471     raise MTYPE ("Nitpick_Mono.do_notin_mtype_fv", [M])
   472 
   473 (* sign -> mtyp -> constraint_set -> constraint_set *)
   474 fun add_notin_mtype_fv _ _ UnsolvableCSet = UnsolvableCSet
   475   | add_notin_mtype_fv sn M (CSet (lits, comps, sexps)) =
   476     (print_g ("*** Add " ^ string_for_mtype M ^ " is right-" ^
   477               (case sn of Minus => "unique" | Plus => "total") ^ ".");
   478      case do_notin_mtype_fv sn [] M (SOME (lits, sexps)) of
   479        NONE => (print_g "**** Unsolvable"; UnsolvableCSet)
   480      | SOME (lits, sexps) => CSet (lits, comps, sexps))
   481 
   482 (* mtyp -> constraint_set -> constraint_set *)
   483 val add_mtype_is_right_unique = add_notin_mtype_fv Minus
   484 val add_mtype_is_right_total = add_notin_mtype_fv Plus
   485 
   486 val bool_from_minus = true
   487 
   488 (* sign -> bool *)
   489 fun bool_from_sign Plus = not bool_from_minus
   490   | bool_from_sign Minus = bool_from_minus
   491 (* bool -> sign *)
   492 fun sign_from_bool b = if b = bool_from_minus then Minus else Plus
   493 
   494 (* literal -> PropLogic.prop_formula *)
   495 fun prop_for_literal (x, sn) =
   496   (not (bool_from_sign sn) ? PropLogic.Not) (PropLogic.BoolVar x)
   497 (* sign_atom -> PropLogic.prop_formula *)
   498 fun prop_for_sign_atom_eq (S sn', sn) =
   499     if sn = sn' then PropLogic.True else PropLogic.False
   500   | prop_for_sign_atom_eq (V x, sn) = prop_for_literal (x, sn)
   501 (* sign_expr -> PropLogic.prop_formula *)
   502 fun prop_for_sign_expr xs = PropLogic.exists (map prop_for_literal xs)
   503 (* var list -> sign -> PropLogic.prop_formula *)
   504 fun prop_for_exists_eq xs sn =
   505   PropLogic.exists (map (fn x => prop_for_literal (x, sn)) xs)
   506 (* comp -> PropLogic.prop_formula *)
   507 fun prop_for_comp (a1, a2, Eq, []) =
   508     PropLogic.SAnd (prop_for_comp (a1, a2, Leq, []),
   509                     prop_for_comp (a2, a1, Leq, []))
   510   | prop_for_comp (a1, a2, Leq, []) =
   511     PropLogic.SOr (prop_for_sign_atom_eq (a1, Plus),
   512                    prop_for_sign_atom_eq (a2, Minus))
   513   | prop_for_comp (a1, a2, cmp, xs) =
   514     PropLogic.SOr (prop_for_exists_eq xs Minus, prop_for_comp (a1, a2, cmp, []))
   515 
   516 (* var -> (int -> bool option) -> literal list -> literal list *)
   517 fun literals_from_assignments max_var assigns lits =
   518   fold (fn x => fn accum =>
   519            if AList.defined (op =) lits x then
   520              accum
   521            else case assigns x of
   522              SOME b => (x, sign_from_bool b) :: accum
   523            | NONE => accum) (max_var downto 1) lits
   524 
   525 (* comp -> string *)
   526 fun string_for_comp (a1, a2, cmp, xs) =
   527   string_for_sign_atom a1 ^ " " ^ string_for_comp_op cmp ^
   528   subscript_string_for_vars " \<and> " xs ^ " " ^ string_for_sign_atom a2
   529 
   530 (* literal list -> comp list -> sign_expr list -> unit *)
   531 fun print_problem lits comps sexps =
   532   print_g ("*** Problem:\n" ^ cat_lines (map string_for_literal lits @
   533                                          map string_for_comp comps @
   534                                          map string_for_sign_expr sexps))
   535 
   536 (* literal list -> unit *)
   537 fun print_solution lits =
   538   let val (pos, neg) = List.partition (curry (op =) Plus o snd) lits in
   539     print_g ("*** Solution:\n" ^
   540              "+: " ^ commas (map (string_for_var o fst) pos) ^ "\n" ^
   541              "-: " ^ commas (map (string_for_var o fst) neg))
   542   end
   543 
   544 (* var -> constraint_set -> literal list option *)
   545 fun solve _ UnsolvableCSet = (print_g "*** Problem: Unsolvable"; NONE)
   546   | solve max_var (CSet (lits, comps, sexps)) =
   547     let
   548       val _ = print_problem lits comps sexps
   549       val prop = PropLogic.all (map prop_for_literal lits @
   550                                 map prop_for_comp comps @
   551                                 map prop_for_sign_expr sexps)
   552       (* use the first ML solver (to avoid startup overhead) *)
   553       val solvers = !SatSolver.solvers
   554                     |> filter (member (op =) ["dptsat", "dpll"] o fst)
   555     in
   556       case snd (hd solvers) prop of
   557         SatSolver.SATISFIABLE assigns =>
   558         SOME (literals_from_assignments max_var assigns lits
   559               |> tap print_solution)
   560       | _ => NONE
   561     end
   562 
   563 type mtype_schema = mtyp * constraint_set
   564 type mtype_context =
   565   {bounds: mtyp list,
   566    frees: (styp * mtyp) list,
   567    consts: (styp * mtyp) list}
   568 
   569 type accumulator = mtype_context * constraint_set
   570 
   571 val initial_gamma = {bounds = [], frees = [], consts = []}
   572 val unsolvable_accum = (initial_gamma, UnsolvableCSet)
   573 
   574 (* mtyp -> mtype_context -> mtype_context *)
   575 fun push_bound M {bounds, frees, consts} =
   576   {bounds = M :: bounds, frees = frees, consts = consts}
   577 (* mtype_context -> mtype_context *)
   578 fun pop_bound {bounds, frees, consts} =
   579   {bounds = tl bounds, frees = frees, consts = consts}
   580   handle List.Empty => initial_gamma
   581 
   582 (* mdata -> term -> accumulator -> mterm * accumulator *)
   583 fun consider_term (mdata as {hol_ctxt = {thy, ctxt, stds, fast_descrs,
   584                                          def_table, ...},
   585                              alpha_T, max_fresh, ...}) =
   586   let
   587     (* typ -> typ -> mtyp * sign_atom * mtyp *)
   588     val mfun_for = fresh_mfun_for_fun_type mdata
   589     (* typ -> mtyp *)
   590     val mtype_for = fresh_mtype_for_type mdata
   591     (* mtyp -> mtyp *)
   592     fun pos_set_mtype_for_dom M =
   593       MFun (M, S (if exists_alpha_sub_mtype M then Plus else Minus), bool_M)
   594     (* typ -> accumulator -> mterm * accumulator *)
   595     fun do_all T (gamma, cset) =
   596       let
   597         val abs_M = mtype_for (domain_type (domain_type T))
   598         val body_M = mtype_for (range_type T)
   599       in
   600         (MFun (MFun (abs_M, S Minus, body_M), S Minus, body_M),
   601          (gamma, cset |> add_mtype_is_right_total abs_M))
   602       end
   603     fun do_equals T (gamma, cset) =
   604       let val M = mtype_for (domain_type T) in
   605         (MFun (M, S Minus, MFun (M, V (Unsynchronized.inc max_fresh),
   606                                  mtype_for (nth_range_type 2 T))),
   607          (gamma, cset |> add_mtype_is_right_unique M))
   608       end
   609     fun do_robust_set_operation T (gamma, cset) =
   610       let
   611         val set_T = domain_type T
   612         val M1 = mtype_for set_T
   613         val M2 = mtype_for set_T
   614         val M3 = mtype_for set_T
   615       in
   616         (MFun (M1, S Minus, MFun (M2, S Minus, M3)),
   617          (gamma, cset |> add_is_sub_mtype M1 M3 |> add_is_sub_mtype M2 M3))
   618       end
   619     fun do_fragile_set_operation T (gamma, cset) =
   620       let
   621         val set_T = domain_type T
   622         val set_M = mtype_for set_T
   623         (* typ -> mtyp *)
   624         fun custom_mtype_for (T as Type ("fun", [T1, T2])) =
   625             if T = set_T then set_M
   626             else MFun (custom_mtype_for T1, S Minus, custom_mtype_for T2)
   627           | custom_mtype_for T = mtype_for T
   628       in
   629         (custom_mtype_for T, (gamma, cset |> add_mtype_is_right_unique set_M))
   630       end
   631     (* typ -> accumulator -> mtyp * accumulator *)
   632     fun do_pair_constr T accum =
   633       case mtype_for (nth_range_type 2 T) of
   634         M as MPair (a_M, b_M) =>
   635         (MFun (a_M, S Minus, MFun (b_M, S Minus, M)), accum)
   636       | M => raise MTYPE ("Nitpick_Mono.consider_term.do_pair_constr", [M])
   637     (* int -> typ -> accumulator -> mtyp * accumulator *)
   638     fun do_nth_pair_sel n T =
   639       case mtype_for (domain_type T) of
   640         M as MPair (a_M, b_M) =>
   641         pair (MFun (M, S Minus, if n = 0 then a_M else b_M))
   642       | M => raise MTYPE ("Nitpick_Mono.consider_term.do_nth_pair_sel", [M])
   643     (* mtyp * accumulator *)
   644     val mtype_unsolvable = (irrelevant_M, unsolvable_accum)
   645     (* term -> mterm * accumulator *)
   646     fun mterm_unsolvable t = (MAtom (t, irrelevant_M), unsolvable_accum)
   647     (* term -> string -> typ -> term -> term -> term -> accumulator
   648        -> mterm * accumulator *)
   649     fun do_bounded_quantifier t0 abs_s abs_T connective_t bound_t body_t accum =
   650       let
   651         val abs_M = mtype_for abs_T
   652         val (bound_m, accum) = accum |>> push_bound abs_M |> do_term bound_t
   653         val expected_bound_M = pos_set_mtype_for_dom abs_M
   654         val (body_m, accum) =
   655           accum ||> add_mtypes_equal expected_bound_M (mtype_of_mterm bound_m)
   656                 |> do_term body_t ||> apfst pop_bound
   657         val bound_M = mtype_of_mterm bound_m
   658         val (M1, a, M2) = dest_MFun bound_M
   659       in
   660         (MApp (MAtom (t0, MFun (bound_M, S Minus, bool_M)),
   661                MAbs (abs_s, abs_T, M1, a,
   662                      MApp (MApp (MAtom (connective_t, irrelevant_M),
   663                                  MApp (bound_m, MAtom (Bound 0, M1))),
   664                            body_m))), accum)
   665       end
   666     (* term -> accumulator -> mterm * accumulator *)
   667     and do_term t (_, UnsolvableCSet) = mterm_unsolvable t
   668       | do_term t (accum as (gamma as {bounds, frees, consts}, cset)) =
   669         (case t of
   670            Const (x as (s, T)) =>
   671            (case AList.lookup (op =) consts x of
   672               SOME M => (M, accum)
   673             | NONE =>
   674               if not (could_exist_alpha_subtype alpha_T T) then
   675                 (mtype_for T, accum)
   676               else case s of
   677                 @{const_name all} => do_all T accum
   678               | @{const_name "=="} => do_equals T accum
   679               | @{const_name All} => do_all T accum
   680               | @{const_name Ex} =>
   681                 do_term (@{const Not}
   682                          $ (HOLogic.eq_const (domain_type T)
   683                             $ Abs (Name.uu, T, @{const False}))) accum
   684                 |>> mtype_of_mterm
   685               | @{const_name "op ="} => do_equals T accum
   686               | @{const_name The} => (print_g "*** The"; mtype_unsolvable)
   687               | @{const_name Eps} => (print_g "*** Eps"; mtype_unsolvable)
   688               | @{const_name If} =>
   689                 do_robust_set_operation (range_type T) accum
   690                 |>> curry3 MFun bool_M (S Minus)
   691               | @{const_name Pair} => do_pair_constr T accum
   692               | @{const_name fst} => do_nth_pair_sel 0 T accum
   693               | @{const_name snd} => do_nth_pair_sel 1 T accum 
   694               | @{const_name Id} =>
   695                 (MFun (mtype_for (domain_type T), S Minus, bool_M), accum)
   696               | @{const_name insert} =>
   697                 let
   698                   val set_T = domain_type (range_type T)
   699                   val M1 = mtype_for (domain_type set_T)
   700                   val M1' = pos_set_mtype_for_dom M1
   701                   val M2 = mtype_for set_T
   702                   val M3 = mtype_for set_T
   703                 in
   704                   (MFun (M1, S Minus, MFun (M2, S Minus, M3)),
   705                    (gamma, cset |> add_mtype_is_right_unique M1
   706                                 |> add_is_sub_mtype M1' M3
   707                                 |> add_is_sub_mtype M2 M3))
   708                 end
   709               | @{const_name converse} =>
   710                 let
   711                   val x = Unsynchronized.inc max_fresh
   712                   (* typ -> mtyp *)
   713                   fun mtype_for_set T =
   714                     MFun (mtype_for (domain_type T), V x, bool_M)
   715                   val ab_set_M = domain_type T |> mtype_for_set
   716                   val ba_set_M = range_type T |> mtype_for_set
   717                 in (MFun (ab_set_M, S Minus, ba_set_M), accum) end
   718               | @{const_name trancl} => do_fragile_set_operation T accum
   719               | @{const_name rtrancl} =>
   720                 (print_g "*** rtrancl"; mtype_unsolvable)
   721               | @{const_name finite} =>
   722                 let val M1 = mtype_for (domain_type (domain_type T)) in
   723                   (MFun (pos_set_mtype_for_dom M1, S Minus, bool_M), accum)
   724                 end
   725               | @{const_name rel_comp} =>
   726                 let
   727                   val x = Unsynchronized.inc max_fresh
   728                   (* typ -> mtyp *)
   729                   fun mtype_for_set T =
   730                     MFun (mtype_for (domain_type T), V x, bool_M)
   731                   val bc_set_M = domain_type T |> mtype_for_set
   732                   val ab_set_M = domain_type (range_type T) |> mtype_for_set
   733                   val ac_set_M = nth_range_type 2 T |> mtype_for_set
   734                 in
   735                   (MFun (bc_set_M, S Minus, MFun (ab_set_M, S Minus, ac_set_M)),
   736                    accum)
   737                 end
   738               | @{const_name image} =>
   739                 let
   740                   val a_M = mtype_for (domain_type (domain_type T))
   741                   val b_M = mtype_for (range_type (domain_type T))
   742                 in
   743                   (MFun (MFun (a_M, S Minus, b_M), S Minus,
   744                          MFun (pos_set_mtype_for_dom a_M, S Minus,
   745                                pos_set_mtype_for_dom b_M)), accum)
   746                 end
   747               | @{const_name Sigma} =>
   748                 let
   749                   val x = Unsynchronized.inc max_fresh
   750                   (* typ -> mtyp *)
   751                   fun mtype_for_set T =
   752                     MFun (mtype_for (domain_type T), V x, bool_M)
   753                   val a_set_T = domain_type T
   754                   val a_M = mtype_for (domain_type a_set_T)
   755                   val b_set_M = mtype_for_set (range_type (domain_type
   756                                                                (range_type T)))
   757                   val a_set_M = mtype_for_set a_set_T
   758                   val a_to_b_set_M = MFun (a_M, S Minus, b_set_M)
   759                   val ab_set_M = mtype_for_set (nth_range_type 2 T)
   760                 in
   761                   (MFun (a_set_M, S Minus,
   762                          MFun (a_to_b_set_M, S Minus, ab_set_M)), accum)
   763                 end
   764               | @{const_name Tha} =>
   765                 let
   766                   val a_M = mtype_for (domain_type (domain_type T))
   767                   val a_set_M = pos_set_mtype_for_dom a_M
   768                 in (MFun (a_set_M, S Minus, a_M), accum) end
   769               | @{const_name FunBox} =>
   770                 let val dom_M = mtype_for (domain_type T) in
   771                   (MFun (dom_M, S Minus, dom_M), accum)
   772                 end
   773               | _ =>
   774                 if s = @{const_name minus_class.minus} andalso
   775                    is_set_type (domain_type T) then
   776                   let
   777                     val set_T = domain_type T
   778                     val left_set_M = mtype_for set_T
   779                     val right_set_M = mtype_for set_T
   780                   in
   781                     (MFun (left_set_M, S Minus,
   782                            MFun (right_set_M, S Minus, left_set_M)),
   783                      (gamma, cset |> add_mtype_is_right_unique right_set_M
   784                                   |> add_is_sub_mtype right_set_M left_set_M))
   785                   end
   786                 else if s = @{const_name ord_class.less_eq} andalso
   787                         is_set_type (domain_type T) then
   788                   do_fragile_set_operation T accum
   789                 else if (s = @{const_name semilattice_inf_class.inf} orelse
   790                          s = @{const_name semilattice_sup_class.sup}) andalso
   791                         is_set_type (domain_type T) then
   792                   do_robust_set_operation T accum
   793                 else if is_sel s then
   794                   if constr_name_for_sel_like s = @{const_name FunBox} then
   795                     let val dom_M = mtype_for (domain_type T) in
   796                       (MFun (dom_M, S Minus, dom_M), accum)
   797                     end
   798                   else
   799                     (mtype_for_sel mdata x, accum)
   800                 else if is_constr thy stds x then
   801                   (mtype_for_constr mdata x, accum)
   802                 else if is_built_in_const thy stds fast_descrs x then
   803                   case def_of_const thy def_table x of
   804                     SOME t' => do_term t' accum |>> mtype_of_mterm
   805                   | NONE => (print_g ("*** built-in " ^ s); mtype_unsolvable)
   806                 else
   807                   let val M = mtype_for T in
   808                     (M, ({bounds = bounds, frees = frees,
   809                           consts = (x, M) :: consts}, cset))
   810                   end) |>> curry MAtom t
   811          | Free (x as (_, T)) =>
   812            (case AList.lookup (op =) frees x of
   813               SOME M => (M, accum)
   814             | NONE =>
   815               let val M = mtype_for T in
   816                 (M, ({bounds = bounds, frees = (x, M) :: frees,
   817                       consts = consts}, cset))
   818               end) |>> curry MAtom t
   819          | Var _ => (print_g "*** Var"; mterm_unsolvable t)
   820          | Bound j => (MAtom (t, nth bounds j), accum)
   821          | Abs (s, T, t' as @{const False}) =>
   822            let val (M1, a, M2) = mfun_for T bool_T in
   823              (MAbs (s, T, M1, a, MAtom (t', M2)), accum)
   824            end
   825          | Abs (s, T, t') =>
   826            ((case t' of
   827                t1' $ Bound 0 =>
   828                if not (loose_bvar1 (t1', 0)) then
   829                  do_term (incr_boundvars ~1 t1') accum
   830                else
   831                  raise SAME ()
   832              | _ => raise SAME ())
   833             handle SAME () =>
   834                    let
   835                      val M = mtype_for T
   836                      val (m', accum) = do_term t' (accum |>> push_bound M)
   837                    in (MAbs (s, T, M, S Minus, m'), accum |>> pop_bound) end)
   838          | (t0 as Const (@{const_name All}, _))
   839            $ Abs (s', T', (t10 as @{const "op -->"}) $ (t11 $ Bound 0) $ t12) =>
   840            do_bounded_quantifier t0 s' T' t10 t11 t12 accum
   841          | (t0 as Const (@{const_name Ex}, _))
   842            $ Abs (s', T', (t10 as @{const "op &"}) $ (t11 $ Bound 0) $ t12) =>
   843            do_bounded_quantifier t0 s' T' t10 t11 t12 accum
   844          | Const (@{const_name Let}, _) $ t1 $ t2 =>
   845            do_term (betapply (t2, t1)) accum
   846          | t1 $ t2 =>
   847            let
   848              val (m1, accum) = do_term t1 accum
   849              val (m2, accum) = do_term t2 accum
   850            in
   851              case accum of
   852                (_, UnsolvableCSet) => mterm_unsolvable t
   853              | _ => (MApp (m1, m2), accum)
   854            end)
   855         |> tap (fn (m, _) => print_g ("  \<Gamma> \<turnstile> " ^
   856                                       string_for_mterm ctxt m))
   857   in do_term end
   858 
   859 (* mdata -> sign -> term -> accumulator -> accumulator *)
   860 fun consider_general_formula (mdata as {hol_ctxt = {ctxt, ...}, ...}) =
   861   let
   862     (* typ -> mtyp *)
   863     val mtype_for = fresh_mtype_for_type mdata
   864     (* term -> accumulator -> mtyp * accumulator *)
   865     val do_term = apfst mtype_of_mterm oo consider_term mdata
   866     (* sign -> term -> accumulator -> accumulator *)
   867     fun do_formula _ _ (_, UnsolvableCSet) = unsolvable_accum
   868       | do_formula sn t (accum as (gamma, cset)) =
   869         let
   870           (* term -> accumulator -> accumulator *)
   871           val do_co_formula = do_formula sn
   872           val do_contra_formula = do_formula (negate sn)
   873           (* string -> typ -> term -> accumulator *)
   874           fun do_quantifier quant_s abs_T body_t =
   875             let
   876               val abs_M = mtype_for abs_T
   877               val side_cond = ((sn = Minus) = (quant_s = @{const_name Ex}))
   878               val cset = cset |> side_cond ? add_mtype_is_right_total abs_M
   879             in
   880               (gamma |> push_bound abs_M, cset)
   881               |> do_co_formula body_t |>> pop_bound
   882             end
   883           (* typ -> term -> accumulator *)
   884           fun do_bounded_quantifier abs_T body_t =
   885             accum |>> push_bound (mtype_for abs_T) |> do_co_formula body_t
   886                   |>> pop_bound
   887           (* term -> term -> accumulator *)
   888           fun do_equals t1 t2 =
   889             case sn of
   890               Plus => do_term t accum |> snd
   891             | Minus => let
   892                          val (M1, accum) = do_term t1 accum
   893                          val (M2, accum) = do_term t2 accum
   894                        in accum ||> add_mtypes_equal M1 M2 end
   895         in
   896           case t of
   897             Const (s0 as @{const_name all}, _) $ Abs (_, T1, t1) =>
   898             do_quantifier s0 T1 t1
   899           | Const (@{const_name "=="}, _) $ t1 $ t2 => do_equals t1 t2
   900           | @{const "==>"} $ t1 $ t2 =>
   901             accum |> do_contra_formula t1 |> do_co_formula t2
   902           | @{const Trueprop} $ t1 => do_co_formula t1 accum
   903           | @{const Not} $ t1 => do_contra_formula t1 accum
   904           | Const (@{const_name All}, _)
   905             $ Abs (_, T1, t1 as @{const "op -->"} $ (_ $ Bound 0) $ _) =>
   906             do_bounded_quantifier T1 t1
   907           | Const (s0 as @{const_name All}, _) $ Abs (_, T1, t1) =>
   908             do_quantifier s0 T1 t1
   909           | Const (@{const_name Ex}, _)
   910             $ Abs (_, T1, t1 as @{const "op &"} $ (_ $ Bound 0) $ _) =>
   911             do_bounded_quantifier T1 t1
   912           | Const (s0 as @{const_name Ex}, T0) $ (t1 as Abs (_, T1, t1')) =>
   913             (case sn of
   914                Plus => do_quantifier s0 T1 t1'
   915              | Minus =>
   916                do_term (@{const Not}
   917                         $ (HOLogic.eq_const (domain_type T0) $ t1
   918                            $ Abs (Name.uu, T1, @{const False}))) accum |> snd)
   919           | Const (@{const_name "op ="}, _) $ t1 $ t2 => do_equals t1 t2
   920           | @{const "op &"} $ t1 $ t2 =>
   921             accum |> do_co_formula t1 |> do_co_formula t2
   922           | @{const "op |"} $ t1 $ t2 =>
   923             accum |> do_co_formula t1 |> do_co_formula t2
   924           | @{const "op -->"} $ t1 $ t2 =>
   925             accum |> do_contra_formula t1 |> do_co_formula t2
   926           | Const (@{const_name If}, _) $ t1 $ t2 $ t3 =>
   927             accum |> do_term t1 |> snd |> fold do_co_formula [t2, t3]
   928           | Const (@{const_name Let}, _) $ t1 $ t2 =>
   929             do_co_formula (betapply (t2, t1)) accum
   930           | _ => do_term t accum |> snd
   931         end
   932         |> tap (fn _ => print_g ("\<Gamma> \<turnstile> " ^
   933                                  Syntax.string_of_term ctxt t ^
   934                                  " : o\<^sup>" ^ string_for_sign sn))
   935   in do_formula end
   936 
   937 (* The harmless axiom optimization below is somewhat too aggressive in the face
   938    of (rather peculiar) user-defined axioms. *)
   939 val harmless_consts =
   940   [@{const_name ord_class.less}, @{const_name ord_class.less_eq}]
   941 val bounteous_consts = [@{const_name bisim}]
   942 
   943 (* term -> bool *)
   944 fun is_harmless_axiom ({thy, stds, fast_descrs, ...} : hol_context) t =
   945   Term.add_consts t []
   946   |> filter_out (is_built_in_const thy stds fast_descrs)
   947   |> (forall (member (op =) harmless_consts o original_name o fst)
   948       orf exists (member (op =) bounteous_consts o fst))
   949 
   950 (* mdata -> sign -> term -> accumulator -> accumulator *)
   951 fun consider_nondefinitional_axiom (mdata as {hol_ctxt, ...}) sn t =
   952   not (is_harmless_axiom hol_ctxt t) ? consider_general_formula mdata sn t
   953 
   954 (* mdata -> term -> accumulator -> accumulator *)
   955 fun consider_definitional_axiom (mdata as {hol_ctxt as {thy, ...}, ...}) t =
   956   if not (is_constr_pattern_formula thy t) then
   957     consider_nondefinitional_axiom mdata Plus t
   958   else if is_harmless_axiom hol_ctxt t then
   959     I
   960   else
   961     let
   962       (* term -> accumulator -> mtyp * accumulator *)
   963       val do_term = apfst mtype_of_mterm oo consider_term mdata
   964       (* typ -> term -> accumulator -> accumulator *)
   965       fun do_all abs_T body_t accum =
   966         let val abs_M = fresh_mtype_for_type mdata abs_T in
   967           accum |>> push_bound abs_M |> do_formula body_t |>> pop_bound
   968         end
   969       (* term -> term -> accumulator -> accumulator *)
   970       and do_implies t1 t2 = do_term t1 #> snd #> do_formula t2
   971       and do_equals t1 t2 accum =
   972         let
   973           val (M1, accum) = do_term t1 accum
   974           val (M2, accum) = do_term t2 accum
   975         in accum ||> add_mtypes_equal M1 M2 end
   976       (* term -> accumulator -> accumulator *)
   977       and do_formula _ (_, UnsolvableCSet) = unsolvable_accum
   978         | do_formula t accum =
   979           case t of
   980             Const (@{const_name all}, _) $ Abs (_, T1, t1) => do_all T1 t1 accum
   981           | @{const Trueprop} $ t1 => do_formula t1 accum
   982           | Const (@{const_name "=="}, _) $ t1 $ t2 => do_equals t1 t2 accum
   983           | @{const "==>"} $ t1 $ t2 => do_implies t1 t2 accum
   984           | @{const Pure.conjunction} $ t1 $ t2 =>
   985             accum |> do_formula t1 |> do_formula t2
   986           | Const (@{const_name All}, _) $ Abs (_, T1, t1) => do_all T1 t1 accum
   987           | Const (@{const_name "op ="}, _) $ t1 $ t2 => do_equals t1 t2 accum
   988           | @{const "op &"} $ t1 $ t2 => accum |> do_formula t1 |> do_formula t2
   989           | @{const "op -->"} $ t1 $ t2 => do_implies t1 t2 accum
   990           | _ => raise TERM ("Nitpick_Mono.consider_definitional_axiom.\
   991                              \do_formula", [t])
   992     in do_formula t end
   993 
   994 (* Proof.context -> literal list -> term -> mtyp -> string *)
   995 fun string_for_mtype_of_term ctxt lits t M =
   996   Syntax.string_of_term ctxt t ^ " : " ^
   997   string_for_mtype (instantiate_mtype lits M)
   998 
   999 (* theory -> literal list -> mtype_context -> unit *)
  1000 fun print_mtype_context ctxt lits ({frees, consts, ...} : mtype_context) =
  1001   map (fn (x, M) => string_for_mtype_of_term ctxt lits (Free x) M) frees @
  1002   map (fn (x, M) => string_for_mtype_of_term ctxt lits (Const x) M) consts
  1003   |> cat_lines |> print_g
  1004 
  1005 (* hol_context -> bool -> typ -> term list * term list * term -> bool *)
  1006 fun formulas_monotonic (hol_ctxt as {ctxt, ...}) binarize alpha_T
  1007                        (def_ts, nondef_ts, core_t) =
  1008   let
  1009     val _ = print_g ("****** Monotonicity analysis: " ^
  1010                      string_for_mtype MAlpha ^ " is " ^
  1011                      Syntax.string_of_typ ctxt alpha_T)
  1012     val mdata as {max_fresh, constr_cache, ...} =
  1013       initial_mdata hol_ctxt binarize alpha_T
  1014     val (gamma as {frees, consts, ...}, cset) =
  1015       (initial_gamma, slack)
  1016       |> fold (consider_definitional_axiom mdata) def_ts
  1017       |> fold (consider_nondefinitional_axiom mdata Plus) nondef_ts
  1018       |> consider_general_formula mdata Plus core_t
  1019   in
  1020     case solve (!max_fresh) cset of
  1021       SOME lits => (print_mtype_context ctxt lits gamma; true)
  1022     | _ => false
  1023   end
  1024   handle MTYPE (loc, Ms) => raise BAD (loc, commas (map string_for_mtype Ms))
  1025 
  1026 end;