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