src/HOL/Tools/Nitpick/nitpick_model.ML
author blanchet
Mon Apr 20 11:23:00 2015 +0200 (2015-04-20)
changeset 60139 9fabfda0643f
parent 59970 e9f73d87d904
child 60193 9274808fa020
permissions -rw-r--r--
declare Nitpick atoms to avoid '??.' prefixes in output
     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   val prove_hol_model :
    43     scope -> Time.time -> nut list -> nut list -> nut NameTable.table
    44     -> Kodkod.raw_bound list -> term -> bool option
    45 end;
    46 
    47 structure Nitpick_Model : NITPICK_MODEL =
    48 struct
    49 
    50 open Nitpick_Util
    51 open Nitpick_HOL
    52 open Nitpick_Scope
    53 open Nitpick_Peephole
    54 open Nitpick_Rep
    55 open Nitpick_Nut
    56 
    57 structure KK = Kodkod
    58 
    59 type params =
    60   {show_types: bool,
    61    show_skolems: bool,
    62    show_consts: bool}
    63 
    64 type term_postprocessor =
    65   Proof.context -> string -> (typ -> term list) -> typ -> term -> term
    66 
    67 structure Data = Generic_Data
    68 (
    69   type T = (typ * term_postprocessor) list
    70   val empty = []
    71   val extend = I
    72   fun merge data = AList.merge (op =) (K true) data
    73 )
    74 
    75 fun xsym s s' () = if print_mode_active Symbol.xsymbolsN then s else s'
    76 
    77 val irrelevant = "_"
    78 val unknown = "?"
    79 val unrep = xsym "\<dots>" "..."
    80 val maybe_mixfix = xsym "_\<^sup>?" "_?"
    81 val base_mixfix = xsym "_\<^bsub>base\<^esub>" "_.base"
    82 val step_mixfix = xsym "_\<^bsub>step\<^esub>" "_.step"
    83 val abs_mixfix = xsym "\<guillemotleft>_\<guillemotright>" "\"_\""
    84 val arg_var_prefix = "x"
    85 val cyclic_co_val_name = xsym "\<omega>" "w"
    86 val cyclic_const_prefix = xsym "\<xi>" "X"
    87 fun cyclic_type_name () = nitpick_prefix ^ cyclic_const_prefix ()
    88 val opt_flag = nitpick_prefix ^ "opt"
    89 val non_opt_flag = nitpick_prefix ^ "non_opt"
    90 
    91 type atom_pool = ((string * int) * int list) list
    92 
    93 fun add_wacky_syntax ctxt =
    94   let
    95     val name_of = fst o dest_Const
    96     val thy = Proof_Context.theory_of ctxt
    97     val (maybe_t, thy) =
    98       Sign.declare_const_global ((@{binding nitpick_maybe}, @{typ "'a => 'a"}),
    99                           Mixfix (maybe_mixfix (), [1000], 1000)) thy
   100     val (abs_t, thy) =
   101       Sign.declare_const_global ((@{binding nitpick_abs}, @{typ "'a => 'b"}),
   102                           Mixfix (abs_mixfix (), [40], 40)) thy
   103     val (base_t, thy) =
   104       Sign.declare_const_global ((@{binding nitpick_base}, @{typ "'a => 'a"}),
   105                           Mixfix (base_mixfix (), [1000], 1000)) thy
   106     val (step_t, thy) =
   107       Sign.declare_const_global ((@{binding nitpick_step}, @{typ "'a => 'a"}),
   108                           Mixfix (step_mixfix (), [1000], 1000)) thy
   109   in
   110     (apply2 (apply2 name_of) ((maybe_t, abs_t), (base_t, step_t)),
   111      Proof_Context.transfer thy ctxt)
   112   end
   113 
   114 (** Term reconstruction **)
   115 
   116 fun nth_atom_number pool T j =
   117   case AList.lookup (op =) (!pool) T of
   118     SOME js =>
   119     (case find_index (curry (op =) j) js of
   120        ~1 => (Unsynchronized.change pool (cons (T, j :: js));
   121               length js + 1)
   122      | n => length js - n)
   123   | NONE => (Unsynchronized.change pool (cons (T, [j])); 1)
   124 
   125 fun atom_suffix s =
   126   nat_subscript
   127   #> (s <> "" andalso Symbol.is_ascii_digit (List.last (raw_explode s)))  (* FIXME Symbol.explode (?) *)
   128      ? prefix "\<^sub>,"
   129 
   130 fun nth_atom_name thy atomss pool prefix T j =
   131   let
   132     val ss = these (triple_lookup (type_match thy) atomss T)
   133     val m = nth_atom_number pool T j
   134   in
   135     if m <= length ss then
   136       nth ss (m - 1)
   137     else case T of
   138       Type (s, _) =>
   139       let val s' = shortest_name s in
   140         prefix ^
   141         (if T = @{typ string} then "s"
   142          else if String.isPrefix "\\" s' then s'
   143          else substring (s', 0, 1)) ^ atom_suffix s m
   144       end
   145     | TFree (s, _) => prefix ^ perhaps (try (unprefix "'")) s ^ atom_suffix s m
   146     | _ => raise TYPE ("Nitpick_Model.nth_atom_name", [T], [])
   147   end
   148 
   149 fun nth_atom thy atomss pool for_auto T j =
   150   if for_auto then
   151     Free (nth_atom_name thy atomss pool (hd (Long_Name.explode nitpick_prefix))
   152                         T j, T)
   153   else
   154     Const (nth_atom_name thy atomss pool "" T j, T)
   155 
   156 fun extract_real_number (Const (@{const_name divide}, _) $ t1 $ t2) =
   157     real (snd (HOLogic.dest_number t1)) / real (snd (HOLogic.dest_number t2))
   158   | extract_real_number t = real (snd (HOLogic.dest_number t))
   159 
   160 fun nice_term_ord (Abs (_, _, t1), Abs (_, _, t2)) = nice_term_ord (t1, t2)
   161   | nice_term_ord tp = Real.compare (apply2 extract_real_number tp)
   162     handle TERM ("dest_number", _) =>
   163            case tp of
   164              (t11 $ t12, t21 $ t22) =>
   165              (case nice_term_ord (t11, t21) of
   166                 EQUAL => nice_term_ord (t12, t22)
   167               | ord => ord)
   168            | _ => Term_Ord.fast_term_ord tp
   169 
   170 fun register_term_postprocessor_generic T postproc =
   171   Data.map (cons (T, postproc))
   172 
   173 (* TODO: Consider morphism. *)
   174 fun register_term_postprocessor T postproc (_ : morphism) =
   175   register_term_postprocessor_generic T postproc
   176 
   177 val register_term_postprocessor_global =
   178   Context.theory_map oo register_term_postprocessor_generic
   179 
   180 fun unregister_term_postprocessor_generic T = Data.map (AList.delete (op =) T)
   181 (* TODO: Consider morphism. *)
   182 
   183 fun unregister_term_postprocessor T (_ : morphism) =
   184   unregister_term_postprocessor_generic T
   185 
   186 val unregister_term_postprocessor_global =
   187   Context.theory_map o unregister_term_postprocessor_generic
   188 
   189 fun tuple_list_for_name rel_table bounds name =
   190   the (AList.lookup (op =) bounds (the_rel rel_table name)) handle NUT _ => [[]]
   191 
   192 fun unarize_unbox_etc_term (Const (@{const_name FunBox}, _) $ t1) =
   193     unarize_unbox_etc_term t1
   194   | unarize_unbox_etc_term
   195         (Const (@{const_name PairBox},
   196                 Type (@{type_name fun}, [T1, Type (@{type_name fun}, [T2, _])]))
   197          $ t1 $ t2) =
   198     let val Ts = map uniterize_unarize_unbox_etc_type [T1, T2] in
   199       Const (@{const_name Pair}, Ts ---> Type (@{type_name prod}, Ts))
   200       $ unarize_unbox_etc_term t1 $ unarize_unbox_etc_term t2
   201     end
   202   | unarize_unbox_etc_term (Const (s, T)) =
   203     Const (s, uniterize_unarize_unbox_etc_type T)
   204   | unarize_unbox_etc_term (t1 $ t2) =
   205     unarize_unbox_etc_term t1 $ unarize_unbox_etc_term t2
   206   | unarize_unbox_etc_term (Free (s, T)) =
   207     Free (s, uniterize_unarize_unbox_etc_type T)
   208   | unarize_unbox_etc_term (Var (x, T)) =
   209     Var (x, uniterize_unarize_unbox_etc_type T)
   210   | unarize_unbox_etc_term (Bound j) = Bound j
   211   | unarize_unbox_etc_term (Abs (s, T, t')) =
   212     Abs (s, uniterize_unarize_unbox_etc_type T, unarize_unbox_etc_term t')
   213 
   214 fun factor_out_types (T1 as Type (@{type_name prod}, [T11, T12]))
   215                      (T2 as Type (@{type_name prod}, [T21, T22])) =
   216     let val (n1, n2) = apply2 num_factors_in_type (T11, T21) in
   217       if n1 = n2 then
   218         let
   219           val ((T11', opt_T12'), (T21', opt_T22')) = factor_out_types T12 T22
   220         in
   221           ((Type (@{type_name prod}, [T11, T11']), opt_T12'),
   222            (Type (@{type_name prod}, [T21, T21']), opt_T22'))
   223         end
   224       else if n1 < n2 then
   225         case factor_out_types T1 T21 of
   226           (p1, (T21', NONE)) => (p1, (T21', SOME T22))
   227         | (p1, (T21', SOME T22')) =>
   228           (p1, (T21', SOME (Type (@{type_name prod}, [T22', T22]))))
   229       else
   230         swap (factor_out_types T2 T1)
   231     end
   232   | factor_out_types (Type (@{type_name prod}, [T11, T12])) T2 =
   233     ((T11, SOME T12), (T2, NONE))
   234   | factor_out_types T1 (Type (@{type_name prod}, [T21, T22])) =
   235     ((T1, NONE), (T21, SOME T22))
   236   | factor_out_types T1 T2 = ((T1, NONE), (T2, NONE))
   237 
   238 (* Term-encoded data structure for holding key-value pairs as well as an "opt"
   239    flag indicating whether the function is approximated. *)
   240 fun make_plain_fun maybe_opt T1 T2 =
   241   let
   242     fun aux T1 T2 [] =
   243         Const (if maybe_opt then opt_flag else non_opt_flag, T1 --> T2)
   244       | aux T1 T2 ((t1, t2) :: tps) =
   245         Const (@{const_name fun_upd}, (T1 --> T2) --> T1 --> T2 --> T1 --> T2)
   246         $ aux T1 T2 tps $ t1 $ t2
   247   in aux T1 T2 o rev end
   248 
   249 fun is_plain_fun (Const (s, _)) = (s = opt_flag orelse s = non_opt_flag)
   250   | is_plain_fun (Const (@{const_name fun_upd}, _) $ t0 $ _ $ _) =
   251     is_plain_fun t0
   252   | is_plain_fun _ = false
   253 val dest_plain_fun =
   254   let
   255     fun aux (Abs (_, _, Const (s, _))) = (s <> irrelevant, ([], []))
   256       | aux (Const (s, _)) = (s <> non_opt_flag, ([], []))
   257       | aux (Const (@{const_name fun_upd}, _) $ t0 $ t1 $ t2) =
   258         let val (maybe_opt, (ts1, ts2)) = aux t0 in
   259           (maybe_opt, (t1 :: ts1, t2 :: ts2))
   260         end
   261       | aux t = raise TERM ("Nitpick_Model.dest_plain_fun", [t])
   262   in apsnd (apply2 rev) o aux end
   263 
   264 fun break_in_two T T1 T2 t =
   265   let
   266     val ps = HOLogic.flat_tupleT_paths T
   267     val cut = length (HOLogic.strip_tupleT T1)
   268     val (ps1, ps2) = apply2 HOLogic.flat_tupleT_paths (T1, T2)
   269     val (ts1, ts2) = t |> HOLogic.strip_ptuple ps |> chop cut
   270   in (HOLogic.mk_ptuple ps1 T1 ts1, HOLogic.mk_ptuple ps2 T2 ts2) end
   271 
   272 fun pair_up (Type (@{type_name prod}, [T1', T2']))
   273             (t1 as Const (@{const_name Pair},
   274                           Type (@{type_name fun},
   275                                 [_, Type (@{type_name fun}, [_, T1])]))
   276              $ t11 $ t12) t2 =
   277     if T1 = T1' then HOLogic.mk_prod (t1, t2)
   278     else HOLogic.mk_prod (t11, pair_up T2' t12 t2)
   279   | pair_up _ t1 t2 = HOLogic.mk_prod (t1, t2)
   280 
   281 fun multi_pair_up T1 t1 (ts2, ts3) = map2 (pair o pair_up T1 t1) ts2 ts3
   282 
   283 fun format_fun T' T1 T2 t =
   284   let
   285     val T1' = pseudo_domain_type T'
   286     val T2' = pseudo_range_type T'
   287     fun do_curry T1 T1a T1b T2 t =
   288       let
   289         val (maybe_opt, tsp) = dest_plain_fun t
   290         val tps =
   291           tsp |>> map (break_in_two T1 T1a T1b)
   292               |> uncurry (map2 (fn (t1a, t1b) => fn t2 => (t1a, (t1b, t2))))
   293               |> AList.coalesce (op =)
   294               |> map (apsnd (make_plain_fun maybe_opt T1b T2))
   295       in make_plain_fun maybe_opt T1a (T1b --> T2) tps end
   296     and do_uncurry T1 T2 t =
   297       let
   298         val (maybe_opt, tsp) = dest_plain_fun t
   299         val tps =
   300           tsp |> op ~~
   301               |> maps (fn (t1, t2) =>
   302                           multi_pair_up T1 t1 (snd (dest_plain_fun t2)))
   303       in make_plain_fun maybe_opt T1 T2 tps end
   304     and do_arrow T1' T2' _ _ (Const (s, _)) = Const (s, T1' --> T2')
   305       | do_arrow T1' T2' T1 T2
   306                  (Const (@{const_name fun_upd}, _) $ t0 $ t1 $ t2) =
   307         Const (@{const_name fun_upd},
   308                (T1' --> T2') --> T1' --> T2' --> T1' --> T2')
   309         $ do_arrow T1' T2' T1 T2 t0 $ do_term T1' T1 t1 $ do_term T2' T2 t2
   310       | do_arrow _ _ _ _ t =
   311         raise TERM ("Nitpick_Model.format_fun.do_arrow", [t])
   312     and do_fun T1' T2' T1 T2 t =
   313       case factor_out_types T1' T1 of
   314         ((_, NONE), (_, NONE)) => t |> do_arrow T1' T2' T1 T2
   315       | ((_, NONE), (T1a, SOME T1b)) =>
   316         t |> do_curry T1 T1a T1b T2 |> do_arrow T1' T2' T1a (T1b --> T2)
   317       | ((T1a', SOME T1b'), (_, NONE)) =>
   318         t |> do_arrow T1a' (T1b' --> T2') T1 T2 |> do_uncurry T1' T2'
   319       | _ => raise TYPE ("Nitpick_Model.format_fun.do_fun", [T1, T1'], [])
   320     and do_term (Type (@{type_name fun}, [T1', T2']))
   321                 (Type (@{type_name fun}, [T1, T2])) t =
   322         do_fun T1' T2' T1 T2 t
   323       | do_term (T' as Type (@{type_name prod}, Ts' as [T1', T2']))
   324                 (Type (@{type_name prod}, [T1, T2]))
   325                 (Const (@{const_name Pair}, _) $ t1 $ t2) =
   326         Const (@{const_name Pair}, Ts' ---> T')
   327         $ do_term T1' T1 t1 $ do_term T2' T2 t2
   328       | do_term T' T t =
   329         if T = T' then t
   330         else raise TYPE ("Nitpick_Model.format_fun.do_term", [T, T'], [])
   331   in if T1' = T1 andalso T2' = T2 then t else do_fun T1' T2' T1 T2 t end
   332 
   333 fun truth_const_sort_key @{const True} = "0"
   334   | truth_const_sort_key @{const False} = "2"
   335   | truth_const_sort_key _ = "1"
   336 
   337 fun mk_tuple (Type (@{type_name prod}, [T1, T2])) ts =
   338     HOLogic.mk_prod (mk_tuple T1 ts,
   339         mk_tuple T2 (List.drop (ts, length (HOLogic.flatten_tupleT T1))))
   340   | mk_tuple _ (t :: _) = t
   341   | mk_tuple T [] = raise TYPE ("Nitpick_Model.mk_tuple", [T], [])
   342 
   343 fun varified_type_match ctxt (candid_T, pat_T) =
   344   let val thy = Proof_Context.theory_of ctxt in
   345     strict_type_match thy (candid_T, varify_type ctxt pat_T)
   346   end
   347 
   348 fun all_values_of_type pool wacky_names (scope as {card_assigns, ...} : scope)
   349                        atomss sel_names rel_table bounds card T =
   350   let
   351     val card = if card = 0 then card_of_type card_assigns T else card
   352     fun nth_value_of_type n =
   353       let
   354         fun term unfold =
   355           reconstruct_term true unfold pool wacky_names scope atomss sel_names
   356                            rel_table bounds T T (Atom (card, 0)) [[n]]
   357       in
   358         case term false of
   359           t as Const (s, _) =>
   360           if String.isPrefix (cyclic_const_prefix ()) s then
   361             HOLogic.mk_eq (t, term true)
   362           else
   363             t
   364         | t => t
   365       end
   366   in index_seq 0 card |> map nth_value_of_type |> sort nice_term_ord end
   367 and reconstruct_term maybe_opt unfold pool
   368         (wacky_names as ((maybe_name, abs_name), _))
   369         (scope as {hol_ctxt as {thy, ctxt, ...}, binarize, card_assigns, bits,
   370                    data_types, ofs, ...})
   371         atomss sel_names rel_table bounds =
   372   let
   373     val for_auto = (maybe_name = "")
   374     fun value_of_bits jss =
   375       let
   376         val j0 = offset_of_type ofs @{typ unsigned_bit}
   377         val js = map (Integer.add (~ j0) o the_single) jss
   378       in
   379         fold (fn j => Integer.add (reasonable_power 2 j |> j = bits ? op ~))
   380              js 0
   381       end
   382     val all_values =
   383       all_values_of_type pool wacky_names scope atomss sel_names rel_table
   384                          bounds 0
   385     fun postprocess_term (Type (@{type_name fun}, _)) = I
   386       | postprocess_term T =
   387         case Data.get (Context.Proof ctxt) of
   388           [] => I
   389         | postprocs =>
   390           case AList.lookup (varified_type_match ctxt) postprocs T of
   391             SOME postproc => postproc ctxt maybe_name all_values T
   392           | NONE => I
   393     fun postprocess_subterms Ts (t1 $ t2) =
   394         let val t = postprocess_subterms Ts t1 $ postprocess_subterms Ts t2 in
   395           postprocess_term (fastype_of1 (Ts, t)) t
   396         end
   397       | postprocess_subterms Ts (Abs (s, T, t')) =
   398         Abs (s, T, postprocess_subterms (T :: Ts) t')
   399       | postprocess_subterms Ts t = postprocess_term (fastype_of1 (Ts, t)) t
   400     fun make_set maybe_opt T tps =
   401       let
   402         val set_T = HOLogic.mk_setT T
   403         val empty_const = Const (@{const_abbrev Set.empty}, set_T)
   404         val insert_const = Const (@{const_name insert}, T --> set_T --> set_T)
   405         fun aux [] =
   406             if maybe_opt andalso not (is_complete_type data_types false T) then
   407               insert_const $ Const (unrep (), T) $ empty_const
   408             else
   409               empty_const
   410           | aux ((t1, t2) :: zs) =
   411             aux zs
   412             |> t2 <> @{const False}
   413                ? curry (op $)
   414                        (insert_const
   415                         $ (t1 |> t2 <> @{const True}
   416                                  ? curry (op $)
   417                                          (Const (maybe_name, T --> T))))
   418       in
   419         if forall (fn (_, t) => t <> @{const True} andalso t <> @{const False})
   420                   tps then
   421           Const (unknown, set_T)
   422         else
   423           aux tps
   424       end
   425     fun make_map maybe_opt T1 T2 T2' =
   426       let
   427         val update_const = Const (@{const_name fun_upd},
   428                                   (T1 --> T2) --> T1 --> T2 --> T1 --> T2)
   429         fun aux' [] = Const (@{const_abbrev Map.empty}, T1 --> T2)
   430           | aux' ((t1, t2) :: tps) =
   431             (case t2 of
   432                Const (@{const_name None}, _) => aux' tps
   433              | _ => update_const $ aux' tps $ t1 $ t2)
   434         fun aux tps =
   435           if maybe_opt andalso not (is_complete_type data_types false T1) then
   436             update_const $ aux' tps $ Const (unrep (), T1)
   437             $ (Const (@{const_name Some}, T2' --> T2) $ Const (unknown, T2'))
   438           else
   439             aux' tps
   440       in aux end
   441     fun polish_funs Ts t =
   442       (case fastype_of1 (Ts, t) of
   443          Type (@{type_name fun}, [T1, T2]) =>
   444          if is_plain_fun t then
   445            case T2 of
   446              Type (@{type_name option}, [T2']) =>
   447              let
   448                val (maybe_opt, ts_pair) =
   449                  dest_plain_fun t ||> apply2 (map (polish_funs Ts))
   450              in make_map maybe_opt T1 T2 T2' (rev (op ~~ ts_pair)) end
   451            | _ => raise SAME ()
   452          else
   453            raise SAME ()
   454        | _ => raise SAME ())
   455       handle SAME () =>
   456              case t of
   457                (t1 as Const (@{const_name fun_upd}, _) $ t11 $ _)
   458                $ (t2 as Const (s, _)) =>
   459                if s = unknown then polish_funs Ts t11
   460                else polish_funs Ts t1 $ polish_funs Ts t2
   461              | t1 $ t2 => polish_funs Ts t1 $ polish_funs Ts t2
   462              | Abs (s, T, t') => Abs (s, T, polish_funs (T :: Ts) t')
   463              | Const (s, Type (@{type_name fun}, [T1, T2])) =>
   464                if s = opt_flag orelse s = non_opt_flag then
   465                  Abs ("x", T1,
   466                       Const (if is_complete_type data_types false T1 then
   467                                irrelevant
   468                              else
   469                                unknown, T2))
   470                else
   471                  t
   472              | t => t
   473     fun make_fun_or_set maybe_opt T T1 T2 T' ts1 ts2 =
   474       ts1 ~~ ts2
   475       |> sort (nice_term_ord o apply2 fst)
   476       |> (case T of
   477             Type (@{type_name set}, _) =>
   478             sort_wrt (truth_const_sort_key o snd)
   479             #> make_set maybe_opt T'
   480           | _ =>
   481             make_plain_fun maybe_opt T1 T2
   482             #> unarize_unbox_etc_term
   483             #> format_fun (uniterize_unarize_unbox_etc_type T')
   484                           (uniterize_unarize_unbox_etc_type T1)
   485                           (uniterize_unarize_unbox_etc_type T2))
   486 
   487     fun term_for_fun_or_set seen T T' j =
   488         let
   489           val k1 = card_of_type card_assigns (pseudo_domain_type T)
   490           val k2 = card_of_type card_assigns (pseudo_range_type T)
   491         in
   492           term_for_rep true seen T T' (Vect (k1, Atom (k2, 0)))
   493                        [nth_combination (replicate k1 (k2, 0)) j]
   494           handle General.Subscript =>
   495                  raise ARG ("Nitpick_Model.reconstruct_term.\
   496                             \term_for_fun_or_set",
   497                             signed_string_of_int j ^ " for " ^
   498                             string_for_rep (Vect (k1, Atom (k2, 0))))
   499         end
   500     and term_for_atom seen (T as Type (@{type_name fun}, _)) T' j _ =
   501         term_for_fun_or_set seen T T' j
   502       | term_for_atom seen (T as Type (@{type_name set}, _)) T' j _ =
   503         term_for_fun_or_set seen T T' j
   504       | term_for_atom seen (Type (@{type_name prod}, [T1, T2])) _ j k =
   505         let
   506           val k1 = card_of_type card_assigns T1
   507           val k2 = k div k1
   508         in
   509           list_comb (HOLogic.pair_const T1 T2,
   510                      @{map 3} (fn T => term_for_atom seen T T) [T1, T2]
   511                           (* ### k2 or k1? FIXME *)
   512                           [j div k2, j mod k2] [k1, k2])
   513         end
   514       | term_for_atom seen @{typ prop} _ j k =
   515         HOLogic.mk_Trueprop (term_for_atom seen bool_T bool_T j k)
   516       | term_for_atom _ @{typ bool} _ j _ =
   517         if j = 0 then @{const False} else @{const True}
   518       | term_for_atom seen T _ j k =
   519         if T = nat_T then
   520           HOLogic.mk_number nat_T j
   521         else if T = int_T then
   522           HOLogic.mk_number int_T (int_for_atom (k, 0) j)
   523         else if is_fp_iterator_type T then
   524           HOLogic.mk_number nat_T (k - j - 1)
   525         else if T = @{typ bisim_iterator} then
   526           HOLogic.mk_number nat_T j
   527         else case data_type_spec data_types T of
   528           NONE => nth_atom thy atomss pool for_auto T j
   529         | SOME {deep = false, ...} => nth_atom thy atomss pool for_auto T j
   530         | SOME {co, constrs, ...} =>
   531           let
   532             fun tuples_for_const (s, T) =
   533               tuple_list_for_name rel_table bounds (ConstName (s, T, Any))
   534             fun cyclic_atom () =
   535               nth_atom thy atomss pool for_auto (Type (cyclic_type_name (), []))
   536                        j
   537             fun cyclic_var () =
   538               Var ((nth_atom_name thy atomss pool "" T j, 0), T)
   539             val discr_jsss = map (tuples_for_const o discr_for_constr o #const)
   540                                  constrs
   541             val real_j = j + offset_of_type ofs T
   542             val constr_x as (constr_s, constr_T) =
   543               get_first (fn (jss, {const, ...}) =>
   544                             if member (op =) jss [real_j] then SOME const
   545                             else NONE)
   546                         (discr_jsss ~~ constrs) |> the
   547             val arg_Ts = curried_binder_types constr_T
   548             val sel_xs =
   549               map (binarized_and_boxed_nth_sel_for_constr hol_ctxt binarize
   550                                                           constr_x)
   551                   (index_seq 0 (length arg_Ts))
   552             val sel_Rs =
   553               map (fn x => get_first
   554                                (fn ConstName (s', T', R) =>
   555                                    if (s', T') = x then SOME R else NONE
   556                                  | u => raise NUT ("Nitpick_Model.reconstruct_\
   557                                                    \term.term_for_atom", [u]))
   558                                sel_names |> the) sel_xs
   559             val arg_Rs = map (snd o dest_Func) sel_Rs
   560             val sel_jsss = map tuples_for_const sel_xs
   561             val arg_jsss =
   562               map (map_filter (fn js => if hd js = real_j then SOME (tl js)
   563                                         else NONE)) sel_jsss
   564             val uncur_arg_Ts = binder_types constr_T
   565           in
   566             if co andalso not (null seen) andalso
   567                member (op =) (seen |> unfold ? (fst o split_last)) (T, j) then
   568               cyclic_var ()
   569             else if constr_s = @{const_name Word} then
   570               HOLogic.mk_number
   571                   (if T = @{typ "unsigned_bit word"} then nat_T else int_T)
   572                   (value_of_bits (the_single arg_jsss))
   573             else
   574               let
   575                 val seen = seen |> co ? cons (T, j)
   576                 val ts =
   577                   if length arg_Ts = 0 then
   578                     []
   579                   else
   580                     @{map 3} (fn Ts => term_for_rep true seen Ts Ts) arg_Ts arg_Rs
   581                          arg_jsss
   582                     |> mk_tuple (HOLogic.mk_tupleT uncur_arg_Ts)
   583                     |> dest_n_tuple (length uncur_arg_Ts)
   584                 val t =
   585                   if constr_s = @{const_name Nitpick.Abs_Frac} then
   586                     case ts of
   587                       [Const (@{const_name Pair}, _) $ t1 $ t2] =>
   588                       frac_from_term_pair (body_type T) t1 t2
   589                     | _ => raise TERM ("Nitpick_Model.reconstruct_term.\
   590                                        \term_for_atom (Abs_Frac)", ts)
   591                   else if not for_auto andalso
   592                           (is_abs_fun ctxt constr_x orelse
   593                            constr_s = @{const_name Quot}) then
   594                     Const (abs_name, constr_T) $ the_single ts
   595                   else
   596                     list_comb (Const constr_x, ts)
   597               in
   598                 if co then
   599                   let val var = cyclic_var () in
   600                     if exists_subterm (curry (op =) var) t then
   601                       if co then
   602                         Const (@{const_name The}, (T --> bool_T) --> T)
   603                         $ Abs (cyclic_co_val_name (), T,
   604                                Const (@{const_name HOL.eq}, T --> T --> bool_T)
   605                                $ Bound 0 $ abstract_over (var, t))
   606                       else
   607                         cyclic_atom ()
   608                     else
   609                       t
   610                   end
   611                 else
   612                   t
   613               end
   614           end
   615     and term_for_vect seen k R T T' js =
   616       let
   617         val T1 = pseudo_domain_type T
   618         val T2 = pseudo_range_type T
   619       in
   620         make_fun_or_set true T T1 T2 T'
   621             (map (fn j => term_for_atom seen T1 T1 j k) (index_seq 0 k))
   622             (map (term_for_rep true seen T2 T2 R o single)
   623                  (chunk_list (arity_of_rep R) js))
   624       end
   625     and term_for_rep _ seen T T' (R as Atom (k, j0)) [[j]] =
   626         if j >= j0 andalso j < j0 + k then term_for_atom seen T T' (j - j0) k
   627         else raise REP ("Nitpick_Model.reconstruct_term.term_for_rep", [R])
   628       | term_for_rep _ seen (Type (@{type_name prod}, [T1, T2])) _
   629                      (Struct [R1, R2]) [js] =
   630         let
   631           val arity1 = arity_of_rep R1
   632           val (js1, js2) = chop arity1 js
   633         in
   634           list_comb (HOLogic.pair_const T1 T2,
   635                      @{map 3} (fn T => term_for_rep true seen T T) [T1, T2] [R1, R2]
   636                           [[js1], [js2]])
   637         end
   638       | term_for_rep _ seen T T' (Vect (k, R')) [js] =
   639         term_for_vect seen k R' T T' js
   640       | term_for_rep maybe_opt seen T T' (Func (R1, Formula Neut)) jss =
   641         let
   642           val T1 = pseudo_domain_type T
   643           val T2 = pseudo_range_type T
   644           val jss1 = all_combinations_for_rep R1
   645           val ts1 = map (term_for_rep true seen T1 T1 R1 o single) jss1
   646           val ts2 =
   647             map (fn js => term_for_rep true seen T2 T2 (Atom (2, 0))
   648                                        [[int_from_bool (member (op =) jss js)]])
   649                 jss1
   650         in make_fun_or_set maybe_opt T T1 T2 T' ts1 ts2 end
   651       | term_for_rep maybe_opt seen T T' (Func (R1, R2)) jss =
   652         let
   653           val T1 = pseudo_domain_type T
   654           val T2 = pseudo_range_type T
   655           val arity1 = arity_of_rep R1
   656           val jss1 = all_combinations_for_rep R1
   657           val ts1 = map (term_for_rep false seen T1 T1 R1 o single) jss1
   658           val grouped_jss2 = AList.group (op =) (map (chop arity1) jss)
   659           val ts2 = map (term_for_rep false seen T2 T2 R2 o the_default []
   660                          o AList.lookup (op =) grouped_jss2) jss1
   661         in make_fun_or_set maybe_opt T T1 T2 T' ts1 ts2 end
   662       | term_for_rep _ seen T T' (Opt R) jss =
   663         if null jss then Const (unknown, T)
   664         else term_for_rep true seen T T' R jss
   665       | term_for_rep _ _ T _ R jss =
   666         raise ARG ("Nitpick_Model.reconstruct_term.term_for_rep",
   667                    Syntax.string_of_typ ctxt T ^ " " ^ string_for_rep R ^ " " ^
   668                    string_of_int (length jss))
   669   in
   670     postprocess_subterms [] o polish_funs [] o unarize_unbox_etc_term
   671     oooo term_for_rep maybe_opt []
   672   end
   673 
   674 (** Constant postprocessing **)
   675 
   676 fun dest_n_tuple_type 1 T = [T]
   677   | dest_n_tuple_type n (Type (_, [T1, T2])) =
   678     T1 :: dest_n_tuple_type (n - 1) T2
   679   | dest_n_tuple_type _ T =
   680     raise TYPE ("Nitpick_Model.dest_n_tuple_type", [T], [])
   681 
   682 fun const_format thy def_tables (x as (s, T)) =
   683   if String.isPrefix unrolled_prefix s then
   684     const_format thy def_tables (original_name s, range_type T)
   685   else if String.isPrefix skolem_prefix s then
   686     let
   687       val k = unprefix skolem_prefix s
   688               |> strip_first_name_sep |> fst |> space_explode "@"
   689               |> hd |> Int.fromString |> the
   690     in [k, num_binder_types T - k] end
   691   else if original_name s <> s then
   692     [num_binder_types T]
   693   else case def_of_const thy def_tables x of
   694     SOME t' => if fixpoint_kind_of_rhs t' <> NoFp then
   695                  let val k = length (strip_abs_vars t') in
   696                    [k, num_binder_types T - k]
   697                  end
   698                else
   699                  [num_binder_types T]
   700   | NONE => [num_binder_types T]
   701 
   702 fun intersect_formats _ [] = []
   703   | intersect_formats [] _ = []
   704   | intersect_formats ks1 ks2 =
   705     let val ((ks1', k1), (ks2', k2)) = apply2 split_last (ks1, ks2) in
   706       intersect_formats (ks1' @ (if k1 > k2 then [k1 - k2] else []))
   707                         (ks2' @ (if k2 > k1 then [k2 - k1] else [])) @
   708       [Int.min (k1, k2)]
   709     end
   710 
   711 fun lookup_format thy def_tables formats t =
   712   case AList.lookup (fn (SOME x, SOME y) =>
   713                         (term_match thy) (x, y) | _ => false)
   714                     formats (SOME t) of
   715     SOME format => format
   716   | NONE => let val format = the (AList.lookup (op =) formats NONE) in
   717               case t of
   718                 Const x => intersect_formats format
   719                                              (const_format thy def_tables x)
   720               | _ => format
   721             end
   722 
   723 fun format_type default_format format T =
   724   let
   725     val T = uniterize_unarize_unbox_etc_type T
   726     val format = format |> filter (curry (op <) 0)
   727   in
   728     if forall (curry (op =) 1) format then
   729       T
   730     else
   731       let
   732         val (binder_Ts, body_T) = strip_type T
   733         val batched =
   734           binder_Ts
   735           |> map (format_type default_format default_format)
   736           |> rev |> chunk_list_unevenly (rev format)
   737           |> map (HOLogic.mk_tupleT o rev)
   738       in List.foldl (op -->) body_T batched end
   739   end
   740 
   741 fun format_term_type thy def_tables formats t =
   742   format_type (the (AList.lookup (op =) formats NONE))
   743               (lookup_format thy def_tables formats t) (fastype_of t)
   744 
   745 fun repair_special_format js m format =
   746   m - 1 downto 0 |> chunk_list_unevenly (rev format)
   747                  |> map (rev o filter_out (member (op =) js))
   748                  |> filter_out null |> map length |> rev
   749 
   750 fun user_friendly_const ({thy, evals, def_tables, skolems, special_funs, ...}
   751                          : hol_context) (base_name, step_name) formats =
   752   let
   753     val default_format = the (AList.lookup (op =) formats NONE)
   754     fun do_const (x as (s, T)) =
   755       (if String.isPrefix special_prefix s then
   756          let
   757            val do_term = map_aterms (fn Const x => fst (do_const x) | t' => t')
   758            val (x' as (_, T'), js, ts) =
   759              AList.find (op =) (!special_funs) (s, unarize_unbox_etc_type T)
   760              |> the_single
   761            val max_j = List.last js
   762            val Ts = List.take (binder_types T', max_j + 1)
   763            val missing_js = filter_out (member (op =) js) (0 upto max_j)
   764            val missing_Ts = filter_indices missing_js Ts
   765            fun nth_missing_var n =
   766              ((arg_var_prefix ^ nat_subscript (n + 1), 0), nth missing_Ts n)
   767            val missing_vars = map nth_missing_var (0 upto length missing_js - 1)
   768            val vars = special_bounds ts @ missing_vars
   769            val ts' =
   770              map (fn j =>
   771                      case AList.lookup (op =) (js ~~ ts) j of
   772                        SOME t => do_term t
   773                      | NONE =>
   774                        Var (nth missing_vars
   775                                 (find_index (curry (op =) j) missing_js)))
   776                  (0 upto max_j)
   777            val t = do_const x' |> fst
   778            val format =
   779              case AList.lookup (fn (SOME t1, SOME t2) => term_match thy (t1, t2)
   780                                  | _ => false) formats (SOME t) of
   781                SOME format =>
   782                repair_special_format js (num_binder_types T') format
   783              | NONE =>
   784                const_format thy def_tables x'
   785                |> repair_special_format js (num_binder_types T')
   786                |> intersect_formats default_format
   787          in
   788            (list_comb (t, ts') |> fold_rev abs_var vars,
   789             format_type default_format format T)
   790          end
   791        else if String.isPrefix uncurry_prefix s then
   792          let
   793            val (ss, s') = unprefix uncurry_prefix s
   794                           |> strip_first_name_sep |>> space_explode "@"
   795          in
   796            if String.isPrefix step_prefix s' then
   797              do_const (s', T)
   798            else
   799              let
   800                val k = the (Int.fromString (hd ss))
   801                val j = the (Int.fromString (List.last ss))
   802                val (before_Ts, (tuple_T, rest_T)) =
   803                  strip_n_binders j T ||> (strip_n_binders 1 #>> hd)
   804                val T' = before_Ts ---> dest_n_tuple_type k tuple_T ---> rest_T
   805              in do_const (s', T') end
   806          end
   807        else if String.isPrefix unrolled_prefix s then
   808          let val t = Const (original_name s, range_type T) in
   809            (lambda (Free (iter_var_prefix, nat_T)) t,
   810             format_type default_format
   811                         (lookup_format thy def_tables formats t) T)
   812          end
   813        else if String.isPrefix base_prefix s then
   814          (Const (base_name, T --> T) $ Const (unprefix base_prefix s, T),
   815           format_type default_format default_format T)
   816        else if String.isPrefix step_prefix s then
   817          (Const (step_name, T --> T) $ Const (unprefix step_prefix s, T),
   818           format_type default_format default_format T)
   819        else if String.isPrefix quot_normal_prefix s then
   820          let val t = Const (nitpick_prefix ^ "quotient normal form", T) in
   821            (t, format_term_type thy def_tables formats t)
   822          end
   823        else if String.isPrefix skolem_prefix s then
   824          let
   825            val ss = the (AList.lookup (op =) (!skolems) s)
   826            val (Ts, Ts') = chop (length ss) (binder_types T)
   827            val frees = map Free (ss ~~ Ts)
   828            val s' = original_name s
   829          in
   830            (fold lambda frees (Const (s', Ts' ---> T)),
   831             format_type default_format
   832                         (lookup_format thy def_tables formats (Const x)) T)
   833          end
   834        else if String.isPrefix eval_prefix s then
   835          let
   836            val t = nth evals (the (Int.fromString (unprefix eval_prefix s)))
   837          in (t, format_term_type thy def_tables formats t) end
   838        else
   839          (* The selector case can occur in conjunction with fractional types.
   840             It's not pretty. *)
   841          let val t = Const (s |> not (is_sel s) ? original_name, T) in
   842            (t, format_term_type thy def_tables formats t)
   843          end)
   844       |>> map_types uniterize_unarize_unbox_etc_type
   845       |>> shorten_names_in_term |>> Term.map_abs_vars shortest_name
   846   in do_const end
   847 
   848 fun assign_operator_for_const (s, T) =
   849   if String.isPrefix ubfp_prefix s then
   850     xsym "\<le>" "<=" ()
   851   else if String.isPrefix lbfp_prefix s then
   852     xsym "\<ge>" ">=" ()
   853   else if original_name s <> s then
   854     assign_operator_for_const (strip_first_name_sep s |> snd, T)
   855   else
   856     "="
   857 
   858 (** Model reconstruction **)
   859 
   860 fun unfold_outer_the_binders (t as Const (@{const_name The}, _)
   861                                    $ Abs (s, T, Const (@{const_name HOL.eq}, _)
   862                                                 $ Bound 0 $ t')) =
   863     betapply (Abs (s, T, t'), t) |> unfold_outer_the_binders
   864   | unfold_outer_the_binders t = t
   865 
   866 fun bisimilar_values _ 0 _ = true
   867   | bisimilar_values coTs max_depth (t1, t2) =
   868     let val T = fastype_of t1 in
   869       if exists_subtype (member (op =) coTs) T then
   870         let
   871           val ((head1, args1), (head2, args2)) =
   872             apply2 (strip_comb o unfold_outer_the_binders) (t1, t2)
   873           val max_depth = max_depth - (if member (op =) coTs T then 1 else 0)
   874         in
   875           head1 = head2 andalso
   876           forall (bisimilar_values coTs max_depth) (args1 ~~ args2)
   877         end
   878       else
   879         t1 = t2
   880     end
   881 
   882 fun pretty_term_auto_global ctxt t =
   883   let
   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_wrt (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 fun term_for_name pool scope atomss sel_names rel_table bounds name =
  1037   let val T = type_of name in
  1038     tuple_list_for_name rel_table bounds name
  1039     |> reconstruct_term (not (is_fully_representable_set name)) false pool
  1040                         (("", ""), ("", "")) scope atomss sel_names rel_table
  1041                         bounds T T (rep_of name)
  1042   end
  1043 
  1044 fun prove_hol_model (scope as {hol_ctxt = {thy, ctxt, debug, ...},
  1045                                card_assigns, ...})
  1046                     auto_timeout free_names sel_names rel_table bounds prop =
  1047   let
  1048     val pool = Unsynchronized.ref []
  1049     val atomss = [(NONE, [])]
  1050     fun free_type_assm (T, k) =
  1051       let
  1052         fun atom j = nth_atom thy atomss pool true T j
  1053         fun equation_for_atom j = HOLogic.eq_const T $ Bound 0 $ atom j
  1054         val eqs = map equation_for_atom (index_seq 0 k)
  1055         val compreh_assm =
  1056           Const (@{const_name All}, (T --> bool_T) --> bool_T)
  1057               $ Abs ("x", T, foldl1 HOLogic.mk_disj eqs)
  1058         val distinct_assm = distinctness_formula T (map atom (index_seq 0 k))
  1059       in s_conj (compreh_assm, distinct_assm) end
  1060     fun free_name_assm name =
  1061       HOLogic.mk_eq (Free (nickname_of name, type_of name),
  1062                      term_for_name pool scope atomss sel_names rel_table bounds
  1063                                    name)
  1064     val freeT_assms = map free_type_assm (filter (is_TFree o fst) card_assigns)
  1065     val model_assms = map free_name_assm free_names
  1066     val assm = foldr1 s_conj (freeT_assms @ model_assms)
  1067     fun try_out negate =
  1068       let
  1069         val concl = (negate ? curry (op $) @{const Not})
  1070                     (Object_Logic.atomize_term ctxt prop)
  1071         val prop = HOLogic.mk_Trueprop (HOLogic.mk_imp (assm, concl))
  1072                    |> map_types (map_type_tfree
  1073                                      (fn (s, []) => TFree (s, @{sort type})
  1074                                        | x => TFree x))
  1075         val _ =
  1076           if debug then
  1077             (if negate then "Genuineness" else "Spuriousness") ^ " goal: " ^
  1078             Syntax.string_of_term ctxt prop ^ "."
  1079             |> writeln
  1080           else
  1081             ()
  1082         val goal = prop |> Thm.cterm_of ctxt |> Goal.init
  1083       in
  1084         (goal |> SINGLE (DETERM_TIMEOUT auto_timeout (auto_tac ctxt))
  1085               |> the |> Goal.finish ctxt; true)
  1086         handle THM _ => false
  1087              | TimeLimit.TimeOut => false
  1088       end
  1089   in
  1090     if try_out false then SOME true
  1091     else if try_out true then SOME false
  1092     else NONE
  1093   end
  1094 
  1095 end;