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