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