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