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