src/HOL/Tools/Nitpick/nitpick_mono.ML
author blanchet
Mon Dec 06 13:18:25 2010 +0100 (2010-12-06)
changeset 40993 52ee2a187cdb
parent 40991 902ad76994d5
child 40994 3bdb8df0daf0
permissions -rw-r--r--
support 3 monotonicity calculi in one and fix soundness bug
     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 = 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 do_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      | _ => do_annotation_atom_comp Eq [] aa2 aa1 accum)
   383   | do_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   | do_annotation_atom_comp cmp xs aa1 aa2 (asgs, comps) =
   390     SOME (asgs, insert (op =) (aa1, aa2, cmp, xs) comps)
   391 
   392 fun add_annotation_atom_comp cmp xs aa1 aa2
   393                              ((asgs, comps, clauses) : constraint_set) =
   394   (trace_msg (fn () => "*** Add " ^ string_for_annotation_atom aa1 ^ " " ^
   395                        string_for_comp_op cmp ^ " " ^
   396                        string_for_annotation_atom aa2);
   397    case do_annotation_atom_comp cmp xs aa1 aa2 (asgs, comps) of
   398      NONE => (trace_msg (K "**** Unsolvable"); raise UNSOLVABLE ())
   399    | SOME (asgs, comps) => (asgs, comps, clauses))
   400 
   401 fun do_mtype_comp _ _ _ _ NONE = NONE
   402   | do_mtype_comp _ _ MAlpha MAlpha accum = accum
   403   | do_mtype_comp Eq xs (MFun (M11, aa1, M12)) (MFun (M21, aa2, M22))
   404                   (SOME accum) =
   405      accum |> do_annotation_atom_comp Eq xs aa1 aa2
   406            |> do_mtype_comp Eq xs M11 M21 |> do_mtype_comp Eq xs M12 M22
   407   | do_mtype_comp Leq xs (MFun (M11, aa1, M12)) (MFun (M21, aa2, M22))
   408                   (SOME accum) =
   409     (if exists_alpha_sub_mtype M11 then
   410        accum |> do_annotation_atom_comp Leq xs aa1 aa2
   411              |> do_mtype_comp Leq xs M21 M11
   412              |> (case aa2 of
   413                    A Gen => I
   414                  | A _ => do_mtype_comp Leq xs M11 M21
   415                  | V x => do_mtype_comp Leq (x :: xs) M11 M21)
   416      else
   417        SOME accum)
   418     |> do_mtype_comp Leq xs M12 M22
   419   | do_mtype_comp cmp xs (M1 as MPair (M11, M12)) (M2 as MPair (M21, M22))
   420                   accum =
   421     (accum |> fold (uncurry (do_mtype_comp cmp xs)) [(M11, M21), (M12, M22)]
   422      handle ListPair.UnequalLengths =>
   423             raise MTYPE ("Nitpick_Mono.do_mtype_comp", [M1, M2], []))
   424   | do_mtype_comp _ _ (MType _) (MType _) accum =
   425     accum (* no need to compare them thanks to the cache *)
   426   | do_mtype_comp cmp _ M1 M2 _ =
   427     raise MTYPE ("Nitpick_Mono.do_mtype_comp (" ^ string_for_comp_op cmp ^ ")",
   428                  [M1, M2], [])
   429 
   430 fun add_mtype_comp cmp M1 M2 ((asgs, comps, clauses) : constraint_set) =
   431   (trace_msg (fn () => "*** Add " ^ string_for_mtype M1 ^ " " ^
   432                        string_for_comp_op cmp ^ " " ^ string_for_mtype M2);
   433    case do_mtype_comp cmp [] M1 M2 (SOME (asgs, comps)) of
   434      NONE => (trace_msg (K "**** Unsolvable"); raise UNSOLVABLE ())
   435    | SOME (asgs, comps) => (asgs, comps, clauses))
   436 
   437 val add_mtypes_equal = add_mtype_comp Eq
   438 val add_is_sub_mtype = add_mtype_comp Leq
   439 
   440 fun do_notin_mtype_fv _ _ _ NONE = NONE
   441   | do_notin_mtype_fv Minus _ MAlpha accum = accum
   442   | do_notin_mtype_fv Plus [] MAlpha _ = NONE
   443   | do_notin_mtype_fv Plus [(x, a)] MAlpha (SOME (asgs, clauses)) =
   444     SOME asgs |> add_assign_conjunct (x, a) |> Option.map (rpair clauses)
   445   | do_notin_mtype_fv Plus clause MAlpha (SOME (asgs, clauses)) =
   446     SOME (asgs, insert (op =) clause clauses)
   447   | do_notin_mtype_fv sn clause (MFun (M1, A a, M2)) accum =
   448     accum |> (if a <> Gen andalso sn = Plus then
   449                 do_notin_mtype_fv Plus clause M1
   450               else
   451                 I)
   452           |> (if a = Gen orelse sn = Plus then
   453                 do_notin_mtype_fv Minus clause M1
   454               else
   455                 I)
   456           |> do_notin_mtype_fv sn clause M2
   457   | do_notin_mtype_fv Plus clause (MFun (M1, V x, M2)) accum =
   458     accum |> (case add_assign_disjunct (x, Gen) (SOME clause) of
   459                 NONE => I
   460               | SOME clause' => do_notin_mtype_fv Plus clause' M1)
   461           |> do_notin_mtype_fv Minus clause M1
   462           |> do_notin_mtype_fv Plus clause M2
   463   | do_notin_mtype_fv Minus clause (MFun (M1, V x, M2)) accum =
   464     accum |> (case fold (fn a => add_assign_disjunct (x, a)) [Fls, Tru]
   465                         (SOME clause) of
   466                 NONE => I
   467               | SOME clause' => do_notin_mtype_fv Plus clause' M1)
   468           |> do_notin_mtype_fv Minus clause M2
   469   | do_notin_mtype_fv sn clause (MPair (M1, M2)) accum =
   470     accum |> fold (do_notin_mtype_fv sn clause) [M1, M2]
   471   | do_notin_mtype_fv sn clause (MType (_, Ms)) accum =
   472     accum |> fold (do_notin_mtype_fv sn clause) Ms
   473   | do_notin_mtype_fv _ _ M _ =
   474     raise MTYPE ("Nitpick_Mono.do_notin_mtype_fv", [M], [])
   475 
   476 fun add_notin_mtype_fv sn M ((asgs, comps, clauses) : constraint_set) =
   477   (trace_msg (fn () => "*** Add " ^ string_for_mtype M ^ " is " ^
   478                        (case sn of Minus => "concrete" | Plus => "complete"));
   479    case do_notin_mtype_fv sn [] M (SOME (asgs, clauses)) of
   480      NONE => (trace_msg (K "**** Unsolvable"); raise UNSOLVABLE ())
   481    | SOME (asgs, clauses) => (asgs, comps, clauses))
   482 
   483 val add_mtype_is_concrete = add_notin_mtype_fv Minus
   484 val add_mtype_is_complete = add_notin_mtype_fv Plus
   485 
   486 val bool_table =
   487   [(Gen, (false, false)),
   488    (New, (false, true)),
   489    (Fls, (true, false)),
   490    (Tru, (true, true))]
   491 
   492 fun fst_var n = 2 * n
   493 fun snd_var n = 2 * n + 1
   494 
   495 val bools_from_annotation = AList.lookup (op =) bool_table #> the
   496 val annotation_from_bools = AList.find (op =) bool_table #> the_single
   497 
   498 fun prop_for_bool b = if b then PL.True else PL.False
   499 fun prop_for_bool_var_equality (v1, v2) =
   500   PL.And (PL.Or (PL.BoolVar v1, PL.Not (PL.BoolVar v2)),
   501           PL.Or (PL.Not (PL.BoolVar v1), PL.BoolVar v2))
   502 fun prop_for_assign (x, a) =
   503   let val (b1, b2) = bools_from_annotation a in
   504     PL.And (PL.BoolVar (fst_var x) |> not b1 ? PL.Not,
   505             PL.BoolVar (snd_var x) |> not b2 ? PL.Not)
   506   end
   507 fun prop_for_atom_assign (A a', a) = prop_for_bool (a = a')
   508   | prop_for_atom_assign (V x, a) = prop_for_assign (x, a)
   509 fun prop_for_atom_equality (aa1, A a2) = prop_for_atom_assign (aa1, a2)
   510   | prop_for_atom_equality (A a1, aa2) = prop_for_atom_assign (aa2, a1)
   511   | prop_for_atom_equality (V x1, V x2) =
   512     PL.And (prop_for_bool_var_equality (pairself fst_var (x1, x2)),
   513             prop_for_bool_var_equality (pairself snd_var (x1, x2)))
   514 val prop_for_assign_clause = PL.exists o map prop_for_assign
   515 fun prop_for_exists_var_assign xs a =
   516   PL.exists (map (fn x => prop_for_assign (x, a)) xs)
   517 fun prop_for_comp (aa1, aa2, Eq, []) =
   518     PL.SAnd (prop_for_comp (aa1, aa2, Leq, []),
   519              prop_for_comp (aa2, aa1, Leq, []))
   520   | prop_for_comp (aa1, aa2, Leq, []) =
   521     PL.SOr (prop_for_atom_equality (aa1, aa2), prop_for_atom_assign (aa2, Gen))
   522   | prop_for_comp (aa1, aa2, cmp, xs) =
   523     PL.SOr (prop_for_exists_var_assign xs Gen,
   524             prop_for_comp (aa1, aa2, cmp, []))
   525 
   526 (* The "calculus" parameter may be 1, 2, or 3, corresponding approximately to
   527    the M1, M2, and M3 calculi from Blanchette & Krauss 2011. *)
   528 fun variable_domain calculus =
   529   [Gen] @ (if calculus > 1 then [Fls] else [])
   530   @ (if calculus > 2 then [New, Tru] else [])
   531 
   532 fun prop_for_variable_domain calculus x =
   533   PL.exists (map (curry prop_for_assign x) (variable_domain calculus))
   534 
   535 fun extract_assigns max_var assigns asgs =
   536   fold (fn x => fn accum =>
   537            if AList.defined (op =) asgs x then
   538              accum
   539            else case (fst_var x, snd_var x) |> pairself assigns of
   540              (NONE, NONE) => accum
   541            | bp => (x, annotation_from_bools (pairself (the_default false) bp))
   542                    :: accum)
   543        (max_var downto 1) asgs
   544 
   545 fun print_problem asgs comps clauses =
   546   trace_msg (fn () => "*** Problem:\n" ^
   547                       cat_lines (map string_for_assign asgs @
   548                                  map string_for_comp comps @
   549                                  map string_for_assign_clause clauses))
   550 
   551 fun print_solution asgs =
   552   trace_msg (fn () => "*** Solution:\n" ^
   553       (asgs
   554        |> map swap
   555        |> AList.group (op =)
   556        |> map (fn (a, xs) => string_for_annotation a ^ ": " ^
   557                              string_for_vars ", " xs)
   558        |> space_implode "\n"))
   559 
   560 fun solve calculus max_var (asgs, comps, clauses) =
   561   let
   562     fun do_assigns assigns =
   563       SOME (extract_assigns max_var assigns asgs |> tap print_solution)
   564     val _ = print_problem asgs comps clauses
   565     val prop =
   566       map prop_for_assign asgs @
   567       map prop_for_comp comps @
   568       map prop_for_assign_clause clauses @
   569       (if calculus < 3 then
   570          map (prop_for_variable_domain calculus) (1 upto max_var)
   571        else
   572          [])
   573       |> PL.all
   574   in
   575     if PL.eval (K false) prop then
   576       do_assigns (K (SOME false))
   577     else if PL.eval (K true) prop then
   578       do_assigns (K (SOME true))
   579     else
   580       let
   581         (* use the first ML solver (to avoid startup overhead) *)
   582         val solvers = !SatSolver.solvers
   583                       |> filter (member (op =) ["dptsat", "dpll"] o fst)
   584       in
   585         case snd (hd solvers) prop of
   586           SatSolver.SATISFIABLE assigns => do_assigns assigns
   587         | _ => NONE
   588       end
   589   end
   590 
   591 type mtype_schema = mtyp * constraint_set
   592 type mtype_context =
   593   {bound_Ts: typ list,
   594    bound_Ms: mtyp list,
   595    bound_frame: (int * annotation_atom) list,
   596    frees: (styp * mtyp) list,
   597    consts: (styp * mtyp) list}
   598 
   599 type accumulator = mtype_context * constraint_set
   600 
   601 val initial_gamma =
   602   {bound_Ts = [], bound_Ms = [], bound_frame = [], frees = [], consts = []}
   603 
   604 fun push_bound aa T M {bound_Ts, bound_Ms, bound_frame, frees, consts} =
   605   {bound_Ts = T :: bound_Ts, bound_Ms = M :: bound_Ms,
   606    bound_frame = (length bound_Ts, aa) :: bound_frame, frees = frees,
   607    consts = consts}
   608 fun pop_bound {bound_Ts, bound_Ms, bound_frame, frees, consts} =
   609   {bound_Ts = tl bound_Ts, bound_Ms = tl bound_Ms,
   610    bound_frame = bound_frame
   611                  |> filter_out (fn (depth, _) => depth = length bound_Ts - 1),
   612    frees = frees, consts = consts}
   613   handle List.Empty => initial_gamma (* FIXME: needed? *)
   614 
   615 fun consider_term (mdata as {hol_ctxt = {thy, ctxt, stds, ...}, alpha_T,
   616                              max_fresh, ...}) =
   617   let
   618     fun is_enough_eta_expanded t =
   619       case strip_comb t of
   620         (Const x, ts) => the_default 0 (arity_of_built_in_const thy stds x)
   621         <= length ts
   622       | _ => true
   623     val mtype_for = fresh_mtype_for_type mdata false
   624     fun plus_set_mtype_for_dom M =
   625       MFun (M, A (if exists_alpha_sub_mtype M then Fls else Gen), bool_M)
   626     fun do_all T (gamma, cset) =
   627       let
   628         val abs_M = mtype_for (domain_type (domain_type T))
   629         val body_M = mtype_for (body_type T)
   630       in
   631         (MFun (MFun (abs_M, A Gen, body_M), A Gen, body_M),
   632          (gamma, cset |> add_mtype_is_complete abs_M))
   633       end
   634     fun do_equals T (gamma, cset) =
   635       let val M = mtype_for (domain_type T) in
   636         (MFun (M, A Gen, MFun (M, V (Unsynchronized.inc max_fresh),
   637                                mtype_for (nth_range_type 2 T))),
   638          (gamma, cset |> add_mtype_is_concrete M))
   639       end
   640     fun do_robust_set_operation T (gamma, cset) =
   641       let
   642         val set_T = domain_type T
   643         val M1 = mtype_for set_T
   644         val M2 = mtype_for set_T
   645         val M3 = mtype_for set_T
   646       in
   647         (MFun (M1, A Gen, MFun (M2, A Gen, M3)),
   648          (gamma, cset |> add_is_sub_mtype M1 M3 |> add_is_sub_mtype M2 M3))
   649       end
   650     fun do_fragile_set_operation T (gamma, cset) =
   651       let
   652         val set_T = domain_type T
   653         val set_M = mtype_for set_T
   654         fun custom_mtype_for (T as Type (@{type_name fun}, [T1, T2])) =
   655             if T = set_T then set_M
   656             else MFun (custom_mtype_for T1, A Gen, custom_mtype_for T2)
   657           | custom_mtype_for T = mtype_for T
   658       in
   659         (custom_mtype_for T, (gamma, cset |> add_mtype_is_concrete set_M))
   660       end
   661     fun do_pair_constr T accum =
   662       case mtype_for (nth_range_type 2 T) of
   663         M as MPair (a_M, b_M) =>
   664         (MFun (a_M, A Gen, MFun (b_M, A Gen, M)), accum)
   665       | M => raise MTYPE ("Nitpick_Mono.consider_term.do_pair_constr", [M], [])
   666     fun do_nth_pair_sel n T =
   667       case mtype_for (domain_type T) of
   668         M as MPair (a_M, b_M) =>
   669         pair (MFun (M, A Gen, if n = 0 then a_M else b_M))
   670       | M => raise MTYPE ("Nitpick_Mono.consider_term.do_nth_pair_sel", [M], [])
   671     fun do_bounded_quantifier t0 abs_s abs_T connective_t bound_t body_t accum =
   672       let
   673         val abs_M = mtype_for abs_T
   674         val aa = V (Unsynchronized.inc max_fresh)
   675         val (bound_m, accum) =
   676           accum |>> push_bound aa abs_T abs_M |> do_term bound_t
   677         val expected_bound_M = plus_set_mtype_for_dom abs_M
   678         val (body_m, accum) =
   679           accum ||> add_mtypes_equal expected_bound_M (mtype_of_mterm bound_m)
   680                 |> do_term body_t ||> apfst pop_bound
   681         val bound_M = mtype_of_mterm bound_m
   682         val (M1, aa', _) = dest_MFun bound_M
   683       in
   684         (MApp (MRaw (t0, MFun (bound_M, aa, bool_M)),
   685                MAbs (abs_s, abs_T, M1, aa',
   686                      MApp (MApp (MRaw (connective_t,
   687                                        mtype_for (fastype_of connective_t)),
   688                                  MApp (bound_m, MRaw (Bound 0, M1))),
   689                            body_m))), accum)
   690       end
   691     and do_term t (accum as ({bound_Ts, bound_Ms, bound_frame, frees, consts},
   692                              cset)) =
   693       (trace_msg (fn () => "  \<Gamma> \<turnstile> " ^
   694                            Syntax.string_of_term ctxt t ^ " : _?");
   695        case t of
   696          Const (x as (s, T)) =>
   697          (case AList.lookup (op =) consts x of
   698             SOME M => (M, accum)
   699           | NONE =>
   700             case s of
   701               @{const_name False} =>
   702               (bool_M, accum ||> fold (add_annotation_atom_comp Leq [] (A Fls))
   703                                       (map snd bound_frame))
   704             | @{const_name True} =>
   705               (bool_M, accum ||> fold (add_annotation_atom_comp Leq [] (A Tru))
   706                                       (map snd bound_frame))
   707             | _ =>
   708               if not (could_exist_alpha_subtype alpha_T T) then
   709                 (mtype_for T, accum)
   710               else case s of
   711                 @{const_name all} => do_all T accum
   712               | @{const_name "=="} => do_equals T accum
   713               | @{const_name All} => do_all T accum
   714               | @{const_name Ex} =>
   715                 let val set_T = domain_type T in
   716                   do_term (Abs (Name.uu, set_T,
   717                                 @{const Not} $ (HOLogic.mk_eq
   718                                     (Abs (Name.uu, domain_type set_T,
   719                                           @{const False}),
   720                                      Bound 0)))) accum
   721                   |>> mtype_of_mterm
   722                 end
   723               | @{const_name HOL.eq} => do_equals T accum
   724               | @{const_name The} =>
   725                 (trace_msg (K "*** The"); raise UNSOLVABLE ())
   726               | @{const_name Eps} =>
   727                 (trace_msg (K "*** Eps"); raise UNSOLVABLE ())
   728               | @{const_name If} =>
   729                 do_robust_set_operation (range_type T) accum
   730                 |>> curry3 MFun bool_M (A Gen)
   731               | @{const_name Pair} => do_pair_constr T accum
   732               | @{const_name fst} => do_nth_pair_sel 0 T accum
   733               | @{const_name snd} => do_nth_pair_sel 1 T accum
   734               | @{const_name Id} =>
   735                 (MFun (mtype_for (domain_type T), A Gen, bool_M), accum)
   736               | @{const_name converse} =>
   737                 let
   738                   val x = Unsynchronized.inc max_fresh
   739                   fun mtype_for_set T =
   740                     MFun (mtype_for (domain_type T), V x, bool_M)
   741                   val ab_set_M = domain_type T |> mtype_for_set
   742                   val ba_set_M = range_type T |> mtype_for_set
   743                 in (MFun (ab_set_M, A Gen, ba_set_M), accum) end
   744               | @{const_name trancl} => do_fragile_set_operation T accum
   745               | @{const_name rel_comp} =>
   746                 let
   747                   val x = Unsynchronized.inc max_fresh
   748                   fun mtype_for_set T =
   749                     MFun (mtype_for (domain_type T), V x, bool_M)
   750                   val bc_set_M = domain_type T |> mtype_for_set
   751                   val ab_set_M = domain_type (range_type T) |> mtype_for_set
   752                   val ac_set_M = nth_range_type 2 T |> mtype_for_set
   753                 in
   754                   (MFun (bc_set_M, A Gen, MFun (ab_set_M, A Gen, ac_set_M)),
   755                    accum)
   756                 end
   757               | @{const_name image} =>
   758                 let
   759                   val a_M = mtype_for (domain_type (domain_type T))
   760                   val b_M = mtype_for (range_type (domain_type T))
   761                 in
   762                   (MFun (MFun (a_M, A Gen, b_M), A Gen,
   763                          MFun (plus_set_mtype_for_dom a_M, A Gen,
   764                                plus_set_mtype_for_dom b_M)), accum)
   765                 end
   766               | @{const_name finite} =>
   767                 let val M1 = mtype_for (domain_type (domain_type T)) in
   768                   (MFun (plus_set_mtype_for_dom M1, A Gen, bool_M), accum)
   769                 end
   770               | @{const_name Sigma} =>
   771                 let
   772                   val x = Unsynchronized.inc max_fresh
   773                   fun mtype_for_set T =
   774                     MFun (mtype_for (domain_type T), V x, bool_M)
   775                   val a_set_T = domain_type T
   776                   val a_M = mtype_for (domain_type a_set_T)
   777                   val b_set_M =
   778                     mtype_for_set (range_type (domain_type (range_type T)))
   779                   val a_set_M = mtype_for_set a_set_T
   780                   val a_to_b_set_M = MFun (a_M, A Gen, b_set_M)
   781                   val ab_set_M = mtype_for_set (nth_range_type 2 T)
   782                 in
   783                   (MFun (a_set_M, A Gen, MFun (a_to_b_set_M, A Gen, ab_set_M)),
   784                    accum)
   785                 end
   786               | _ =>
   787                 if s = @{const_name safe_The} then
   788                   let
   789                     val a_set_M = mtype_for (domain_type T)
   790                     val a_M = dest_MFun a_set_M |> #1
   791                   in (MFun (a_set_M, A Gen, a_M), accum) end
   792                 else if s = @{const_name ord_class.less_eq} andalso
   793                         is_set_type (domain_type T) then
   794                   do_fragile_set_operation T accum
   795                 else if is_sel s then
   796                   (mtype_for_sel mdata x, accum)
   797                 else if is_constr ctxt stds x then
   798                   (mtype_for_constr mdata x, accum)
   799                 else if is_built_in_const thy stds x then
   800                   (fresh_mtype_for_type mdata true T, accum)
   801                 else
   802                   let val M = mtype_for T in
   803                     (M, ({bound_Ts = bound_Ts, bound_Ms = bound_Ms,
   804                           bound_frame = bound_frame, frees = frees,
   805                           consts = (x, M) :: consts}, cset))
   806                   end) |>> curry MRaw t
   807          | Free (x as (_, T)) =>
   808            (case AList.lookup (op =) frees x of
   809               SOME M => (M, accum)
   810             | NONE =>
   811               let val M = mtype_for T in
   812                 (M, ({bound_Ts = bound_Ts, bound_Ms = bound_Ms,
   813                       bound_frame = bound_frame, frees = (x, M) :: frees,
   814                       consts = consts}, cset))
   815               end) |>> curry MRaw t
   816          | Var _ => (trace_msg (K "*** Var"); raise UNSOLVABLE ())
   817          | Bound j => (MRaw (t, nth bound_Ms j), accum)
   818          | Abs (s, T, t') =>
   819            (case fin_fun_body T (fastype_of1 (T :: bound_Ts, t')) t' of
   820               SOME t' =>
   821               let
   822                 val M = mtype_for T
   823                 val (m', accum) = do_term t' (accum |>> push_bound (A Fls) T M)
   824               in (MAbs (s, T, M, A Fls, m'), accum |>> pop_bound) end
   825             | NONE =>
   826               ((case t' of
   827                   t1' $ Bound 0 =>
   828                   if not (loose_bvar1 (t1', 0)) andalso
   829                      is_enough_eta_expanded t1' then
   830                     do_term (incr_boundvars ~1 t1') accum
   831                   else
   832                     raise SAME ()
   833                 | (t11 as Const (@{const_name HOL.eq}, _)) $ Bound 0 $ t13 =>
   834                   if not (loose_bvar1 (t13, 0)) then
   835                     do_term (incr_boundvars ~1 (t11 $ t13)) accum
   836                   else
   837                     raise SAME ()
   838                 | _ => raise SAME ())
   839                handle SAME () =>
   840                       let
   841                         val M = mtype_for T
   842                         val aa = V (Unsynchronized.inc max_fresh)
   843                         val (m', accum) =
   844                           do_term t' (accum |>> push_bound aa T M)
   845                       in (MAbs (s, T, M, aa, m'), accum |>> pop_bound) end))
   846          | (t0 as Const (@{const_name All}, _))
   847            $ Abs (s', T', (t10 as @{const HOL.implies})
   848                           $ (t11 $ Bound 0) $ t12) =>
   849            do_bounded_quantifier t0 s' T' t10 t11 t12 accum
   850          | (t0 as Const (@{const_name Ex}, _))
   851            $ Abs (s', T', (t10 as @{const HOL.conj})
   852                           $ (t11 $ Bound 0) $ t12) =>
   853            do_bounded_quantifier t0 s' T' t10 t11 t12 accum
   854          | Const (@{const_name Let}, _) $ t1 $ t2 =>
   855            do_term (betapply (t2, t1)) accum
   856          | t1 $ t2 =>
   857            let
   858              val (m1, accum) = do_term t1 accum
   859              val (m2, accum) = do_term t2 accum
   860            in
   861              let
   862                val M11 = mtype_of_mterm m1 |> dest_MFun |> #1
   863                val M2 = mtype_of_mterm m2
   864              in (MApp (m1, m2), accum ||> add_is_sub_mtype M2 M11) end
   865            end)
   866         |> tap (fn (m, _) => trace_msg (fn () => "  \<Gamma> \<turnstile> " ^
   867                                                  string_for_mterm ctxt m))
   868   in do_term end
   869 
   870 fun force_minus_funs 0 _ = I
   871   | force_minus_funs n (M as MFun (M1, _, M2)) =
   872     add_mtypes_equal M (MFun (M1, A Gen, M2)) #> force_minus_funs (n - 1) M2
   873   | force_minus_funs _ M =
   874     raise MTYPE ("Nitpick_Mono.force_minus_funs", [M], [])
   875 fun consider_general_equals mdata def (x as (_, T)) t1 t2 accum =
   876   let
   877     val (m1, accum) = consider_term mdata t1 accum
   878     val (m2, accum) = consider_term mdata t2 accum
   879     val M1 = mtype_of_mterm m1
   880     val M2 = mtype_of_mterm m2
   881     val accum = accum ||> add_mtypes_equal M1 M2
   882     val body_M = fresh_mtype_for_type mdata false (nth_range_type 2 T)
   883     val m = MApp (MApp (MRaw (Const x,
   884                            MFun (M1, A Gen, MFun (M2, A Gen, body_M))), m1), m2)
   885   in
   886     (m, if def then
   887           let val (head_m, arg_ms) = strip_mcomb m1 in
   888             accum ||> force_minus_funs (length arg_ms) (mtype_of_mterm head_m)
   889           end
   890         else
   891           accum)
   892   end
   893 
   894 fun consider_general_formula (mdata as {hol_ctxt = {ctxt, ...}, ...}) =
   895   let
   896     val mtype_for = fresh_mtype_for_type mdata false
   897     val do_term = consider_term mdata
   898     fun do_formula sn t accum =
   899         let
   900           fun do_quantifier (quant_x as (quant_s, _)) abs_s abs_T body_t =
   901             let
   902               val abs_M = mtype_for abs_T
   903               val a = Gen (* FIXME: strengthen *)
   904               val side_cond = ((sn = Minus) = (quant_s = @{const_name Ex}))
   905               val (body_m, accum) =
   906                 accum ||> side_cond ? add_mtype_is_complete abs_M
   907                       |>> push_bound (A a) abs_T abs_M |> do_formula sn body_t
   908               val body_M = mtype_of_mterm body_m
   909             in
   910               (MApp (MRaw (Const quant_x,
   911                            MFun (MFun (abs_M, A Gen, body_M), A Gen, body_M)),
   912                      MAbs (abs_s, abs_T, abs_M, A Gen, body_m)),
   913                accum |>> pop_bound)
   914             end
   915           fun do_equals x t1 t2 =
   916             case sn of
   917               Plus => do_term t accum
   918             | Minus => consider_general_equals mdata false x t1 t2 accum
   919         in
   920           (trace_msg (fn () => "  \<Gamma> \<turnstile> " ^
   921                                Syntax.string_of_term ctxt t ^ " : o\<^sup>" ^
   922                                string_for_sign sn ^ "?");
   923            case t of
   924              Const (x as (@{const_name all}, _)) $ Abs (s1, T1, t1) =>
   925              do_quantifier x s1 T1 t1
   926            | Const (x as (@{const_name "=="}, _)) $ t1 $ t2 => do_equals x t1 t2
   927            | @{const Trueprop} $ t1 =>
   928              let val (m1, accum) = do_formula sn t1 accum in
   929                (MApp (MRaw (@{const Trueprop}, mtype_for (bool_T --> prop_T)),
   930                       m1), accum)
   931              end
   932            | @{const Not} $ t1 =>
   933              let val (m1, accum) = do_formula (negate_sign sn) t1 accum in
   934                (MApp (MRaw (@{const Not}, mtype_for (bool_T --> bool_T)), m1),
   935                 accum)
   936              end
   937            | Const (x as (@{const_name All}, _)) $ Abs (s1, T1, t1) =>
   938              do_quantifier x s1 T1 t1
   939            | Const (x0 as (@{const_name Ex}, T0))
   940              $ (t1 as Abs (s1, T1, t1')) =>
   941              (case sn of
   942                 Plus => do_quantifier x0 s1 T1 t1'
   943               | Minus =>
   944                 (* FIXME: Move elsewhere *)
   945                 do_term (@{const Not}
   946                          $ (HOLogic.eq_const (domain_type T0) $ t1
   947                             $ Abs (Name.uu, T1, @{const False}))) accum)
   948            | Const (x as (@{const_name HOL.eq}, _)) $ t1 $ t2 =>
   949              do_equals x t1 t2
   950            | Const (@{const_name Let}, _) $ t1 $ t2 =>
   951              do_formula sn (betapply (t2, t1)) accum
   952            | (t0 as Const (s0, _)) $ t1 $ t2 =>
   953              if s0 = @{const_name "==>"} orelse
   954                 s0 = @{const_name Pure.conjunction} orelse
   955                 s0 = @{const_name HOL.conj} orelse
   956                 s0 = @{const_name HOL.disj} orelse
   957                 s0 = @{const_name HOL.implies} then
   958                let
   959                  val impl = (s0 = @{const_name "==>"} orelse
   960                              s0 = @{const_name HOL.implies})
   961                  val (m1, accum) =
   962                    do_formula (sn |> impl ? negate_sign) t1 accum
   963                  val (m2, accum) = do_formula sn t2 accum
   964                in
   965                  (MApp (MApp (MRaw (t0, mtype_for (fastype_of t0)), m1), m2),
   966                   accum)
   967                end
   968              else
   969                do_term t accum
   970            | _ => do_term t accum)
   971         end
   972         |> tap (fn (m, _) =>
   973                    trace_msg (fn () => "\<Gamma> \<turnstile> " ^
   974                                        string_for_mterm ctxt m ^ " : o\<^sup>" ^
   975                                        string_for_sign sn))
   976   in do_formula end
   977 
   978 (* The harmless axiom optimization below is somewhat too aggressive in the face
   979    of (rather peculiar) user-defined axioms. *)
   980 val harmless_consts =
   981   [@{const_name ord_class.less}, @{const_name ord_class.less_eq}]
   982 val bounteous_consts = [@{const_name bisim}]
   983 
   984 fun is_harmless_axiom ({no_harmless = true, ...} : mdata) _ = false
   985   | is_harmless_axiom {hol_ctxt = {thy, stds, ...}, ...} t =
   986     Term.add_consts t []
   987     |> filter_out (is_built_in_const thy stds)
   988     |> (forall (member (op =) harmless_consts o original_name o fst) orf
   989         exists (member (op =) bounteous_consts o fst))
   990 
   991 fun consider_nondefinitional_axiom mdata t =
   992   if is_harmless_axiom mdata t then pair (MRaw (t, dummy_M))
   993   else consider_general_formula mdata Plus t
   994 
   995 fun consider_definitional_axiom (mdata as {hol_ctxt = {ctxt, ...}, ...}) t =
   996   if not (is_constr_pattern_formula ctxt t) then
   997     consider_nondefinitional_axiom mdata t
   998   else if is_harmless_axiom mdata t then
   999     pair (MRaw (t, dummy_M))
  1000   else
  1001     let
  1002       val mtype_for = fresh_mtype_for_type mdata false
  1003       val do_term = consider_term mdata
  1004       fun do_all quant_t abs_s abs_T body_t accum =
  1005         let
  1006           val abs_M = mtype_for abs_T
  1007           val (body_m, accum) =
  1008             accum |>> push_bound (A Gen) abs_T abs_M |> do_formula body_t
  1009           val body_M = mtype_of_mterm body_m
  1010         in
  1011           (MApp (MRaw (quant_t, MFun (MFun (abs_M, A Gen, body_M), A Gen,
  1012                        body_M)),
  1013                  MAbs (abs_s, abs_T, abs_M, A Gen, body_m)),
  1014            accum |>> pop_bound)
  1015         end
  1016       and do_conjunction t0 t1 t2 accum =
  1017         let
  1018           val (m1, accum) = do_formula t1 accum
  1019           val (m2, accum) = do_formula t2 accum
  1020         in
  1021           (MApp (MApp (MRaw (t0, mtype_for (fastype_of t0)), m1), m2), accum)
  1022         end
  1023       and do_implies t0 t1 t2 accum =
  1024         let
  1025           val (m1, accum) = do_term t1 accum
  1026           val (m2, accum) = do_formula t2 accum
  1027         in
  1028           (MApp (MApp (MRaw (t0, mtype_for (fastype_of t0)), m1), m2), accum)
  1029         end
  1030       and do_formula t accum =
  1031           case t of
  1032             (t0 as Const (@{const_name all}, _)) $ Abs (s1, T1, t1) =>
  1033             do_all t0 s1 T1 t1 accum
  1034           | @{const Trueprop} $ t1 =>
  1035             let val (m1, accum) = do_formula t1 accum in
  1036               (MApp (MRaw (@{const Trueprop}, mtype_for (bool_T --> prop_T)),
  1037                      m1), accum)
  1038             end
  1039           | Const (x as (@{const_name "=="}, _)) $ t1 $ t2 =>
  1040             consider_general_equals mdata true x t1 t2 accum
  1041           | (t0 as @{const "==>"}) $ t1 $ t2 => do_implies t0 t1 t2 accum
  1042           | (t0 as @{const Pure.conjunction}) $ t1 $ t2 =>
  1043             do_conjunction t0 t1 t2 accum
  1044           | (t0 as Const (@{const_name All}, _)) $ Abs (s0, T1, t1) =>
  1045             do_all t0 s0 T1 t1 accum
  1046           | Const (x as (@{const_name HOL.eq}, _)) $ t1 $ t2 =>
  1047             consider_general_equals mdata true x t1 t2 accum
  1048           | (t0 as @{const HOL.conj}) $ t1 $ t2 => do_conjunction t0 t1 t2 accum
  1049           | (t0 as @{const HOL.implies}) $ t1 $ t2 => do_implies t0 t1 t2 accum
  1050           | _ => raise TERM ("Nitpick_Mono.consider_definitional_axiom.\
  1051                              \do_formula", [t])
  1052     in do_formula t end
  1053 
  1054 fun string_for_mtype_of_term ctxt asgs t M =
  1055   Syntax.string_of_term ctxt t ^ " : " ^ string_for_mtype (resolve_mtype asgs M)
  1056 
  1057 fun print_mtype_context ctxt asgs ({frees, consts, ...} : mtype_context) =
  1058   trace_msg (fn () =>
  1059       map (fn (x, M) => string_for_mtype_of_term ctxt asgs (Free x) M) frees @
  1060       map (fn (x, M) => string_for_mtype_of_term ctxt asgs (Const x) M) consts
  1061       |> cat_lines)
  1062 
  1063 fun amass f t (ms, accum) =
  1064   let val (m, accum) = f t accum in (m :: ms, accum) end
  1065 
  1066 fun infer which no_harmless (hol_ctxt as {ctxt, ...}) binarize calculus alpha_T
  1067           (nondef_ts, def_ts) =
  1068   let
  1069     val _ = trace_msg (fn () => "****** " ^ which ^ " analysis: " ^
  1070                                 string_for_mtype MAlpha ^ " is " ^
  1071                                 Syntax.string_of_typ ctxt alpha_T)
  1072     val mdata as {max_fresh, constr_mcache, ...} =
  1073       initial_mdata hol_ctxt binarize no_harmless alpha_T
  1074     val accum = (initial_gamma, ([], [], []))
  1075     val (nondef_ms, accum) =
  1076       ([], accum) |> amass (consider_general_formula mdata Plus) (hd nondef_ts)
  1077                   |> fold (amass (consider_nondefinitional_axiom mdata))
  1078                           (tl nondef_ts)
  1079     val (def_ms, (gamma, cset)) =
  1080       ([], accum) |> fold (amass (consider_definitional_axiom mdata)) def_ts
  1081   in
  1082     case solve calculus (!max_fresh) cset of
  1083       SOME asgs => (print_mtype_context ctxt asgs gamma;
  1084                     SOME (asgs, (nondef_ms, def_ms), !constr_mcache))
  1085     | _ => NONE
  1086   end
  1087   handle UNSOLVABLE () => NONE
  1088        | MTYPE (loc, Ms, Ts) =>
  1089          raise BAD (loc, commas (map string_for_mtype Ms @
  1090                                  map (Syntax.string_of_typ ctxt) Ts))
  1091        | MTERM (loc, ms) =>
  1092          raise BAD (loc, commas (map (string_for_mterm ctxt) ms))
  1093 
  1094 fun formulas_monotonic hol_ctxt =
  1095   is_some oooo infer "Monotonicity" false hol_ctxt
  1096 
  1097 fun fin_fun_constr T1 T2 =
  1098   (@{const_name FinFun}, (T1 --> T2) --> Type (@{type_name fin_fun}, [T1, T2]))
  1099 
  1100 fun finitize_funs (hol_ctxt as {thy, ctxt, stds, constr_cache, ...}) binarize
  1101                   finitizes calculus alpha_T tsp =
  1102   case infer "Finiteness" true hol_ctxt binarize calculus alpha_T tsp of
  1103     SOME (asgs, msp, constr_mtypes) =>
  1104     if forall (curry (op =) Gen o snd) asgs then
  1105       tsp
  1106     else
  1107       let
  1108         fun should_finitize T aa =
  1109           case triple_lookup (type_match thy) finitizes T of
  1110             SOME (SOME false) => false
  1111           | _ => resolve_annotation_atom asgs aa = A Fls
  1112         fun type_from_mtype T M =
  1113           case (M, T) of
  1114             (MAlpha, _) => T
  1115           | (MFun (M1, aa, M2), Type (@{type_name fun}, Ts)) =>
  1116             Type (if should_finitize T aa then @{type_name fin_fun}
  1117                   else @{type_name fun}, map2 type_from_mtype Ts [M1, M2])
  1118           | (MPair (M1, M2), Type (@{type_name prod}, Ts)) =>
  1119             Type (@{type_name prod}, map2 type_from_mtype Ts [M1, M2])
  1120           | (MType _, _) => T
  1121           | _ => raise MTYPE ("Nitpick_Mono.finitize_funs.type_from_mtype",
  1122                               [M], [T])
  1123         fun finitize_constr (x as (s, T)) =
  1124           (s, case AList.lookup (op =) constr_mtypes x of
  1125                 SOME M => type_from_mtype T M
  1126               | NONE => T)
  1127         fun term_from_mterm new_Ts old_Ts m =
  1128           case m of
  1129             MRaw (t, M) =>
  1130             let
  1131               val T = fastype_of1 (old_Ts, t)
  1132               val T' = type_from_mtype T M
  1133             in
  1134               case t of
  1135                 Const (x as (s, _)) =>
  1136                 if s = @{const_name finite} then
  1137                   case domain_type T' of
  1138                     set_T' as Type (@{type_name fin_fun}, _) =>
  1139                     Abs (Name.uu, set_T', @{const True})
  1140                   | _ => Const (s, T')
  1141                 else if s = @{const_name "=="} orelse
  1142                         s = @{const_name HOL.eq} then
  1143                   let
  1144                     val T =
  1145                       case T' of
  1146                         Type (_, [T1, Type (_, [T2, T3])]) =>
  1147                         T1 --> T2 --> T3
  1148                       | _ => raise TYPE ("Nitpick_Mono.finitize_funs.\
  1149                                          \term_from_mterm", [T, T'], [])
  1150                   in coerce_term hol_ctxt new_Ts T' T (Const (s, T)) end
  1151                 else if is_built_in_const thy stds x then
  1152                   coerce_term hol_ctxt new_Ts T' T t
  1153                 else if is_constr ctxt stds x then
  1154                   Const (finitize_constr x)
  1155                 else if is_sel s then
  1156                   let
  1157                     val n = sel_no_from_name s
  1158                     val x' =
  1159                       x |> binarized_and_boxed_constr_for_sel hol_ctxt binarize
  1160                         |> finitize_constr
  1161                     val x'' =
  1162                       binarized_and_boxed_nth_sel_for_constr hol_ctxt binarize
  1163                                                              x' n
  1164                   in Const x'' end
  1165                 else
  1166                   Const (s, T')
  1167               | Free (s, T) => Free (s, type_from_mtype T M)
  1168               | Bound _ => t
  1169               | _ => raise MTERM ("Nitpick_Mono.finitize_funs.term_from_mterm",
  1170                                   [m])
  1171             end
  1172           | MApp (m1, m2) =>
  1173             let
  1174               val (t1, t2) = pairself (term_from_mterm new_Ts old_Ts) (m1, m2)
  1175               val (T1, T2) = pairself (curry fastype_of1 new_Ts) (t1, t2)
  1176               val (t1', T2') =
  1177                 case T1 of
  1178                   Type (s, [T11, T12]) =>
  1179                   (if s = @{type_name fin_fun} then
  1180                      select_nth_constr_arg ctxt stds (fin_fun_constr T11 T12) t1
  1181                                            0 (T11 --> T12)
  1182                    else
  1183                      t1, T11)
  1184                 | _ => raise TYPE ("Nitpick_Mono.finitize_funs.term_from_mterm",
  1185                                    [T1], [])
  1186             in betapply (t1', coerce_term hol_ctxt new_Ts T2' T2 t2) end
  1187           | MAbs (s, old_T, M, aa, m') =>
  1188             let
  1189               val new_T = type_from_mtype old_T M
  1190               val t' = term_from_mterm (new_T :: new_Ts) (old_T :: old_Ts) m'
  1191               val T' = fastype_of1 (new_T :: new_Ts, t')
  1192             in
  1193               Abs (s, new_T, t')
  1194               |> should_finitize (new_T --> T') aa
  1195                  ? construct_value ctxt stds (fin_fun_constr new_T T') o single
  1196             end
  1197       in
  1198         Unsynchronized.change constr_cache (map (apsnd (map finitize_constr)));
  1199         pairself (map (term_from_mterm [] [])) msp
  1200       end
  1201   | NONE => tsp
  1202 
  1203 end;