src/HOL/Tools/Nitpick/nitpick_model.ML
author blanchet
Fri Nov 13 15:59:53 2009 +0100 (2009-11-13)
changeset 33705 947184dc75c9
parent 33580 45c33e97cb86
child 33884 a0c43f185fef
permissions -rw-r--r--
removed a few global names in Nitpick (styp, nat_less, pairf)
     1 (*  Title:      HOL/Nitpick/Tools/nitpick_model.ML
     2     Author:     Jasmin Blanchette, TU Muenchen
     3     Copyright   2009
     4 
     5 Model reconstruction for Nitpick.
     6 *)
     7 
     8 signature NITPICK_MODEL =
     9 sig
    10   type styp = Nitpick_Util.styp
    11   type scope = Nitpick_Scope.scope
    12   type rep = Nitpick_Rep.rep
    13   type nut = Nitpick_Nut.nut
    14 
    15   type params = {
    16     show_skolems: bool,
    17     show_datatypes: bool,
    18     show_consts: bool}
    19 
    20   structure NameTable : TABLE
    21 
    22   val tuple_list_for_name :
    23     nut NameTable.table -> Kodkod.raw_bound list -> nut -> int list list
    24   val reconstruct_hol_model :
    25     params -> scope -> (term option * int list) list -> styp list -> nut list
    26     -> nut list -> nut list -> nut NameTable.table -> Kodkod.raw_bound list
    27     -> Pretty.T * bool
    28   val prove_hol_model :
    29     scope -> Time.time option -> nut list -> nut list -> nut NameTable.table
    30     -> Kodkod.raw_bound list -> term -> bool option
    31 end;
    32 
    33 structure Nitpick_Model : NITPICK_MODEL =
    34 struct
    35 
    36 open Nitpick_Util
    37 open Nitpick_HOL
    38 open Nitpick_Scope
    39 open Nitpick_Peephole
    40 open Nitpick_Rep
    41 open Nitpick_Nut
    42 
    43 type params = {
    44   show_skolems: bool,
    45   show_datatypes: bool,
    46   show_consts: bool}
    47 
    48 val unknown = "?"
    49 val unrep = "\<dots>"
    50 val maybe_mixfix = "_\<^sup>?"
    51 val base_mixfix = "_\<^bsub>base\<^esub>"
    52 val step_mixfix = "_\<^bsub>step\<^esub>"
    53 val abs_mixfix = "\<guillemotleft>_\<guillemotright>"
    54 val non_opt_name = nitpick_prefix ^ "non_opt"
    55 
    56 (* string -> typ -> int -> string *)
    57 fun atom_name prefix (T as Type (s, _)) j =
    58     prefix ^ substring (short_name s, 0, 1) ^ nat_subscript (j + 1)
    59   | atom_name prefix (T as TFree (s, _)) j =
    60     prefix ^ perhaps (try (unprefix "'")) s ^ nat_subscript (j + 1)
    61   | atom_name _ T _ = raise TYPE ("Nitpick_Model.atom_name", [T], [])
    62 (* bool -> typ -> int -> term *)
    63 fun atom for_auto T j =
    64   if for_auto then
    65     Free (atom_name (hd (space_explode "." nitpick_prefix)) T j, T)
    66   else
    67     Const (atom_name "" T j, T)
    68 
    69 (* nut NameTable.table -> Kodkod.raw_bound list -> nut -> int list list *)
    70 fun tuple_list_for_name rel_table bounds name =
    71   the (AList.lookup (op =) bounds (the_rel rel_table name)) handle NUT _ => [[]]
    72 
    73 (* term -> term *)
    74 fun unbox_term (Const (@{const_name FunBox}, _) $ t1) = unbox_term t1
    75   | unbox_term (Const (@{const_name PairBox},
    76                        Type ("fun", [T1, Type ("fun", [T2, T3])])) $ t1 $ t2) =
    77     let val Ts = map unbox_type [T1, T2] in
    78       Const (@{const_name Pair}, Ts ---> Type ("*", Ts))
    79       $ unbox_term t1 $ unbox_term t2
    80     end
    81   | unbox_term (Const (s, T)) = Const (s, unbox_type T)
    82   | unbox_term (t1 $ t2) = unbox_term t1 $ unbox_term t2
    83   | unbox_term (Free (s, T)) = Free (s, unbox_type T)
    84   | unbox_term (Var (x, T)) = Var (x, unbox_type T)
    85   | unbox_term (Bound j) = Bound j
    86   | unbox_term (Abs (s, T, t')) = Abs (s, unbox_type T, unbox_term t')
    87 
    88 (* typ -> typ -> (typ * typ) * (typ * typ) *)
    89 fun factor_out_types (T1 as Type ("*", [T11, T12]))
    90                      (T2 as Type ("*", [T21, T22])) =
    91     let val (n1, n2) = pairself num_factors_in_type (T11, T21) in
    92       if n1 = n2 then
    93         let
    94           val ((T11', opt_T12'), (T21', opt_T22')) = factor_out_types T12 T22
    95         in
    96           ((Type ("*", [T11, T11']), opt_T12'),
    97            (Type ("*", [T21, T21']), opt_T22'))
    98         end
    99       else if n1 < n2 then
   100         case factor_out_types T1 T21 of
   101           (p1, (T21', NONE)) => (p1, (T21', SOME T22))
   102         | (p1, (T21', SOME T22')) =>
   103           (p1, (T21', SOME (Type ("*", [T22', T22]))))
   104       else
   105         swap (factor_out_types T2 T1)
   106     end
   107   | factor_out_types (Type ("*", [T11, T12])) T2 = ((T11, SOME T12), (T2, NONE))
   108   | factor_out_types T1 (Type ("*", [T21, T22])) = ((T1, NONE), (T21, SOME T22))
   109   | factor_out_types T1 T2 = ((T1, NONE), (T2, NONE))
   110 
   111 (* bool -> typ -> typ -> (term * term) list -> term *)
   112 fun make_plain_fun maybe_opt T1 T2 =
   113   let
   114     (* typ -> typ -> (term * term) list -> term *)
   115     fun aux T1 T2 [] =
   116         Const (if maybe_opt orelse T2 <> bool_T then @{const_name undefined}
   117                else non_opt_name, T1 --> T2)
   118       | aux T1 T2 ((t1, t2) :: ps) =
   119         Const (@{const_name fun_upd}, [T1 --> T2, T1, T2] ---> T1 --> T2)
   120         $ aux T1 T2 ps $ t1 $ t2
   121   in aux T1 T2 o rev end
   122 (* term -> bool *)
   123 fun is_plain_fun (Const (s, _)) = s mem [@{const_name undefined}, non_opt_name]
   124   | is_plain_fun (Const (@{const_name fun_upd}, _) $ t0 $ _ $ _) =
   125     is_plain_fun t0
   126   | is_plain_fun _ = false
   127 (* term -> bool * (term list * term list) *)
   128 val dest_plain_fun =
   129   let
   130     (* term -> term list * term list *)
   131     fun aux (Const (s, _)) = (s <> non_opt_name, ([], []))
   132       | aux (Const (@{const_name fun_upd}, _) $ t0 $ t1 $ t2) =
   133         let val (s, (ts1, ts2)) = aux t0 in (s, (t1 :: ts1, t2 :: ts2)) end
   134       | aux t = raise TERM ("Nitpick_Model.dest_plain_fun", [t])
   135   in apsnd (pairself rev) o aux end
   136 
   137 (* typ -> typ -> typ -> term -> term * term *)
   138 fun break_in_two T T1 T2 t =
   139   let
   140     val ps = HOLogic.flat_tupleT_paths T
   141     val cut = length (HOLogic.strip_tupleT T1)
   142     val (ps1, ps2) = pairself HOLogic.flat_tupleT_paths (T1, T2)
   143     val (ts1, ts2) = t |> HOLogic.strip_ptuple ps |> chop cut
   144   in (HOLogic.mk_ptuple ps1 T1 ts1, HOLogic.mk_ptuple ps2 T2 ts2) end
   145 (* typ -> term -> term -> term *)
   146 fun pair_up (Type ("*", [T1', T2']))
   147             (t1 as Const (@{const_name Pair},
   148                           Type ("fun", [_, Type ("fun", [_, T1])])) $ t11 $ t12)
   149             t2 =
   150     if T1 = T1' then HOLogic.mk_prod (t1, t2)
   151     else HOLogic.mk_prod (t11, pair_up T2' t12 t2)
   152   | pair_up _ t1 t2 = HOLogic.mk_prod (t1, t2)
   153 (* typ -> term -> term list * term list -> (term * term) list*)
   154 fun multi_pair_up T1 t1 (ts2, ts3) = map2 (pair o pair_up T1 t1) ts2 ts3
   155 
   156 (* typ -> typ -> typ -> term -> term *)
   157 fun typecast_fun (Type ("fun", [T1', T2'])) T1 T2 t =
   158     let
   159       (* typ -> typ -> typ -> typ -> term -> term *)
   160       fun do_curry T1 T1a T1b T2 t =
   161         let
   162           val (maybe_opt, ps) = dest_plain_fun t
   163           val ps =
   164             ps |>> map (break_in_two T1 T1a T1b)
   165                |> uncurry (map2 (fn (t1a, t1b) => fn t2 => (t1a, (t1b, t2))))
   166                |> AList.coalesce (op =)
   167                |> map (apsnd (make_plain_fun maybe_opt T1b T2))
   168         in make_plain_fun maybe_opt T1a (T1b --> T2) ps end
   169       (* typ -> typ -> term -> term *)
   170       and do_uncurry T1 T2 t =
   171         let
   172           val (maybe_opt, tsp) = dest_plain_fun t
   173           val ps =
   174             tsp |> op ~~
   175                 |> maps (fn (t1, t2) =>
   176                             multi_pair_up T1 t1 (snd (dest_plain_fun t2)))
   177         in make_plain_fun maybe_opt T1 T2 ps end
   178       (* typ -> typ -> typ -> typ -> term -> term *)
   179       and do_arrow T1' T2' _ _ (Const (s, _)) = Const (s, T1' --> T2')
   180         | do_arrow T1' T2' T1 T2
   181                    (Const (@{const_name fun_upd}, _) $ t0 $ t1 $ t2) =
   182           Const (@{const_name fun_upd},
   183                  [T1' --> T2', T1', T2'] ---> T1' --> T2')
   184           $ do_arrow T1' T2' T1 T2 t0 $ do_term T1' T1 t1 $ do_term T2' T2 t2
   185         | do_arrow _ _ _ _ t =
   186           raise TERM ("Nitpick_Model.typecast_fun.do_arrow", [t])
   187       and do_fun T1' T2' T1 T2 t =
   188         case factor_out_types T1' T1 of
   189           ((_, NONE), (_, NONE)) => t |> do_arrow T1' T2' T1 T2
   190         | ((_, NONE), (T1a, SOME T1b)) =>
   191           t |> do_curry T1 T1a T1b T2 |> do_arrow T1' T2' T1a (T1b --> T2)
   192         | ((T1a', SOME T1b'), (_, NONE)) =>
   193           t |> do_arrow T1a' (T1b' --> T2') T1 T2 |> do_uncurry T1' T2'
   194         | _ => raise TYPE ("Nitpick_Model.typecast_fun.do_fun", [T1, T1'], [])
   195       (* typ -> typ -> term -> term *)
   196       and do_term (Type ("fun", [T1', T2'])) (Type ("fun", [T1, T2])) t =
   197           do_fun T1' T2' T1 T2 t
   198         | do_term (T' as Type ("*", Ts' as [T1', T2'])) (Type ("*", [T1, T2]))
   199                   (Const (@{const_name Pair}, _) $ t1 $ t2) =
   200           Const (@{const_name Pair}, Ts' ---> T')
   201           $ do_term T1' T1 t1 $ do_term T2' T2 t2
   202         | do_term T' T t =
   203           if T = T' then t
   204           else raise TYPE ("Nitpick_Model.typecast_fun.do_term", [T, T'], [])
   205     in if T1' = T1 andalso T2' = T2 then t else do_fun T1' T2' T1 T2 t end
   206   | typecast_fun T' _ _ _ = raise TYPE ("Nitpick_Model.typecast_fun", [T'], [])
   207 
   208 (* term -> string *)
   209 fun truth_const_sort_key @{const True} = "0"
   210   | truth_const_sort_key @{const False} = "2"
   211   | truth_const_sort_key _ = "1"
   212 
   213 (* typ -> term list -> term *)
   214 fun mk_tuple (Type ("*", [T1, T2])) ts =
   215     HOLogic.mk_prod (mk_tuple T1 ts,
   216         mk_tuple T2 (List.drop (ts, length (HOLogic.flatten_tupleT T1))))
   217   | mk_tuple _ (t :: _) = t
   218 
   219 (* string * string * string * string -> scope -> nut list -> nut list
   220    -> nut list -> nut NameTable.table -> Kodkod.raw_bound list -> typ -> typ
   221    -> rep -> int list list -> term *)
   222 fun reconstruct_term (maybe_name, base_name, step_name, abs_name)
   223         ({ext_ctxt as {thy, ctxt, ...}, card_assigns, datatypes, ofs, ...}
   224          : scope) sel_names rel_table bounds =
   225   let
   226     val for_auto = (maybe_name = "")
   227     (* bool -> typ -> typ -> (term * term) list -> term *)
   228     fun make_set maybe_opt T1 T2 =
   229       let
   230         val empty_const = Const (@{const_name Set.empty}, T1 --> T2)
   231         val insert_const = Const (@{const_name insert},
   232                                   [T1, T1 --> T2] ---> T1 --> T2)
   233         (* (term * term) list -> term *)
   234         fun aux [] =
   235             if maybe_opt andalso not (is_precise_type datatypes T1) then
   236               insert_const $ Const (unrep, T1) $ empty_const
   237             else
   238               empty_const
   239           | aux ((t1, t2) :: zs) =
   240             aux zs |> t2 <> @{const False}
   241                       ? curry (op $) (insert_const
   242                                       $ (t1 |> t2 <> @{const True}
   243                                                ? curry (op $)
   244                                                        (Const (maybe_name,
   245                                                                T1 --> T1))))
   246       in aux end
   247     (* typ -> typ -> typ -> (term * term) list -> term *)
   248     fun make_map T1 T2 T2' =
   249       let
   250         val update_const = Const (@{const_name fun_upd},
   251                                   [T1 --> T2, T1, T2] ---> T1 --> T2)
   252         (* (term * term) list -> term *)
   253         fun aux' [] = Const (@{const_name Map.empty}, T1 --> T2)
   254           | aux' ((t1, t2) :: ps) =
   255             (case t2 of
   256                Const (@{const_name None}, _) => aux' ps
   257              | _ => update_const $ aux' ps $ t1 $ t2)
   258         fun aux ps =
   259           if not (is_precise_type datatypes T1) then
   260             update_const $ aux' ps $ Const (unrep, T1)
   261             $ (Const (@{const_name Some}, T2' --> T2) $ Const (unknown, T2'))
   262           else
   263             aux' ps
   264       in aux end
   265     (* typ list -> term -> term *)
   266     fun setify_mapify_funs Ts t =
   267       (case fastype_of1 (Ts, t) of
   268          Type ("fun", [T1, T2]) =>
   269          if is_plain_fun t then
   270            case T2 of
   271              @{typ bool} =>
   272              let
   273                val (maybe_opt, ts_pair) =
   274                  dest_plain_fun t ||> pairself (map (setify_mapify_funs Ts))
   275              in
   276                make_set maybe_opt T1 T2
   277                         (sort_wrt (truth_const_sort_key o snd) (op ~~ ts_pair))
   278              end
   279            | Type (@{type_name option}, [T2']) =>
   280              let
   281                val ts_pair = snd (dest_plain_fun t)
   282                              |> pairself (map (setify_mapify_funs Ts))
   283              in make_map T1 T2 T2' (rev (op ~~ ts_pair)) end
   284            | _ => raise SAME ()
   285          else
   286            raise SAME ()
   287        | _ => raise SAME ())
   288       handle SAME () =>
   289              case t of
   290                t1 $ t2 => setify_mapify_funs Ts t1 $ setify_mapify_funs Ts t2
   291              | Abs (s, T, t') => Abs (s, T, setify_mapify_funs (T :: Ts) t')
   292              | _ => t
   293     (* bool -> typ -> typ -> typ -> term list -> term list -> term *)
   294     fun make_fun maybe_opt T1 T2 T' ts1 ts2 =
   295       ts1 ~~ ts2 |> T1 = @{typ bisim_iterator} ? rev
   296                  |> make_plain_fun (maybe_opt andalso not for_auto) T1 T2
   297                  |> unbox_term
   298                  |> typecast_fun (unbox_type T') (unbox_type T1) (unbox_type T2)
   299     (* (typ * int) list -> typ -> typ -> int -> term *)
   300     fun term_for_atom seen (T as Type ("fun", [T1, T2])) T' j =
   301         let
   302           val k1 = card_of_type card_assigns T1
   303           val k2 = card_of_type card_assigns T2
   304         in
   305           term_for_rep seen T T' (Vect (k1, Atom (k2, 0)))
   306                        [nth_combination (replicate k1 (k2, 0)) j]
   307           handle General.Subscript =>
   308                  raise ARG ("Nitpick_Model.reconstruct_term.term_for_atom",
   309                             signed_string_of_int j ^ " for " ^
   310                             string_for_rep (Vect (k1, Atom (k2, 0))))
   311         end
   312       | term_for_atom seen (Type ("*", [T1, T2])) _ j =
   313         let val k1 = card_of_type card_assigns T1 in
   314           list_comb (HOLogic.pair_const T1 T2,
   315                      map2 (fn T => term_for_atom seen T T) [T1, T2]
   316                           [j div k1, j mod k1])
   317         end
   318       | term_for_atom seen @{typ prop} _ j =
   319         HOLogic.mk_Trueprop (term_for_atom seen bool_T bool_T j)
   320       | term_for_atom _ @{typ bool} _ j =
   321         if j = 0 then @{const False} else @{const True}
   322       | term_for_atom _ @{typ unit} _ _ = @{const Unity}
   323       | term_for_atom seen T _ j =
   324         if T = nat_T then
   325           HOLogic.mk_number nat_T j
   326         else if T = int_T then
   327           HOLogic.mk_number int_T
   328               (int_for_atom (card_of_type card_assigns int_T, 0) j)
   329         else if is_fp_iterator_type T then
   330           HOLogic.mk_number nat_T (card_of_type card_assigns T - j - 1)
   331         else if T = @{typ bisim_iterator} then
   332           HOLogic.mk_number nat_T j
   333         else case datatype_spec datatypes T of
   334           NONE => atom for_auto T j
   335         | SOME {shallow = true, ...} => atom for_auto T j
   336         | SOME {co, constrs, ...} =>
   337           let
   338             (* styp -> int list *)
   339             fun tuples_for_const (s, T) =
   340               tuple_list_for_name rel_table bounds (ConstName (s, T, Any))
   341             (* unit -> indexname * typ *)
   342             fun var () = ((atom_name "" T j, 0), T)
   343             val discr_jsss = map (tuples_for_const o discr_for_constr o #const)
   344                                  constrs
   345             val real_j = j + offset_of_type ofs T
   346             val constr_x as (constr_s, constr_T) =
   347               get_first (fn (jss, {const, ...}) =>
   348                             if [real_j] mem jss then SOME const else NONE)
   349                         (discr_jsss ~~ constrs) |> the
   350             val arg_Ts = curried_binder_types constr_T
   351             val sel_xs = map (boxed_nth_sel_for_constr ext_ctxt constr_x)
   352                              (index_seq 0 (length arg_Ts))
   353             val sel_Rs =
   354               map (fn x => get_first
   355                                (fn ConstName (s', T', R) =>
   356                                    if (s', T') = x then SOME R else NONE
   357                                  | u => raise NUT ("Nitpick_Model.reconstruct_\
   358                                                    \term.term_for_atom", [u]))
   359                                sel_names |> the) sel_xs
   360             val arg_Rs = map (snd o dest_Func) sel_Rs
   361             val sel_jsss = map tuples_for_const sel_xs
   362             val arg_jsss =
   363               map (map_filter (fn js => if hd js = real_j then SOME (tl js)
   364                                         else NONE)) sel_jsss
   365             val uncur_arg_Ts = binder_types constr_T
   366           in
   367             if co andalso (T, j) mem seen then
   368               Var (var ())
   369             else
   370               let
   371                 val seen = seen |> co ? cons (T, j)
   372                 val ts =
   373                   if length arg_Ts = 0 then
   374                     []
   375                   else
   376                     map3 (fn Ts => term_for_rep seen Ts Ts) arg_Ts arg_Rs
   377                          arg_jsss
   378                     |> mk_tuple (HOLogic.mk_tupleT uncur_arg_Ts)
   379                     |> dest_n_tuple (length uncur_arg_Ts)
   380                 val t =
   381                   if constr_s = @{const_name Abs_Frac} then
   382                     let
   383                       val num_T = body_type T
   384                       (* int -> term *)
   385                       val mk_num = HOLogic.mk_number num_T
   386                     in
   387                       case ts of
   388                         [Const (@{const_name Pair}, _) $ t1 $ t2] =>
   389                         (case snd (HOLogic.dest_number t1) of
   390                            0 => mk_num 0
   391                          | n1 => case HOLogic.dest_number t2 |> snd of
   392                                    1 => mk_num n1
   393                                  | n2 => Const (@{const_name HOL.divide},
   394                                                 [num_T, num_T] ---> num_T)
   395                                          $ mk_num n1 $ mk_num n2)
   396                       | _ => raise TERM ("Nitpick_Model.reconstruct_term.term_\
   397                                          \for_atom (Abs_Frac)", ts)
   398                     end
   399                   else if not for_auto andalso is_abs_fun thy constr_x then
   400                     Const (abs_name, constr_T) $ the_single ts
   401                   else
   402                     list_comb (Const constr_x, ts)
   403               in
   404                 if co then
   405                   let val var = var () in
   406                     if exists_subterm (equal (Var var)) t then
   407                       Const (@{const_name The}, (T --> bool_T) --> T)
   408                       $ Abs ("\<omega>", T,
   409                              Const (@{const_name "op ="}, [T, T] ---> bool_T)
   410                              $ Bound 0 $ abstract_over (Var var, t))
   411                     else
   412                       t
   413                   end
   414                 else
   415                   t
   416               end
   417           end
   418     (* (typ * int) list -> int -> rep -> typ -> typ -> typ -> int list
   419        -> term *)
   420     and term_for_vect seen k R T1 T2 T' js =
   421       make_fun true T1 T2 T' (map (term_for_atom seen T1 T1) (index_seq 0 k))
   422                (map (term_for_rep seen T2 T2 R o single)
   423                     (batch_list (arity_of_rep R) js))
   424     (* (typ * int) list -> typ -> typ -> rep -> int list list -> term *)
   425     and term_for_rep seen T T' Unit [[]] = term_for_atom seen T T' 0
   426       | term_for_rep seen T T' (R as Atom (k, j0)) [[j]] =
   427         if j >= j0 andalso j < j0 + k then term_for_atom seen T T' (j - j0)
   428         else raise REP ("Nitpick_Model.reconstruct_term.term_for_rep", [R])
   429       | term_for_rep seen (Type ("*", [T1, T2])) _ (Struct [R1, R2]) [js] =
   430         let
   431           val arity1 = arity_of_rep R1
   432           val (js1, js2) = chop arity1 js
   433         in
   434           list_comb (HOLogic.pair_const T1 T2,
   435                      map3 (fn T => term_for_rep seen T T) [T1, T2] [R1, R2]
   436                           [[js1], [js2]])
   437         end
   438       | term_for_rep seen (Type ("fun", [T1, T2])) T' (R as Vect (k, R')) [js] =
   439         term_for_vect seen k R' T1 T2 T' js
   440       | term_for_rep seen (Type ("fun", [T1, T2])) T' (Func (R1, Formula Neut))
   441                      jss =
   442         let
   443           val jss1 = all_combinations_for_rep R1
   444           val ts1 = map (term_for_rep seen T1 T1 R1 o single) jss1
   445           val ts2 =
   446             map (fn js => term_for_rep seen T2 T2 (Atom (2, 0))
   447                                        [[int_for_bool (js mem jss)]]) jss1
   448         in make_fun false T1 T2 T' ts1 ts2 end
   449       | term_for_rep seen (Type ("fun", [T1, T2])) T' (Func (R1, R2)) jss =
   450         let
   451           val arity1 = arity_of_rep R1
   452           val jss1 = all_combinations_for_rep R1
   453           val ts1 = map (term_for_rep seen T1 T1 R1 o single) jss1
   454           val grouped_jss2 = AList.group (op =) (map (chop arity1) jss)
   455           val ts2 = map (term_for_rep seen T2 T2 R2 o the_default []
   456                          o AList.lookup (op =) grouped_jss2) jss1
   457         in make_fun true T1 T2 T' ts1 ts2 end
   458       | term_for_rep seen T T' (Opt R) jss =
   459         if null jss then Const (unknown, T) else term_for_rep seen T T' R jss
   460       | term_for_rep seen T _ R jss =
   461         raise ARG ("Nitpick_Model.reconstruct_term.term_for_rep",
   462                    Refute.string_of_typ T ^ " " ^ string_for_rep R ^ " " ^
   463                    string_of_int (length jss))
   464   in
   465     (not for_auto ? setify_mapify_funs []) o unbox_term oooo term_for_rep []
   466   end
   467 
   468 (* scope -> nut list -> nut NameTable.table -> Kodkod.raw_bound list -> nut
   469    -> term *)
   470 fun term_for_name scope sel_names rel_table bounds name =
   471   let val T = type_of name in
   472     tuple_list_for_name rel_table bounds name
   473     |> reconstruct_term ("", "", "", "") scope sel_names rel_table bounds T T
   474                         (rep_of name)
   475   end
   476 
   477 (* Proof.context
   478    -> (string * string * string * string * string) * Proof.context *)
   479 fun add_wacky_syntax ctxt =
   480   let
   481     (* term -> string *)
   482     val name_of = fst o dest_Const
   483     val thy = ProofContext.theory_of ctxt |> Context.reject_draft
   484     val (maybe_t, thy) =
   485       Sign.declare_const ((@{binding nitpick_maybe}, @{typ "'a => 'a"}),
   486                           Mixfix (maybe_mixfix, [1000], 1000)) thy
   487     val (base_t, thy) =
   488       Sign.declare_const ((@{binding nitpick_base}, @{typ "'a => 'a"}),
   489                           Mixfix (base_mixfix, [1000], 1000)) thy
   490     val (step_t, thy) =
   491       Sign.declare_const ((@{binding nitpick_step}, @{typ "'a => 'a"}),
   492                           Mixfix (step_mixfix, [1000], 1000)) thy
   493     val (abs_t, thy) =
   494       Sign.declare_const ((@{binding nitpick_abs}, @{typ "'a => 'b"}),
   495                           Mixfix (abs_mixfix, [40], 40)) thy
   496   in
   497     ((name_of maybe_t, name_of base_t, name_of step_t, name_of abs_t),
   498      ProofContext.transfer_syntax thy ctxt)
   499   end
   500 
   501 (* term -> term *)
   502 fun unfold_outer_the_binders (t as Const (@{const_name The}, _)
   503                                    $ Abs (s, T, Const (@{const_name "op ="}, _)
   504                                                 $ Bound 0 $ t')) =
   505     betapply (Abs (s, T, t'), t) |> unfold_outer_the_binders
   506   | unfold_outer_the_binders t = t
   507 (* typ list -> int -> term * term -> bool *)
   508 fun bisimilar_values _ 0 _ = true
   509   | bisimilar_values coTs max_depth (t1, t2) =
   510     let val T = fastype_of t1 in
   511       if exists_subtype (member (op =) coTs) T then
   512         let
   513           val ((head1, args1), (head2, args2)) =
   514             pairself (strip_comb o unfold_outer_the_binders) (t1, t2)
   515           val max_depth = max_depth - (if T mem coTs then 1 else 0)
   516         in
   517           head1 = head2
   518           andalso forall (bisimilar_values coTs max_depth) (args1 ~~ args2)
   519         end
   520       else
   521         t1 = t2
   522     end
   523 
   524 (* params -> scope -> (term option * int list) list -> styp list -> nut list
   525   -> nut list -> nut list -> nut NameTable.table -> Kodkod.raw_bound list
   526   -> Pretty.T * bool *)
   527 fun reconstruct_hol_model {show_skolems, show_datatypes, show_consts}
   528         ({ext_ctxt as {thy, ctxt, max_bisim_depth, boxes, user_axioms, debug,
   529                        wfs, destroy_constrs, specialize, skolemize,
   530                        star_linear_preds, uncurry, fast_descrs, tac_timeout,
   531                        evals, case_names, def_table, nondef_table, user_nondefs,
   532                        simp_table, psimp_table, intro_table, ground_thm_table,
   533                        ersatz_table, skolems, special_funs, unrolled_preds,
   534                        wf_cache, constr_cache},
   535          card_assigns, bisim_depth, datatypes, ofs} : scope) formats all_frees
   536         free_names sel_names nonsel_names rel_table bounds =
   537   let
   538     val (wacky_names as (_, base_name, step_name, _), ctxt) =
   539       add_wacky_syntax ctxt
   540     val ext_ctxt =
   541       {thy = thy, ctxt = ctxt, max_bisim_depth = max_bisim_depth, boxes = boxes,
   542        wfs = wfs, user_axioms = user_axioms, debug = debug,
   543        destroy_constrs = destroy_constrs, specialize = specialize,
   544        skolemize = skolemize, star_linear_preds = star_linear_preds,
   545        uncurry = uncurry, fast_descrs = fast_descrs, tac_timeout = tac_timeout,
   546        evals = evals, case_names = case_names, def_table = def_table,
   547        nondef_table = nondef_table, user_nondefs = user_nondefs,
   548        simp_table = simp_table, psimp_table = psimp_table,
   549        intro_table = intro_table, ground_thm_table = ground_thm_table,
   550        ersatz_table = ersatz_table, skolems = skolems,
   551        special_funs = special_funs, unrolled_preds = unrolled_preds,
   552        wf_cache = wf_cache, constr_cache = constr_cache}
   553     val scope = {ext_ctxt = ext_ctxt, card_assigns = card_assigns,
   554                  bisim_depth = bisim_depth, datatypes = datatypes, ofs = ofs}
   555     (* typ -> typ -> rep -> int list list -> term *)
   556     val term_for_rep = reconstruct_term wacky_names scope sel_names rel_table
   557                                         bounds
   558     (* typ -> typ -> typ *)
   559     fun nth_value_of_type T card n = term_for_rep T T (Atom (card, 0)) [[n]]
   560     (* dtype_spec list -> dtype_spec -> bool *)
   561     fun is_codatatype_wellformed (cos : dtype_spec list)
   562                                  ({typ, card, ...} : dtype_spec) =
   563       let
   564         val ts = map (nth_value_of_type typ card) (index_seq 0 card)
   565         val max_depth = Integer.sum (map #card cos)
   566       in
   567         forall (not o bisimilar_values (map #typ cos) max_depth)
   568                (all_distinct_unordered_pairs_of ts)
   569       end
   570     (* string -> Pretty.T *)
   571     fun pretty_for_assign name =
   572       let
   573         val (oper, (t1, T'), T) =
   574           case name of
   575             FreeName (s, T, _) =>
   576             let val t = Free (s, unbox_type T) in
   577               ("=", (t, format_term_type thy def_table formats t), T)
   578             end
   579           | ConstName (s, T, _) =>
   580             (assign_operator_for_const (s, T),
   581              user_friendly_const ext_ctxt (base_name, step_name) formats (s, T),
   582              T)
   583           | _ => raise NUT ("Nitpick_Model.reconstruct_hol_model.\
   584                             \pretty_for_assign", [name])
   585         val t2 = if rep_of name = Any then
   586                    Const (@{const_name undefined}, T')
   587                  else
   588                    tuple_list_for_name rel_table bounds name
   589                    |> term_for_rep T T' (rep_of name)
   590       in
   591         Pretty.block (Pretty.breaks
   592             [setmp_show_all_types (Syntax.pretty_term ctxt) t1,
   593              Pretty.str oper, Syntax.pretty_term ctxt t2])
   594       end
   595     (* dtype_spec -> Pretty.T *)
   596     fun pretty_for_datatype ({typ, card, precise, ...} : dtype_spec) =
   597       Pretty.block (Pretty.breaks
   598           [Syntax.pretty_typ ctxt (unbox_type typ), Pretty.str "=",
   599            Pretty.enum "," "{" "}"
   600                (map (Syntax.pretty_term ctxt o nth_value_of_type typ card)
   601                     (index_seq 0 card) @
   602                 (if precise then [] else [Pretty.str unrep]))])
   603     (* typ -> dtype_spec list *)
   604     fun integer_datatype T =
   605       [{typ = T, card = card_of_type card_assigns T, co = false,
   606         precise = false, shallow = false, constrs = []}]
   607       handle TYPE ("Nitpick_HOL.card_of_type", _, _) => []
   608     val (codatatypes, datatypes) =
   609       datatypes |> filter_out #shallow
   610                 |> List.partition #co
   611                 ||> append (integer_datatype nat_T @ integer_datatype int_T)
   612     val block_of_datatypes =
   613       if show_datatypes andalso not (null datatypes) then
   614         [Pretty.big_list ("Datatype" ^ plural_s_for_list datatypes ^ ":")
   615                          (map pretty_for_datatype datatypes)]
   616       else
   617         []
   618     val block_of_codatatypes =
   619       if show_datatypes andalso not (null codatatypes) then
   620         [Pretty.big_list ("Codatatype" ^ plural_s_for_list codatatypes ^ ":")
   621                          (map pretty_for_datatype codatatypes)]
   622       else
   623         []
   624     (* bool -> string -> nut list -> Pretty.T list *)
   625     fun block_of_names show title names =
   626       if show andalso not (null names) then
   627         Pretty.str (title ^ plural_s_for_list names ^ ":")
   628         :: map (Pretty.indent indent_size o pretty_for_assign)
   629                (sort_wrt (original_name o nickname_of) names)
   630       else
   631         []
   632     val (skolem_names, nonskolem_nonsel_names) =
   633       List.partition is_skolem_name nonsel_names
   634     val (eval_names, noneval_nonskolem_nonsel_names) =
   635       List.partition (String.isPrefix eval_prefix o nickname_of)
   636                      nonskolem_nonsel_names
   637       ||> filter_out (equal @{const_name bisim_iterator_max} o nickname_of)
   638     val free_names =
   639       map (fn x as (s, T) =>
   640               case filter (equal x o pairf nickname_of (unbox_type o type_of))
   641                           free_names of
   642                 [name] => name
   643               | [] => FreeName (s, T, Any)
   644               | _ => raise TERM ("Nitpick_Model.reconstruct_hol_model",
   645                                  [Const x])) all_frees
   646     val chunks = block_of_names true "Free variable" free_names @
   647                  block_of_names show_skolems "Skolem constant" skolem_names @
   648                  block_of_names true "Evaluated term" eval_names @
   649                  block_of_datatypes @ block_of_codatatypes @
   650                  block_of_names show_consts "Constant"
   651                                 noneval_nonskolem_nonsel_names
   652   in
   653     (Pretty.chunks (if null chunks then [Pretty.str "Empty assignment"]
   654                     else chunks),
   655      bisim_depth >= 0
   656      orelse forall (is_codatatype_wellformed codatatypes) codatatypes)
   657   end
   658 
   659 (* scope -> Time.time option -> nut list -> nut list -> nut NameTable.table
   660    -> Kodkod.raw_bound list -> term -> bool option *)
   661 fun prove_hol_model (scope as {ext_ctxt as {thy, ctxt, ...}, card_assigns, ...})
   662                     auto_timeout free_names sel_names rel_table bounds prop =
   663   let
   664     (* typ * int -> term *)
   665     fun free_type_assm (T, k) =
   666       let
   667         (* int -> term *)
   668         val atom = atom true T
   669         fun equation_for_atom j = HOLogic.eq_const T $ Bound 0 $ atom j
   670         val eqs = map equation_for_atom (index_seq 0 k)
   671         val compreh_assm =
   672           Const (@{const_name All}, (T --> bool_T) --> bool_T)
   673               $ Abs ("x", T, foldl1 HOLogic.mk_disj eqs)
   674         val distinct_assm = distinctness_formula T (map atom (index_seq 0 k))
   675       in HOLogic.mk_conj (compreh_assm, distinct_assm) end
   676     (* nut -> term *)
   677     fun free_name_assm name =
   678       HOLogic.mk_eq (Free (nickname_of name, type_of name),
   679                      term_for_name scope sel_names rel_table bounds name)
   680     val freeT_assms = map free_type_assm (filter (is_TFree o fst) card_assigns)
   681     val model_assms = map free_name_assm free_names
   682     val assm = List.foldr HOLogic.mk_conj @{const True}
   683                           (freeT_assms @ model_assms)
   684     (* bool -> bool *)
   685     fun try_out negate =
   686       let
   687         val concl = (negate ? curry (op $) @{const Not})
   688                     (ObjectLogic.atomize_term thy prop)
   689         val goal = HOLogic.mk_Trueprop (HOLogic.mk_imp (assm, concl))
   690                    |> map_types (map_type_tfree
   691                           (fn (s, []) => TFree (s, HOLogic.typeS)
   692                             | x => TFree x))
   693                    |> cterm_of thy |> Goal.init
   694       in
   695         (goal |> SINGLE (DETERM_TIMEOUT auto_timeout
   696                                         (auto_tac (clasimpset_of ctxt)))
   697               |> the |> Goal.finish ctxt; true)
   698         handle THM _ => false
   699              | TimeLimit.TimeOut => false
   700       end
   701   in
   702     if try_out false then SOME true
   703     else if try_out true then SOME false
   704     else NONE
   705   end
   706 
   707 end;