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