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