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