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