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