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