src/HOL/Tools/Nitpick/nitpick_model.ML
author blanchet
Sat Apr 24 16:33:01 2010 +0200 (2010-04-24)
changeset 36385 ff5f88702590
parent 36384 76d5fd5a45fb
child 36388 30f7ce76712d
permissions -rw-r--r--
remove type annotations as comments;
Nitpick is now 1136 lines shorter
     1 (*  Title:      HOL/Tools/Nitpick/nitpick_model.ML
     2     Author:     Jasmin Blanchette, TU Muenchen
     3     Copyright   2009, 2010
     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   type term_postprocessor =
    20     Proof.context -> string -> (typ -> term list) -> typ -> term -> term
    21 
    22   structure NameTable : TABLE
    23 
    24   val irrelevant : string
    25   val unknown : string
    26   val unrep : string
    27   val register_term_postprocessor :
    28     typ -> term_postprocessor -> theory -> theory
    29   val unregister_term_postprocessor : typ -> theory -> theory
    30   val tuple_list_for_name :
    31     nut NameTable.table -> Kodkod.raw_bound list -> nut -> int list list
    32   val dest_plain_fun : term -> bool * (term list * term list)
    33   val reconstruct_hol_model :
    34     params -> scope -> (term option * int list) list -> styp list -> nut list
    35     -> nut list -> nut list -> nut NameTable.table -> Kodkod.raw_bound list
    36     -> Pretty.T * bool
    37   val prove_hol_model :
    38     scope -> Time.time option -> nut list -> nut list -> nut NameTable.table
    39     -> Kodkod.raw_bound list -> term -> bool option
    40 end;
    41 
    42 structure Nitpick_Model : NITPICK_MODEL =
    43 struct
    44 
    45 open Nitpick_Util
    46 open Nitpick_HOL
    47 open Nitpick_Scope
    48 open Nitpick_Peephole
    49 open Nitpick_Rep
    50 open Nitpick_Nut
    51 
    52 structure KK = Kodkod
    53 
    54 type params = {
    55   show_skolems: bool,
    56   show_datatypes: bool,
    57   show_consts: bool}
    58 
    59 type term_postprocessor =
    60   Proof.context -> string -> (typ -> term list) -> typ -> term -> term
    61 
    62 structure Data = Theory_Data(
    63   type T = (typ * term_postprocessor) list
    64   val empty = []
    65   val extend = I
    66   fun merge (ps1, ps2) = AList.merge (op =) (K true) (ps1, ps2))
    67 
    68 val irrelevant = "_"
    69 val unknown = "?"
    70 val unrep = "\<dots>"
    71 val maybe_mixfix = "_\<^sup>?"
    72 val base_mixfix = "_\<^bsub>base\<^esub>"
    73 val step_mixfix = "_\<^bsub>step\<^esub>"
    74 val abs_mixfix = "\<guillemotleft>_\<guillemotright>"
    75 val arg_var_prefix = "x"
    76 val cyclic_co_val_name = "\<omega>"
    77 val cyclic_const_prefix = "\<xi>"
    78 val cyclic_type_name = nitpick_prefix ^ cyclic_const_prefix
    79 val opt_flag = nitpick_prefix ^ "opt"
    80 val non_opt_flag = nitpick_prefix ^ "non_opt"
    81 
    82 type atom_pool = ((string * int) * int list) list
    83 
    84 fun add_wacky_syntax ctxt =
    85   let
    86     val name_of = fst o dest_Const
    87     val thy = ProofContext.theory_of ctxt |> Context.reject_draft
    88     val (maybe_t, thy) =
    89       Sign.declare_const ((@{binding nitpick_maybe}, @{typ "'a => 'a"}),
    90                           Mixfix (maybe_mixfix, [1000], 1000)) thy
    91     val (abs_t, thy) =
    92       Sign.declare_const ((@{binding nitpick_abs}, @{typ "'a => 'b"}),
    93                           Mixfix (abs_mixfix, [40], 40)) thy
    94     val (base_t, thy) =
    95       Sign.declare_const ((@{binding nitpick_base}, @{typ "'a => 'a"}),
    96                           Mixfix (base_mixfix, [1000], 1000)) thy
    97     val (step_t, thy) =
    98       Sign.declare_const ((@{binding nitpick_step}, @{typ "'a => 'a"}),
    99                           Mixfix (step_mixfix, [1000], 1000)) thy
   100   in
   101     (pairself (pairself name_of) ((maybe_t, abs_t), (base_t, step_t)),
   102      ProofContext.transfer_syntax thy ctxt)
   103   end
   104 
   105 (** Term reconstruction **)
   106 
   107 fun nth_atom_suffix pool s j k =
   108   (case AList.lookup (op =) (!pool) (s, k) of
   109      SOME js =>
   110      (case find_index (curry (op =) j) js of
   111         ~1 => (Unsynchronized.change pool (cons ((s, k), j :: js));
   112                length js + 1)
   113       | n => length js - n)
   114    | NONE => (Unsynchronized.change pool (cons ((s, k), [j])); 1))
   115   |> nat_subscript
   116   |> (s <> "" andalso Symbol.is_ascii_digit (List.last (explode s)))
   117      ? prefix "\<^isub>,"
   118 fun nth_atom_name pool prefix (Type (s, _)) j k =
   119     let val s' = shortest_name s in
   120       prefix ^ (if String.isPrefix "\\" s' then s' else substring (s', 0, 1)) ^
   121       nth_atom_suffix pool s j k
   122     end
   123   | nth_atom_name pool prefix (TFree (s, _)) j k =
   124     prefix ^ perhaps (try (unprefix "'")) s ^ nth_atom_suffix pool s j k
   125   | nth_atom_name _ _ T _ _ =
   126     raise TYPE ("Nitpick_Model.nth_atom_name", [T], [])
   127 fun nth_atom pool for_auto T j k =
   128   if for_auto then
   129     Free (nth_atom_name pool (hd (space_explode "." nitpick_prefix)) T j k, T)
   130   else
   131     Const (nth_atom_name pool "" T j k, T)
   132 
   133 fun extract_real_number (Const (@{const_name divide}, _) $ t1 $ t2) =
   134     real (snd (HOLogic.dest_number t1)) / real (snd (HOLogic.dest_number t2))
   135   | extract_real_number t = real (snd (HOLogic.dest_number t))
   136 fun nice_term_ord (Abs (_, _, t1), Abs (_, _, t2)) = nice_term_ord (t1, t2)
   137   | nice_term_ord tp = Real.compare (pairself extract_real_number tp)
   138     handle TERM ("dest_number", _) =>
   139            case tp of
   140              (t11 $ t12, t21 $ t22) =>
   141              (case nice_term_ord (t11, t21) of
   142                 EQUAL => nice_term_ord (t12, t22)
   143               | ord => ord)
   144            | _ => Term_Ord.fast_term_ord tp
   145 
   146 fun register_term_postprocessor T p = Data.map (cons (T, p))
   147 fun unregister_term_postprocessor T = Data.map (AList.delete (op =) T)
   148 
   149 fun tuple_list_for_name rel_table bounds name =
   150   the (AList.lookup (op =) bounds (the_rel rel_table name)) handle NUT _ => [[]]
   151 
   152 fun unarize_unbox_etc_term (Const (@{const_name FinFun}, _) $ t1) =
   153     unarize_unbox_etc_term t1
   154   | unarize_unbox_etc_term (Const (@{const_name FunBox}, _) $ t1) =
   155     unarize_unbox_etc_term t1
   156   | unarize_unbox_etc_term
   157         (Const (@{const_name PairBox},
   158                 Type (@{type_name fun}, [T1, Type (@{type_name fun}, [T2, _])]))
   159          $ t1 $ t2) =
   160     let val Ts = map uniterize_unarize_unbox_etc_type [T1, T2] in
   161       Const (@{const_name Pair}, Ts ---> Type (@{type_name "*"}, Ts))
   162       $ unarize_unbox_etc_term t1 $ unarize_unbox_etc_term t2
   163     end
   164   | unarize_unbox_etc_term (Const (s, T)) =
   165     Const (s, uniterize_unarize_unbox_etc_type T)
   166   | unarize_unbox_etc_term (t1 $ t2) =
   167     unarize_unbox_etc_term t1 $ unarize_unbox_etc_term t2
   168   | unarize_unbox_etc_term (Free (s, T)) =
   169     Free (s, uniterize_unarize_unbox_etc_type T)
   170   | unarize_unbox_etc_term (Var (x, T)) =
   171     Var (x, uniterize_unarize_unbox_etc_type T)
   172   | unarize_unbox_etc_term (Bound j) = Bound j
   173   | unarize_unbox_etc_term (Abs (s, T, t')) =
   174     Abs (s, uniterize_unarize_unbox_etc_type T, unarize_unbox_etc_term t')
   175 
   176 fun factor_out_types (T1 as Type (@{type_name "*"}, [T11, T12]))
   177                      (T2 as Type (@{type_name "*"}, [T21, T22])) =
   178     let val (n1, n2) = pairself num_factors_in_type (T11, T21) in
   179       if n1 = n2 then
   180         let
   181           val ((T11', opt_T12'), (T21', opt_T22')) = factor_out_types T12 T22
   182         in
   183           ((Type (@{type_name "*"}, [T11, T11']), opt_T12'),
   184            (Type (@{type_name "*"}, [T21, T21']), opt_T22'))
   185         end
   186       else if n1 < n2 then
   187         case factor_out_types T1 T21 of
   188           (p1, (T21', NONE)) => (p1, (T21', SOME T22))
   189         | (p1, (T21', SOME T22')) =>
   190           (p1, (T21', SOME (Type (@{type_name "*"}, [T22', T22]))))
   191       else
   192         swap (factor_out_types T2 T1)
   193     end
   194   | factor_out_types (Type (@{type_name "*"}, [T11, T12])) T2 =
   195     ((T11, SOME T12), (T2, NONE))
   196   | factor_out_types T1 (Type (@{type_name "*"}, [T21, T22])) =
   197     ((T1, NONE), (T21, SOME T22))
   198   | factor_out_types T1 T2 = ((T1, NONE), (T2, NONE))
   199 
   200 fun make_plain_fun maybe_opt T1 T2 =
   201   let
   202     fun aux T1 T2 [] =
   203         Const (if maybe_opt then opt_flag else non_opt_flag, T1 --> T2)
   204       | aux T1 T2 ((t1, t2) :: tps) =
   205         Const (@{const_name fun_upd}, (T1 --> T2) --> T1 --> T2 --> T1 --> T2)
   206         $ aux T1 T2 tps $ t1 $ t2
   207   in aux T1 T2 o rev end
   208 fun is_plain_fun (Const (s, _)) = (s = opt_flag orelse s = non_opt_flag)
   209   | is_plain_fun (Const (@{const_name fun_upd}, _) $ t0 $ _ $ _) =
   210     is_plain_fun t0
   211   | is_plain_fun _ = false
   212 val dest_plain_fun =
   213   let
   214     fun aux (Abs (_, _, Const (s, _))) = (s <> irrelevant, ([], []))
   215       | aux (Const (s, _)) = (s <> non_opt_flag, ([], []))
   216       | aux (Const (@{const_name fun_upd}, _) $ t0 $ t1 $ t2) =
   217         let val (maybe_opt, (ts1, ts2)) = aux t0 in
   218           (maybe_opt, (t1 :: ts1, t2 :: ts2))
   219         end
   220       | aux t = raise TERM ("Nitpick_Model.dest_plain_fun", [t])
   221   in apsnd (pairself rev) o aux end
   222 
   223 fun break_in_two T T1 T2 t =
   224   let
   225     val ps = HOLogic.flat_tupleT_paths T
   226     val cut = length (HOLogic.strip_tupleT T1)
   227     val (ps1, ps2) = pairself HOLogic.flat_tupleT_paths (T1, T2)
   228     val (ts1, ts2) = t |> HOLogic.strip_ptuple ps |> chop cut
   229   in (HOLogic.mk_ptuple ps1 T1 ts1, HOLogic.mk_ptuple ps2 T2 ts2) end
   230 fun pair_up (Type (@{type_name "*"}, [T1', T2']))
   231             (t1 as Const (@{const_name Pair},
   232                           Type (@{type_name fun},
   233                                 [_, Type (@{type_name fun}, [_, T1])]))
   234              $ t11 $ t12) t2 =
   235     if T1 = T1' then HOLogic.mk_prod (t1, t2)
   236     else HOLogic.mk_prod (t11, pair_up T2' t12 t2)
   237   | pair_up _ t1 t2 = HOLogic.mk_prod (t1, t2)
   238 fun multi_pair_up T1 t1 (ts2, ts3) = map2 (pair o pair_up T1 t1) ts2 ts3
   239 
   240 fun typecast_fun (Type (@{type_name fun}, [T1', T2'])) T1 T2 t =
   241     let
   242       fun do_curry T1 T1a T1b T2 t =
   243         let
   244           val (maybe_opt, tsp) = dest_plain_fun t
   245           val tps =
   246             tsp |>> map (break_in_two T1 T1a T1b)
   247                 |> uncurry (map2 (fn (t1a, t1b) => fn t2 => (t1a, (t1b, t2))))
   248                 |> AList.coalesce (op =)
   249                 |> map (apsnd (make_plain_fun maybe_opt T1b T2))
   250         in make_plain_fun maybe_opt T1a (T1b --> T2) tps end
   251       and do_uncurry T1 T2 t =
   252         let
   253           val (maybe_opt, tsp) = dest_plain_fun t
   254           val tps =
   255             tsp |> op ~~
   256                 |> maps (fn (t1, t2) =>
   257                             multi_pair_up T1 t1 (snd (dest_plain_fun t2)))
   258         in make_plain_fun maybe_opt T1 T2 tps end
   259       and do_arrow T1' T2' _ _ (Const (s, _)) = Const (s, T1' --> T2')
   260         | do_arrow T1' T2' T1 T2
   261                    (Const (@{const_name fun_upd}, _) $ t0 $ t1 $ t2) =
   262           Const (@{const_name fun_upd},
   263                  (T1' --> T2') --> T1' --> T2' --> T1' --> T2')
   264           $ do_arrow T1' T2' T1 T2 t0 $ do_term T1' T1 t1 $ do_term T2' T2 t2
   265         | do_arrow _ _ _ _ t =
   266           raise TERM ("Nitpick_Model.typecast_fun.do_arrow", [t])
   267       and do_fun T1' T2' T1 T2 t =
   268         case factor_out_types T1' T1 of
   269           ((_, NONE), (_, NONE)) => t |> do_arrow T1' T2' T1 T2
   270         | ((_, NONE), (T1a, SOME T1b)) =>
   271           t |> do_curry T1 T1a T1b T2 |> do_arrow T1' T2' T1a (T1b --> T2)
   272         | ((T1a', SOME T1b'), (_, NONE)) =>
   273           t |> do_arrow T1a' (T1b' --> T2') T1 T2 |> do_uncurry T1' T2'
   274         | _ => raise TYPE ("Nitpick_Model.typecast_fun.do_fun", [T1, T1'], [])
   275       and do_term (Type (@{type_name fun}, [T1', T2']))
   276                   (Type (@{type_name fun}, [T1, T2])) t =
   277           do_fun T1' T2' T1 T2 t
   278         | do_term (T' as Type (@{type_name "*"}, Ts' as [T1', T2']))
   279                   (Type (@{type_name "*"}, [T1, T2]))
   280                   (Const (@{const_name Pair}, _) $ t1 $ t2) =
   281           Const (@{const_name Pair}, Ts' ---> T')
   282           $ do_term T1' T1 t1 $ do_term T2' T2 t2
   283         | do_term T' T t =
   284           if T = T' then t
   285           else raise TYPE ("Nitpick_Model.typecast_fun.do_term", [T, T'], [])
   286     in if T1' = T1 andalso T2' = T2 then t else do_fun T1' T2' T1 T2 t end
   287   | typecast_fun T' _ _ _ =
   288     raise TYPE ("Nitpick_Model.typecast_fun", [T'], [])
   289 
   290 fun truth_const_sort_key @{const True} = "0"
   291   | truth_const_sort_key @{const False} = "2"
   292   | truth_const_sort_key _ = "1"
   293 
   294 fun mk_tuple (Type (@{type_name "*"}, [T1, T2])) ts =
   295     HOLogic.mk_prod (mk_tuple T1 ts,
   296         mk_tuple T2 (List.drop (ts, length (HOLogic.flatten_tupleT T1))))
   297   | mk_tuple _ (t :: _) = t
   298   | mk_tuple T [] = raise TYPE ("Nitpick_Model.mk_tuple", [T], [])
   299 
   300 fun varified_type_match thy (candid_T, pat_T) =
   301   strict_type_match thy (candid_T, Logic.varifyT_global pat_T)
   302 
   303 fun all_values_of_type pool wacky_names (scope as {card_assigns, ...} : scope)
   304                        sel_names rel_table bounds card T =
   305   let
   306     val card = if card = 0 then card_of_type card_assigns T else card
   307     fun nth_value_of_type n =
   308       let
   309         fun term unfold =
   310           reconstruct_term unfold pool wacky_names scope sel_names rel_table
   311                            bounds T T (Atom (card, 0)) [[n]]
   312       in
   313         case term false of
   314           t as Const (s, _) =>
   315           if String.isPrefix cyclic_const_prefix s then
   316             HOLogic.mk_eq (t, term true)
   317           else
   318             t
   319         | t => t
   320       end
   321   in index_seq 0 card |> map nth_value_of_type |> sort nice_term_ord end
   322 and reconstruct_term unfold pool (wacky_names as ((maybe_name, abs_name), _))
   323         (scope as {hol_ctxt as {ctxt, thy, stds, ...}, binarize, card_assigns,
   324                    bits, datatypes, ofs, ...}) sel_names rel_table bounds =
   325   let
   326     val for_auto = (maybe_name = "")
   327     fun value_of_bits jss =
   328       let
   329         val j0 = offset_of_type ofs @{typ unsigned_bit}
   330         val js = map (Integer.add (~ j0) o the_single) jss
   331       in
   332         fold (fn j => Integer.add (reasonable_power 2 j |> j = bits ? op ~))
   333              js 0
   334       end
   335     val all_values =
   336       all_values_of_type pool wacky_names scope sel_names rel_table bounds 0
   337     fun postprocess_term (Type (@{type_name fun}, _)) = I
   338       | postprocess_term T =
   339         if null (Data.get thy) then
   340           I
   341         else case AList.lookup (varified_type_match thy) (Data.get thy) T of
   342           SOME postproc => postproc ctxt maybe_name all_values T
   343         | NONE => I
   344     fun postprocess_subterms Ts (t1 $ t2) =
   345         let val t = postprocess_subterms Ts t1 $ postprocess_subterms Ts t2 in
   346           postprocess_term (fastype_of1 (Ts, t)) t
   347         end
   348       | postprocess_subterms Ts (Abs (s, T, t')) =
   349         Abs (s, T, postprocess_subterms (T :: Ts) t')
   350       | postprocess_subterms Ts t = postprocess_term (fastype_of1 (Ts, t)) t
   351     fun make_set maybe_opt T1 T2 tps =
   352       let
   353         val empty_const = Const (@{const_abbrev Set.empty}, T1 --> T2)
   354         val insert_const = Const (@{const_name insert},
   355                                   T1 --> (T1 --> T2) --> T1 --> T2)
   356         fun aux [] =
   357             if maybe_opt andalso not (is_complete_type datatypes false T1) then
   358               insert_const $ Const (unrep, T1) $ empty_const
   359             else
   360               empty_const
   361           | aux ((t1, t2) :: zs) =
   362             aux zs
   363             |> t2 <> @{const False}
   364                ? curry (op $)
   365                        (insert_const
   366                         $ (t1 |> t2 <> @{const True}
   367                                  ? curry (op $)
   368                                          (Const (maybe_name, T1 --> T1))))
   369       in
   370         if forall (fn (_, t) => t <> @{const True} andalso t <> @{const False})
   371                   tps then
   372           Const (unknown, T1 --> T2)
   373         else
   374           aux tps
   375       end
   376     fun make_map maybe_opt T1 T2 T2' =
   377       let
   378         val update_const = Const (@{const_name fun_upd},
   379                                   (T1 --> T2) --> T1 --> T2 --> T1 --> T2)
   380         fun aux' [] = Const (@{const_abbrev Map.empty}, T1 --> T2)
   381           | aux' ((t1, t2) :: tps) =
   382             (case t2 of
   383                Const (@{const_name None}, _) => aux' tps
   384              | _ => update_const $ aux' tps $ t1 $ t2)
   385         fun aux tps =
   386           if maybe_opt andalso not (is_complete_type datatypes false T1) then
   387             update_const $ aux' tps $ Const (unrep, T1)
   388             $ (Const (@{const_name Some}, T2' --> T2) $ Const (unknown, T2'))
   389           else
   390             aux' tps
   391       in aux end
   392     fun polish_funs Ts t =
   393       (case fastype_of1 (Ts, t) of
   394          Type (@{type_name fun}, [T1, T2]) =>
   395          if is_plain_fun t then
   396            case T2 of
   397              @{typ bool} =>
   398              let
   399                val (maybe_opt, ts_pair) =
   400                  dest_plain_fun t ||> pairself (map (polish_funs Ts))
   401              in
   402                make_set maybe_opt T1 T2
   403                         (sort_wrt (truth_const_sort_key o snd) (op ~~ ts_pair))
   404              end
   405            | Type (@{type_name option}, [T2']) =>
   406              let
   407                val (maybe_opt, ts_pair) =
   408                  dest_plain_fun t ||> pairself (map (polish_funs Ts))
   409              in make_map maybe_opt T1 T2 T2' (rev (op ~~ ts_pair)) end
   410            | _ => raise SAME ()
   411          else
   412            raise SAME ()
   413        | _ => raise SAME ())
   414       handle SAME () =>
   415              case t of
   416                (t1 as Const (@{const_name fun_upd}, _) $ t11 $ _)
   417                $ (t2 as Const (s, _)) =>
   418                if s = unknown then polish_funs Ts t11
   419                else polish_funs Ts t1 $ polish_funs Ts t2
   420              | t1 $ t2 => polish_funs Ts t1 $ polish_funs Ts t2
   421              | Abs (s, T, t') => Abs (s, T, polish_funs (T :: Ts) t')
   422              | Const (s, Type (@{type_name fun}, [T1, T2])) =>
   423                if s = opt_flag orelse s = non_opt_flag then
   424                  Abs ("x", T1,
   425                       Const (if is_complete_type datatypes false T1 then
   426                                irrelevant
   427                              else
   428                                unknown, T2))
   429                else
   430                  t
   431              | t => t
   432     fun make_fun maybe_opt T1 T2 T' ts1 ts2 =
   433       ts1 ~~ ts2 |> sort (nice_term_ord o pairself fst)
   434                  |> make_plain_fun maybe_opt T1 T2
   435                  |> unarize_unbox_etc_term
   436                  |> typecast_fun (uniterize_unarize_unbox_etc_type T')
   437                                  (uniterize_unarize_unbox_etc_type T1)
   438                                  (uniterize_unarize_unbox_etc_type T2)
   439     fun term_for_atom seen (T as Type (@{type_name fun}, [T1, T2])) T' j _ =
   440         let
   441           val k1 = card_of_type card_assigns T1
   442           val k2 = card_of_type card_assigns T2
   443         in
   444           term_for_rep true seen T T' (Vect (k1, Atom (k2, 0)))
   445                        [nth_combination (replicate k1 (k2, 0)) j]
   446           handle General.Subscript =>
   447                  raise ARG ("Nitpick_Model.reconstruct_term.term_for_atom",
   448                             signed_string_of_int j ^ " for " ^
   449                             string_for_rep (Vect (k1, Atom (k2, 0))))
   450         end
   451       | term_for_atom seen (Type (@{type_name "*"}, [T1, T2])) _ j k =
   452         let
   453           val k1 = card_of_type card_assigns T1
   454           val k2 = k div k1
   455         in
   456           list_comb (HOLogic.pair_const T1 T2,
   457                      map3 (fn T => term_for_atom seen T T) [T1, T2]
   458                           [j div k2, j mod k2] [k1, k2]) (* ### k2 or k1? FIXME *)
   459         end
   460       | term_for_atom seen @{typ prop} _ j k =
   461         HOLogic.mk_Trueprop (term_for_atom seen bool_T bool_T j k)
   462       | term_for_atom _ @{typ bool} _ j _ =
   463         if j = 0 then @{const False} else @{const True}
   464       | term_for_atom _ @{typ unit} _ _ _ = @{const Unity}
   465       | term_for_atom seen T _ j k =
   466         if T = nat_T andalso is_standard_datatype thy stds nat_T then
   467           HOLogic.mk_number nat_T j
   468         else if T = int_T then
   469           HOLogic.mk_number int_T (int_for_atom (k, 0) j)
   470         else if is_fp_iterator_type T then
   471           HOLogic.mk_number nat_T (k - j - 1)
   472         else if T = @{typ bisim_iterator} then
   473           HOLogic.mk_number nat_T j
   474         else case datatype_spec datatypes T of
   475           NONE => nth_atom pool for_auto T j k
   476         | SOME {deep = false, ...} => nth_atom pool for_auto T j k
   477         | SOME {co, standard, constrs, ...} =>
   478           let
   479             fun tuples_for_const (s, T) =
   480               tuple_list_for_name rel_table bounds (ConstName (s, T, Any))
   481             fun cyclic_atom () =
   482               nth_atom pool for_auto (Type (cyclic_type_name, [])) j k
   483             fun cyclic_var () = Var ((nth_atom_name pool "" T j k, 0), T)
   484 
   485             val discr_jsss = map (tuples_for_const o discr_for_constr o #const)
   486                                  constrs
   487             val real_j = j + offset_of_type ofs T
   488             val constr_x as (constr_s, constr_T) =
   489               get_first (fn (jss, {const, ...}) =>
   490                             if member (op =) jss [real_j] then SOME const
   491                             else NONE)
   492                         (discr_jsss ~~ constrs) |> the
   493             val arg_Ts = curried_binder_types constr_T
   494             val sel_xs =
   495               map (binarized_and_boxed_nth_sel_for_constr hol_ctxt binarize
   496                                                           constr_x)
   497                   (index_seq 0 (length arg_Ts))
   498             val sel_Rs =
   499               map (fn x => get_first
   500                                (fn ConstName (s', T', R) =>
   501                                    if (s', T') = x then SOME R else NONE
   502                                  | u => raise NUT ("Nitpick_Model.reconstruct_\
   503                                                    \term.term_for_atom", [u]))
   504                                sel_names |> the) sel_xs
   505             val arg_Rs = map (snd o dest_Func) sel_Rs
   506             val sel_jsss = map tuples_for_const sel_xs
   507             val arg_jsss =
   508               map (map_filter (fn js => if hd js = real_j then SOME (tl js)
   509                                         else NONE)) sel_jsss
   510             val uncur_arg_Ts = binder_types constr_T
   511             val maybe_cyclic = co orelse not standard
   512           in
   513             if maybe_cyclic andalso not (null seen) andalso
   514                member (op =) (seen |> unfold ? (fst o split_last)) (T, j) then
   515               cyclic_var ()
   516             else if constr_s = @{const_name Word} then
   517               HOLogic.mk_number
   518                   (if T = @{typ "unsigned_bit word"} then nat_T else int_T)
   519                   (value_of_bits (the_single arg_jsss))
   520             else
   521               let
   522                 val seen = seen |> maybe_cyclic ? cons (T, j)
   523                 val ts =
   524                   if length arg_Ts = 0 then
   525                     []
   526                   else
   527                     map3 (fn Ts =>
   528                              term_for_rep (constr_s <> @{const_name FinFun})
   529                                           seen Ts Ts) arg_Ts arg_Rs arg_jsss
   530                     |> mk_tuple (HOLogic.mk_tupleT uncur_arg_Ts)
   531                     |> dest_n_tuple (length uncur_arg_Ts)
   532                 val t =
   533                   if constr_s = @{const_name Abs_Frac} then
   534                     case ts of
   535                       [Const (@{const_name Pair}, _) $ t1 $ t2] =>
   536                       frac_from_term_pair (body_type T) t1 t2
   537                     | _ => raise TERM ("Nitpick_Model.reconstruct_term.\
   538                                        \term_for_atom (Abs_Frac)", ts)
   539                   else if not for_auto andalso
   540                           (is_abs_fun thy constr_x orelse
   541                            constr_s = @{const_name Quot}) then
   542                     Const (abs_name, constr_T) $ the_single ts
   543                   else
   544                     list_comb (Const constr_x, ts)
   545               in
   546                 if maybe_cyclic then
   547                   let val var = cyclic_var () in
   548                     if unfold andalso not standard andalso
   549                        length seen = 1 andalso
   550                        exists_subterm (fn Const (s, _) =>
   551                                           String.isPrefix cyclic_const_prefix s
   552                                         | t' => t' = var) t then
   553                       subst_atomic [(var, cyclic_atom ())] t
   554                     else if exists_subterm (curry (op =) var) t then
   555                       if co then
   556                         Const (@{const_name The}, (T --> bool_T) --> T)
   557                         $ Abs (cyclic_co_val_name, T,
   558                                Const (@{const_name "op ="}, T --> T --> bool_T)
   559                                $ Bound 0 $ abstract_over (var, t))
   560                       else
   561                         cyclic_atom ()
   562                     else
   563                       t
   564                   end
   565                 else
   566                   t
   567               end
   568           end
   569     and term_for_vect seen k R T1 T2 T' js =
   570       make_fun true T1 T2 T'
   571                (map (fn j => term_for_atom seen T1 T1 j k) (index_seq 0 k))
   572                (map (term_for_rep true seen T2 T2 R o single)
   573                     (batch_list (arity_of_rep R) js))
   574     and term_for_rep _ seen T T' Unit [[]] = term_for_atom seen T T' 0 1
   575       | term_for_rep _ seen T T' (R as Atom (k, j0)) [[j]] =
   576         if j >= j0 andalso j < j0 + k then term_for_atom seen T T' (j - j0) k
   577         else raise REP ("Nitpick_Model.reconstruct_term.term_for_rep", [R])
   578       | term_for_rep _ seen (Type (@{type_name "*"}, [T1, T2])) _
   579                      (Struct [R1, R2]) [js] =
   580         let
   581           val arity1 = arity_of_rep R1
   582           val (js1, js2) = chop arity1 js
   583         in
   584           list_comb (HOLogic.pair_const T1 T2,
   585                      map3 (fn T => term_for_rep true seen T T) [T1, T2] [R1, R2]
   586                           [[js1], [js2]])
   587         end
   588       | term_for_rep _ seen (Type (@{type_name fun}, [T1, T2])) T'
   589                      (Vect (k, R')) [js] =
   590         term_for_vect seen k R' T1 T2 T' js
   591       | term_for_rep _ seen (Type (@{type_name fun}, [T1, T2])) T'
   592                      (Func (R1, Formula Neut)) jss =
   593         let
   594           val jss1 = all_combinations_for_rep R1
   595           val ts1 = map (term_for_rep true seen T1 T1 R1 o single) jss1
   596           val ts2 =
   597             map (fn js => term_for_rep true seen T2 T2 (Atom (2, 0))
   598                                        [[int_from_bool (member (op =) jss js)]])
   599                 jss1
   600         in make_fun false T1 T2 T' ts1 ts2 end
   601       | term_for_rep maybe_opt seen (Type (@{type_name fun}, [T1, T2])) T'
   602                      (Func (R1, R2)) jss =
   603         let
   604           val arity1 = arity_of_rep R1
   605           val jss1 = all_combinations_for_rep R1
   606           val ts1 = map (term_for_rep false seen T1 T1 R1 o single) jss1
   607           val grouped_jss2 = AList.group (op =) (map (chop arity1) jss)
   608           val ts2 = map (term_for_rep false seen T2 T2 R2 o the_default []
   609                          o AList.lookup (op =) grouped_jss2) jss1
   610         in make_fun maybe_opt T1 T2 T' ts1 ts2 end
   611       | term_for_rep _ seen T T' (Opt R) jss =
   612         if null jss then Const (unknown, T)
   613         else term_for_rep true seen T T' R jss
   614       | term_for_rep _ _ T _ R jss =
   615         raise ARG ("Nitpick_Model.reconstruct_term.term_for_rep",
   616                    Refute.string_of_typ T ^ " " ^ string_for_rep R ^ " " ^
   617                    string_of_int (length jss))
   618   in
   619     postprocess_subterms [] o polish_funs [] o unarize_unbox_etc_term
   620     oooo term_for_rep true []
   621   end
   622 
   623 (** Constant postprocessing **)
   624 
   625 fun dest_n_tuple_type 1 T = [T]
   626   | dest_n_tuple_type n (Type (_, [T1, T2])) =
   627     T1 :: dest_n_tuple_type (n - 1) T2
   628   | dest_n_tuple_type _ T =
   629     raise TYPE ("Nitpick_Model.dest_n_tuple_type", [T], [])
   630 
   631 fun const_format thy def_table (x as (s, T)) =
   632   if String.isPrefix unrolled_prefix s then
   633     const_format thy def_table (original_name s, range_type T)
   634   else if String.isPrefix skolem_prefix s then
   635     let
   636       val k = unprefix skolem_prefix s
   637               |> strip_first_name_sep |> fst |> space_explode "@"
   638               |> hd |> Int.fromString |> the
   639     in [k, num_binder_types T - k] end
   640   else if original_name s <> s then
   641     [num_binder_types T]
   642   else case def_of_const thy def_table x of
   643     SOME t' => if fixpoint_kind_of_rhs t' <> NoFp then
   644                  let val k = length (strip_abs_vars t') in
   645                    [k, num_binder_types T - k]
   646                  end
   647                else
   648                  [num_binder_types T]
   649   | NONE => [num_binder_types T]
   650 fun intersect_formats _ [] = []
   651   | intersect_formats [] _ = []
   652   | intersect_formats ks1 ks2 =
   653     let val ((ks1', k1), (ks2', k2)) = pairself split_last (ks1, ks2) in
   654       intersect_formats (ks1' @ (if k1 > k2 then [k1 - k2] else []))
   655                         (ks2' @ (if k2 > k1 then [k2 - k1] else [])) @
   656       [Int.min (k1, k2)]
   657     end
   658 
   659 fun lookup_format thy def_table formats t =
   660   case AList.lookup (fn (SOME x, SOME y) =>
   661                         (term_match thy) (x, y) | _ => false)
   662                     formats (SOME t) of
   663     SOME format => format
   664   | NONE => let val format = the (AList.lookup (op =) formats NONE) in
   665               case t of
   666                 Const x => intersect_formats format
   667                                              (const_format thy def_table x)
   668               | _ => format
   669             end
   670 
   671 fun format_type default_format format T =
   672   let
   673     val T = uniterize_unarize_unbox_etc_type T
   674     val format = format |> filter (curry (op <) 0)
   675   in
   676     if forall (curry (op =) 1) format then
   677       T
   678     else
   679       let
   680         val (binder_Ts, body_T) = strip_type T
   681         val batched =
   682           binder_Ts
   683           |> map (format_type default_format default_format)
   684           |> rev |> chunk_list_unevenly (rev format)
   685           |> map (HOLogic.mk_tupleT o rev)
   686       in List.foldl (op -->) body_T batched end
   687   end
   688 fun format_term_type thy def_table formats t =
   689   format_type (the (AList.lookup (op =) formats NONE))
   690               (lookup_format thy def_table formats t) (fastype_of t)
   691 
   692 fun repair_special_format js m format =
   693   m - 1 downto 0 |> chunk_list_unevenly (rev format)
   694                  |> map (rev o filter_out (member (op =) js))
   695                  |> filter_out null |> map length |> rev
   696 
   697 fun user_friendly_const ({thy, evals, def_table, skolems, special_funs, ...}
   698                          : hol_context) (base_name, step_name) formats =
   699   let
   700     val default_format = the (AList.lookup (op =) formats NONE)
   701     fun do_const (x as (s, T)) =
   702       (if String.isPrefix special_prefix s then
   703          let
   704            val do_term = map_aterms (fn Const x => fst (do_const x) | t' => t')
   705            val (x' as (_, T'), js, ts) =
   706              AList.find (op =) (!special_funs) (s, unarize_unbox_etc_type T)
   707              |> the_single
   708            val max_j = List.last js
   709            val Ts = List.take (binder_types T', max_j + 1)
   710            val missing_js = filter_out (member (op =) js) (0 upto max_j)
   711            val missing_Ts = filter_indices missing_js Ts
   712            fun nth_missing_var n =
   713              ((arg_var_prefix ^ nat_subscript (n + 1), 0), nth missing_Ts n)
   714            val missing_vars = map nth_missing_var (0 upto length missing_js - 1)
   715            val vars = special_bounds ts @ missing_vars
   716            val ts' =
   717              map (fn j =>
   718                      case AList.lookup (op =) (js ~~ ts) j of
   719                        SOME t => do_term t
   720                      | NONE =>
   721                        Var (nth missing_vars
   722                                 (find_index (curry (op =) j) missing_js)))
   723                  (0 upto max_j)
   724            val t = do_const x' |> fst
   725            val format =
   726              case AList.lookup (fn (SOME t1, SOME t2) => term_match thy (t1, t2)
   727                                  | _ => false) formats (SOME t) of
   728                SOME format =>
   729                repair_special_format js (num_binder_types T') format
   730              | NONE =>
   731                const_format thy def_table x'
   732                |> repair_special_format js (num_binder_types T')
   733                |> intersect_formats default_format
   734          in
   735            (list_comb (t, ts') |> fold_rev abs_var vars,
   736             format_type default_format format T)
   737          end
   738        else if String.isPrefix uncurry_prefix s then
   739          let
   740            val (ss, s') = unprefix uncurry_prefix s
   741                           |> strip_first_name_sep |>> space_explode "@"
   742          in
   743            if String.isPrefix step_prefix s' then
   744              do_const (s', T)
   745            else
   746              let
   747                val k = the (Int.fromString (hd ss))
   748                val j = the (Int.fromString (List.last ss))
   749                val (before_Ts, (tuple_T, rest_T)) =
   750                  strip_n_binders j T ||> (strip_n_binders 1 #>> hd)
   751                val T' = before_Ts ---> dest_n_tuple_type k tuple_T ---> rest_T
   752              in do_const (s', T') end
   753          end
   754        else if String.isPrefix unrolled_prefix s then
   755          let val t = Const (original_name s, range_type T) in
   756            (lambda (Free (iter_var_prefix, nat_T)) t,
   757             format_type default_format
   758                         (lookup_format thy def_table formats t) T)
   759          end
   760        else if String.isPrefix base_prefix s then
   761          (Const (base_name, T --> T) $ Const (unprefix base_prefix s, T),
   762           format_type default_format default_format T)
   763        else if String.isPrefix step_prefix s then
   764          (Const (step_name, T --> T) $ Const (unprefix step_prefix s, T),
   765           format_type default_format default_format T)
   766        else if String.isPrefix quot_normal_prefix s then
   767          let val t = Const (nitpick_prefix ^ "normalize quotient type", T) in
   768            (t, format_term_type thy def_table formats t)
   769          end
   770        else if String.isPrefix skolem_prefix s then
   771          let
   772            val ss = the (AList.lookup (op =) (!skolems) s)
   773            val (Ts, Ts') = chop (length ss) (binder_types T)
   774            val frees = map Free (ss ~~ Ts)
   775            val s' = original_name s
   776          in
   777            (fold lambda frees (Const (s', Ts' ---> T)),
   778             format_type default_format
   779                         (lookup_format thy def_table formats (Const x)) T)
   780          end
   781        else if String.isPrefix eval_prefix s then
   782          let
   783            val t = nth evals (the (Int.fromString (unprefix eval_prefix s)))
   784          in (t, format_term_type thy def_table formats t) end
   785        else if s = @{const_name undefined_fast_The} then
   786          (Const (nitpick_prefix ^ "The fallback", T),
   787           format_type default_format
   788                       (lookup_format thy def_table formats
   789                            (Const (@{const_name The}, (T --> bool_T) --> T))) T)
   790        else if s = @{const_name undefined_fast_Eps} then
   791          (Const (nitpick_prefix ^ "Eps fallback", T),
   792           format_type default_format
   793                       (lookup_format thy def_table formats
   794                            (Const (@{const_name Eps}, (T --> bool_T) --> T))) T)
   795        else
   796          let val t = Const (original_name s, T) in
   797            (t, format_term_type thy def_table formats t)
   798          end)
   799       |>> map_types uniterize_unarize_unbox_etc_type
   800       |>> shorten_names_in_term |>> Term.map_abs_vars shortest_name
   801   in do_const end
   802 
   803 fun assign_operator_for_const (s, T) =
   804   if String.isPrefix ubfp_prefix s then
   805     if is_fun_type T then "\<subseteq>" else "\<le>"
   806   else if String.isPrefix lbfp_prefix s then
   807     if is_fun_type T then "\<supseteq>" else "\<ge>"
   808   else if original_name s <> s then
   809     assign_operator_for_const (strip_first_name_sep s |> snd, T)
   810   else
   811     "="
   812 
   813 (** Model reconstruction **)
   814 
   815 fun term_for_name pool scope sel_names rel_table bounds name =
   816   let val T = type_of name in
   817     tuple_list_for_name rel_table bounds name
   818     |> reconstruct_term false pool (("", ""), ("", "")) scope sel_names
   819                         rel_table bounds T T (rep_of name)
   820   end
   821 
   822 fun unfold_outer_the_binders (t as Const (@{const_name The}, _)
   823                                    $ Abs (s, T, Const (@{const_name "op ="}, _)
   824                                                 $ Bound 0 $ t')) =
   825     betapply (Abs (s, T, t'), t) |> unfold_outer_the_binders
   826   | unfold_outer_the_binders t = t
   827 fun bisimilar_values _ 0 _ = true
   828   | bisimilar_values coTs max_depth (t1, t2) =
   829     let val T = fastype_of t1 in
   830       if exists_subtype (member (op =) coTs) T then
   831         let
   832           val ((head1, args1), (head2, args2)) =
   833             pairself (strip_comb o unfold_outer_the_binders) (t1, t2)
   834           val max_depth = max_depth - (if member (op =) coTs T then 1 else 0)
   835         in
   836           head1 = head2 andalso
   837           forall (bisimilar_values coTs max_depth) (args1 ~~ args2)
   838         end
   839       else
   840         t1 = t2
   841     end
   842 
   843 fun reconstruct_hol_model {show_skolems, show_datatypes, show_consts}
   844         ({hol_ctxt = {thy, ctxt, max_bisim_depth, boxes, stds, wfs, user_axioms,
   845                       debug, binary_ints, destroy_constrs, specialize,
   846                       skolemize, star_linear_preds, uncurry, fast_descrs,
   847                       tac_timeout, evals, case_names, def_table, nondef_table,
   848                       user_nondefs, simp_table, psimp_table, choice_spec_table,
   849                       intro_table, ground_thm_table, ersatz_table, skolems,
   850                       special_funs, unrolled_preds, wf_cache, constr_cache},
   851          binarize, card_assigns, bits, bisim_depth, datatypes, ofs} : scope)
   852         formats all_frees free_names sel_names nonsel_names rel_table bounds =
   853   let
   854     val pool = Unsynchronized.ref []
   855     val (wacky_names as (_, base_step_names), ctxt) =
   856       add_wacky_syntax ctxt
   857     val hol_ctxt =
   858       {thy = thy, ctxt = ctxt, max_bisim_depth = max_bisim_depth, boxes = boxes,
   859        stds = stds, wfs = wfs, user_axioms = user_axioms, debug = debug,
   860        binary_ints = binary_ints, destroy_constrs = destroy_constrs,
   861        specialize = specialize, skolemize = skolemize,
   862        star_linear_preds = star_linear_preds, uncurry = uncurry,
   863        fast_descrs = fast_descrs, tac_timeout = tac_timeout, evals = evals,
   864        case_names = case_names, def_table = def_table,
   865        nondef_table = nondef_table, user_nondefs = user_nondefs,
   866        simp_table = simp_table, psimp_table = psimp_table,
   867        choice_spec_table = choice_spec_table, intro_table = intro_table,
   868        ground_thm_table = ground_thm_table, ersatz_table = ersatz_table,
   869        skolems = skolems, special_funs = special_funs,
   870        unrolled_preds = unrolled_preds, wf_cache = wf_cache,
   871        constr_cache = constr_cache}
   872     val scope = {hol_ctxt = hol_ctxt, binarize = binarize,
   873                  card_assigns = card_assigns, bits = bits,
   874                  bisim_depth = bisim_depth, datatypes = datatypes, ofs = ofs}
   875     fun term_for_rep unfold =
   876       reconstruct_term unfold pool wacky_names scope sel_names rel_table bounds
   877     fun nth_value_of_type card T n =
   878       let
   879         fun aux unfold = term_for_rep unfold T T (Atom (card, 0)) [[n]]
   880       in
   881         case aux false of
   882           t as Const (s, _) =>
   883           if String.isPrefix cyclic_const_prefix s then
   884             HOLogic.mk_eq (t, aux true)
   885           else
   886             t
   887         | t => t
   888       end
   889     val all_values =
   890       all_values_of_type pool wacky_names scope sel_names rel_table bounds
   891     fun is_codatatype_wellformed (cos : dtype_spec list)
   892                                  ({typ, card, ...} : dtype_spec) =
   893       let
   894         val ts = all_values card typ
   895         val max_depth = Integer.sum (map #card cos)
   896       in
   897         forall (not o bisimilar_values (map #typ cos) max_depth)
   898                (all_distinct_unordered_pairs_of ts)
   899       end
   900     fun pretty_for_assign name =
   901       let
   902         val (oper, (t1, T'), T) =
   903           case name of
   904             FreeName (s, T, _) =>
   905             let val t = Free (s, uniterize_unarize_unbox_etc_type T) in
   906               ("=", (t, format_term_type thy def_table formats t), T)
   907             end
   908           | ConstName (s, T, _) =>
   909             (assign_operator_for_const (s, T),
   910              user_friendly_const hol_ctxt base_step_names formats (s, T), T)
   911           | _ => raise NUT ("Nitpick_Model.reconstruct_hol_model.\
   912                             \pretty_for_assign", [name])
   913         val t2 = if rep_of name = Any then
   914                    Const (@{const_name undefined}, T')
   915                  else
   916                    tuple_list_for_name rel_table bounds name
   917                    |> term_for_rep false T T' (rep_of name)
   918       in
   919         Pretty.block (Pretty.breaks
   920             [setmp_show_all_types (Syntax.pretty_term ctxt) t1,
   921              Pretty.str oper, Syntax.pretty_term ctxt t2])
   922       end
   923     fun pretty_for_datatype ({typ, card, complete, ...} : dtype_spec) =
   924       Pretty.block (Pretty.breaks
   925           (Syntax.pretty_typ ctxt (uniterize_unarize_unbox_etc_type typ) ::
   926            (case typ of
   927               Type (@{type_name fin_fun}, _) => [Pretty.str "[finite]"]
   928             | Type (@{type_name fun_box}, _) => [Pretty.str "[boxed]"]
   929             | Type (@{type_name pair_box}, _) => [Pretty.str "[boxed]"]
   930             | _ => []) @
   931            [Pretty.str "=",
   932             Pretty.enum "," "{" "}"
   933                 (map (Syntax.pretty_term ctxt) (all_values card typ) @
   934                  (if fun_from_pair complete false then []
   935                   else [Pretty.str unrep]))]))
   936     fun integer_datatype T =
   937       [{typ = T, card = card_of_type card_assigns T, co = false,
   938         standard = true, complete = (false, false), concrete = (true, true),
   939         deep = true, constrs = []}]
   940       handle TYPE ("Nitpick_HOL.card_of_type", _, _) => []
   941     val (codatatypes, datatypes) =
   942       datatypes |> filter #deep |> List.partition #co
   943                 ||> append (integer_datatype int_T
   944                             |> is_standard_datatype thy stds nat_T
   945                                ? append (integer_datatype nat_T))
   946     val block_of_datatypes =
   947       if show_datatypes andalso not (null datatypes) then
   948         [Pretty.big_list ("Datatype" ^ plural_s_for_list datatypes ^ ":")
   949                          (map pretty_for_datatype datatypes)]
   950       else
   951         []
   952     val block_of_codatatypes =
   953       if show_datatypes andalso not (null codatatypes) then
   954         [Pretty.big_list ("Codatatype" ^ plural_s_for_list codatatypes ^ ":")
   955                          (map pretty_for_datatype codatatypes)]
   956       else
   957         []
   958     fun block_of_names show title names =
   959       if show andalso not (null names) then
   960         Pretty.str (title ^ plural_s_for_list names ^ ":")
   961         :: map (Pretty.indent indent_size o pretty_for_assign)
   962                (sort_wrt (original_name o nickname_of) names)
   963       else
   964         []
   965     val (skolem_names, nonskolem_nonsel_names) =
   966       List.partition is_skolem_name nonsel_names
   967     val (eval_names, noneval_nonskolem_nonsel_names) =
   968       List.partition (String.isPrefix eval_prefix o nickname_of)
   969                      nonskolem_nonsel_names
   970       ||> filter_out (member (op =) [@{const_name bisim},
   971                                      @{const_name bisim_iterator_max}]
   972                       o nickname_of)
   973     val free_names =
   974       map (fn x as (s, T) =>
   975               case filter (curry (op =) x
   976                        o pairf nickname_of
   977                                (uniterize_unarize_unbox_etc_type o type_of))
   978                        free_names of
   979                 [name] => name
   980               | [] => FreeName (s, T, Any)
   981               | _ => raise TERM ("Nitpick_Model.reconstruct_hol_model",
   982                                  [Const x])) all_frees
   983     val chunks = block_of_names true "Free variable" free_names @
   984                  block_of_names show_skolems "Skolem constant" skolem_names @
   985                  block_of_names true "Evaluated term" eval_names @
   986                  block_of_datatypes @ block_of_codatatypes @
   987                  block_of_names show_consts "Constant"
   988                                 noneval_nonskolem_nonsel_names
   989   in
   990     (Pretty.chunks (if null chunks then [Pretty.str "Empty assignment"]
   991                     else chunks),
   992      bisim_depth >= 0 orelse
   993      forall (is_codatatype_wellformed codatatypes) codatatypes)
   994   end
   995 
   996 fun prove_hol_model (scope as {hol_ctxt = {thy, ctxt, debug, ...},
   997                                card_assigns, ...})
   998                     auto_timeout free_names sel_names rel_table bounds prop =
   999   let
  1000     val pool = Unsynchronized.ref []
  1001     fun free_type_assm (T, k) =
  1002       let
  1003         fun atom j = nth_atom pool true T j k
  1004         fun equation_for_atom j = HOLogic.eq_const T $ Bound 0 $ atom j
  1005         val eqs = map equation_for_atom (index_seq 0 k)
  1006         val compreh_assm =
  1007           Const (@{const_name All}, (T --> bool_T) --> bool_T)
  1008               $ Abs ("x", T, foldl1 HOLogic.mk_disj eqs)
  1009         val distinct_assm = distinctness_formula T (map atom (index_seq 0 k))
  1010       in s_conj (compreh_assm, distinct_assm) end
  1011     fun free_name_assm name =
  1012       HOLogic.mk_eq (Free (nickname_of name, type_of name),
  1013                      term_for_name pool scope sel_names rel_table bounds name)
  1014     val freeT_assms = map free_type_assm (filter (is_TFree o fst) card_assigns)
  1015     val model_assms = map free_name_assm free_names
  1016     val assm = foldr1 s_conj (freeT_assms @ model_assms)
  1017     fun try_out negate =
  1018       let
  1019         val concl = (negate ? curry (op $) @{const Not})
  1020                     (Object_Logic.atomize_term thy prop)
  1021         val prop = HOLogic.mk_Trueprop (HOLogic.mk_imp (assm, concl))
  1022                    |> map_types (map_type_tfree
  1023                                      (fn (s, []) => TFree (s, HOLogic.typeS)
  1024                                        | x => TFree x))
  1025        val _ = if debug then
  1026                  priority ((if negate then "Genuineness" else "Spuriousness") ^
  1027                            " goal: " ^ Syntax.string_of_term ctxt prop ^ ".")
  1028                else
  1029                  ()
  1030         val goal = prop |> cterm_of thy |> Goal.init
  1031       in
  1032         (goal |> SINGLE (DETERM_TIMEOUT auto_timeout
  1033                                         (auto_tac (clasimpset_of ctxt)))
  1034               |> the |> Goal.finish ctxt; true)
  1035         handle THM _ => false
  1036              | TimeLimit.TimeOut => false
  1037       end
  1038   in
  1039     if try_out false then SOME true
  1040     else if try_out true then SOME false
  1041     else NONE
  1042   end
  1043 
  1044 end;