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