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