src/HOL/Tools/Nitpick/nitpick_model.ML
author blanchet
Mon, 14 Dec 2009 12:30:26 +0100
changeset 34118 5e831d805118
parent 33982 1ae222745c4a
child 34120 c4988215a691
permissions -rw-r--r--
get rid of polymorphic equality in Nitpick's code + a few minor cleanups
     1 (*  Title:      HOL/Tools/Nitpick/nitpick_model.ML
     2     Author:     Jasmin Blanchette, TU Muenchen
     3     Copyright   2009
     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 
    20   structure NameTable : TABLE
    21 
    22   val tuple_list_for_name :
    23     nut NameTable.table -> Kodkod.raw_bound list -> nut -> int list list
    24   val reconstruct_hol_model :
    25     params -> scope -> (term option * int list) list -> styp list -> nut list
    26     -> nut list -> nut list -> nut NameTable.table -> Kodkod.raw_bound list
    27     -> Pretty.T * bool
    28   val prove_hol_model :
    29     scope -> Time.time option -> nut list -> nut list -> nut NameTable.table
    30     -> Kodkod.raw_bound list -> term -> bool option
    31 end;
    32 
    33 structure Nitpick_Model : NITPICK_MODEL =
    34 struct
    35 
    36 open Nitpick_Util
    37 open Nitpick_HOL
    38 open Nitpick_Scope
    39 open Nitpick_Peephole
    40 open Nitpick_Rep
    41 open Nitpick_Nut
    42 
    43 type params = {
    44   show_skolems: bool,
    45   show_datatypes: bool,
    46   show_consts: bool}
    47 
    48 val unknown = "?"
    49 val unrep = "\<dots>"
    50 val maybe_mixfix = "_\<^sup>?"
    51 val base_mixfix = "_\<^bsub>base\<^esub>"
    52 val step_mixfix = "_\<^bsub>step\<^esub>"
    53 val abs_mixfix = "\<guillemotleft>_\<guillemotright>"
    54 val non_opt_name = nitpick_prefix ^ "non_opt"
    55 
    56 (* string -> int -> string *)
    57 fun atom_suffix s j =
    58   nat_subscript (j + 1)
    59   |> (s <> "" andalso Symbol.is_ascii_digit (List.last (explode s)))
    60      ? prefix "\<^isub>,"
    61 (* string -> typ -> int -> string *)
    62 fun atom_name prefix (T as Type (s, _)) j =
    63     prefix ^ substring (shortest_name s, 0, 1) ^ atom_suffix s j
    64   | atom_name prefix (T as TFree (s, _)) j =
    65     prefix ^ perhaps (try (unprefix "'")) s ^ atom_suffix s j
    66   | atom_name _ T _ = raise TYPE ("Nitpick_Model.atom_name", [T], [])
    67 (* bool -> typ -> int -> term *)
    68 fun atom for_auto T j =
    69   if for_auto then
    70     Free (atom_name (hd (space_explode "." nitpick_prefix)) T j, T)
    71   else
    72     Const (atom_name "" T j, T)
    73 
    74 (* nut NameTable.table -> Kodkod.raw_bound list -> nut -> int list list *)
    75 fun tuple_list_for_name rel_table bounds name =
    76   the (AList.lookup (op =) bounds (the_rel rel_table name)) handle NUT _ => [[]]
    77 
    78 (* term -> term *)
    79 fun unbox_term (Const (@{const_name FunBox}, _) $ t1) = unbox_term t1
    80   | unbox_term (Const (@{const_name PairBox},
    81                        Type ("fun", [T1, Type ("fun", [T2, T3])])) $ t1 $ t2) =
    82     let val Ts = map unbox_type [T1, T2] in
    83       Const (@{const_name Pair}, Ts ---> Type ("*", Ts))
    84       $ unbox_term t1 $ unbox_term t2
    85     end
    86   | unbox_term (Const (s, T)) = Const (s, unbox_type T)
    87   | unbox_term (t1 $ t2) = unbox_term t1 $ unbox_term t2
    88   | unbox_term (Free (s, T)) = Free (s, unbox_type T)
    89   | unbox_term (Var (x, T)) = Var (x, unbox_type T)
    90   | unbox_term (Bound j) = Bound j
    91   | unbox_term (Abs (s, T, t')) = Abs (s, unbox_type T, unbox_term t')
    92 
    93 (* typ -> typ -> (typ * typ) * (typ * typ) *)
    94 fun factor_out_types (T1 as Type ("*", [T11, T12]))
    95                      (T2 as Type ("*", [T21, T22])) =
    96     let val (n1, n2) = pairself num_factors_in_type (T11, T21) in
    97       if n1 = n2 then
    98         let
    99           val ((T11', opt_T12'), (T21', opt_T22')) = factor_out_types T12 T22
   100         in
   101           ((Type ("*", [T11, T11']), opt_T12'),
   102            (Type ("*", [T21, T21']), opt_T22'))
   103         end
   104       else if n1 < n2 then
   105         case factor_out_types T1 T21 of
   106           (p1, (T21', NONE)) => (p1, (T21', SOME T22))
   107         | (p1, (T21', SOME T22')) =>
   108           (p1, (T21', SOME (Type ("*", [T22', T22]))))
   109       else
   110         swap (factor_out_types T2 T1)
   111     end
   112   | factor_out_types (Type ("*", [T11, T12])) T2 = ((T11, SOME T12), (T2, NONE))
   113   | factor_out_types T1 (Type ("*", [T21, T22])) = ((T1, NONE), (T21, SOME T22))
   114   | factor_out_types T1 T2 = ((T1, NONE), (T2, NONE))
   115 
   116 (* bool -> typ -> typ -> (term * term) list -> term *)
   117 fun make_plain_fun maybe_opt T1 T2 =
   118   let
   119     (* typ -> typ -> (term * term) list -> term *)
   120     fun aux T1 T2 [] =
   121         Const (if maybe_opt orelse T2 <> bool_T then @{const_name undefined}
   122                else non_opt_name, T1 --> T2)
   123       | aux T1 T2 ((t1, t2) :: ps) =
   124         Const (@{const_name fun_upd}, [T1 --> T2, T1, T2] ---> T1 --> T2)
   125         $ aux T1 T2 ps $ t1 $ t2
   126   in aux T1 T2 o rev end
   127 (* term -> bool *)
   128 fun is_plain_fun (Const (s, _)) =
   129     (s = @{const_name undefined} orelse s = non_opt_name)
   130   | is_plain_fun (Const (@{const_name fun_upd}, _) $ t0 $ _ $ _) =
   131     is_plain_fun t0
   132   | is_plain_fun _ = false
   133 (* term -> bool * (term list * term list) *)
   134 val dest_plain_fun =
   135   let
   136     (* term -> term list * term list *)
   137     fun aux (Const (s, _)) = (s <> non_opt_name, ([], []))
   138       | aux (Const (@{const_name fun_upd}, _) $ t0 $ t1 $ t2) =
   139         let val (s, (ts1, ts2)) = aux t0 in (s, (t1 :: ts1, t2 :: ts2)) end
   140       | aux t = raise TERM ("Nitpick_Model.dest_plain_fun", [t])
   141   in apsnd (pairself rev) o aux end
   142 
   143 (* typ -> typ -> typ -> term -> term * term *)
   144 fun break_in_two T T1 T2 t =
   145   let
   146     val ps = HOLogic.flat_tupleT_paths T
   147     val cut = length (HOLogic.strip_tupleT T1)
   148     val (ps1, ps2) = pairself HOLogic.flat_tupleT_paths (T1, T2)
   149     val (ts1, ts2) = t |> HOLogic.strip_ptuple ps |> chop cut
   150   in (HOLogic.mk_ptuple ps1 T1 ts1, HOLogic.mk_ptuple ps2 T2 ts2) end
   151 (* typ -> term -> term -> term *)
   152 fun pair_up (Type ("*", [T1', T2']))
   153             (t1 as Const (@{const_name Pair},
   154                           Type ("fun", [_, Type ("fun", [_, T1])])) $ t11 $ t12)
   155             t2 =
   156     if T1 = T1' then HOLogic.mk_prod (t1, t2)
   157     else HOLogic.mk_prod (t11, pair_up T2' t12 t2)
   158   | pair_up _ t1 t2 = HOLogic.mk_prod (t1, t2)
   159 (* typ -> term -> term list * term list -> (term * term) list*)
   160 fun multi_pair_up T1 t1 (ts2, ts3) = map2 (pair o pair_up T1 t1) ts2 ts3
   161 
   162 (* typ -> typ -> typ -> term -> term *)
   163 fun typecast_fun (Type ("fun", [T1', T2'])) T1 T2 t =
   164     let
   165       (* typ -> typ -> typ -> typ -> term -> term *)
   166       fun do_curry T1 T1a T1b T2 t =
   167         let
   168           val (maybe_opt, ps) = dest_plain_fun t
   169           val ps =
   170             ps |>> map (break_in_two T1 T1a T1b)
   171                |> uncurry (map2 (fn (t1a, t1b) => fn t2 => (t1a, (t1b, t2))))
   172                |> AList.coalesce (op =)
   173                |> map (apsnd (make_plain_fun maybe_opt T1b T2))
   174         in make_plain_fun maybe_opt T1a (T1b --> T2) ps end
   175       (* typ -> typ -> term -> term *)
   176       and do_uncurry T1 T2 t =
   177         let
   178           val (maybe_opt, tsp) = dest_plain_fun t
   179           val ps =
   180             tsp |> op ~~
   181                 |> maps (fn (t1, t2) =>
   182                             multi_pair_up T1 t1 (snd (dest_plain_fun t2)))
   183         in make_plain_fun maybe_opt T1 T2 ps end
   184       (* typ -> typ -> typ -> typ -> term -> term *)
   185       and do_arrow T1' T2' _ _ (Const (s, _)) = Const (s, T1' --> T2')
   186         | do_arrow T1' T2' T1 T2
   187                    (Const (@{const_name fun_upd}, _) $ t0 $ t1 $ t2) =
   188           Const (@{const_name fun_upd},
   189                  [T1' --> T2', T1', T2'] ---> T1' --> T2')
   190           $ do_arrow T1' T2' T1 T2 t0 $ do_term T1' T1 t1 $ do_term T2' T2 t2
   191         | do_arrow _ _ _ _ t =
   192           raise TERM ("Nitpick_Model.typecast_fun.do_arrow", [t])
   193       and do_fun T1' T2' T1 T2 t =
   194         case factor_out_types T1' T1 of
   195           ((_, NONE), (_, NONE)) => t |> do_arrow T1' T2' T1 T2
   196         | ((_, NONE), (T1a, SOME T1b)) =>
   197           t |> do_curry T1 T1a T1b T2 |> do_arrow T1' T2' T1a (T1b --> T2)
   198         | ((T1a', SOME T1b'), (_, NONE)) =>
   199           t |> do_arrow T1a' (T1b' --> T2') T1 T2 |> do_uncurry T1' T2'
   200         | _ => raise TYPE ("Nitpick_Model.typecast_fun.do_fun", [T1, T1'], [])
   201       (* typ -> typ -> term -> term *)
   202       and do_term (Type ("fun", [T1', T2'])) (Type ("fun", [T1, T2])) t =
   203           do_fun T1' T2' T1 T2 t
   204         | do_term (T' as Type ("*", Ts' as [T1', T2'])) (Type ("*", [T1, T2]))
   205                   (Const (@{const_name Pair}, _) $ t1 $ t2) =
   206           Const (@{const_name Pair}, Ts' ---> T')
   207           $ do_term T1' T1 t1 $ do_term T2' T2 t2
   208         | do_term T' T t =
   209           if T = T' then t
   210           else raise TYPE ("Nitpick_Model.typecast_fun.do_term", [T, T'], [])
   211     in if T1' = T1 andalso T2' = T2 then t else do_fun T1' T2' T1 T2 t end
   212   | typecast_fun T' _ _ _ = raise TYPE ("Nitpick_Model.typecast_fun", [T'], [])
   213 
   214 (* term -> string *)
   215 fun truth_const_sort_key @{const True} = "0"
   216   | truth_const_sort_key @{const False} = "2"
   217   | truth_const_sort_key _ = "1"
   218 
   219 (* typ -> term list -> term *)
   220 fun mk_tuple (Type ("*", [T1, T2])) ts =
   221     HOLogic.mk_prod (mk_tuple T1 ts,
   222         mk_tuple T2 (List.drop (ts, length (HOLogic.flatten_tupleT T1))))
   223   | mk_tuple _ (t :: _) = t
   224 
   225 (* string * string * string * string -> scope -> nut list -> nut list
   226    -> nut list -> nut NameTable.table -> Kodkod.raw_bound list -> typ -> typ
   227    -> rep -> int list list -> term *)
   228 fun reconstruct_term (maybe_name, base_name, step_name, abs_name)
   229         ({ext_ctxt as {thy, ctxt, ...}, card_assigns, datatypes, ofs, ...}
   230          : scope) sel_names rel_table bounds =
   231   let
   232     val for_auto = (maybe_name = "")
   233     (* bool -> typ -> typ -> (term * term) list -> term *)
   234     fun make_set maybe_opt T1 T2 =
   235       let
   236         val empty_const = Const (@{const_name Set.empty}, T1 --> T2)
   237         val insert_const = Const (@{const_name insert},
   238                                   [T1, T1 --> T2] ---> T1 --> T2)
   239         (* (term * term) list -> term *)
   240         fun aux [] =
   241             if maybe_opt andalso not (is_precise_type datatypes T1) then
   242               insert_const $ Const (unrep, T1) $ empty_const
   243             else
   244               empty_const
   245           | aux ((t1, t2) :: zs) =
   246             aux zs |> t2 <> @{const False}
   247                       ? curry (op $) (insert_const
   248                                       $ (t1 |> t2 <> @{const True}
   249                                                ? curry (op $)
   250                                                        (Const (maybe_name,
   251                                                                T1 --> T1))))
   252       in aux end
   253     (* typ -> typ -> typ -> (term * term) list -> term *)
   254     fun make_map T1 T2 T2' =
   255       let
   256         val update_const = Const (@{const_name fun_upd},
   257                                   [T1 --> T2, T1, T2] ---> T1 --> T2)
   258         (* (term * term) list -> term *)
   259         fun aux' [] = Const (@{const_name Map.empty}, T1 --> T2)
   260           | aux' ((t1, t2) :: ps) =
   261             (case t2 of
   262                Const (@{const_name None}, _) => aux' ps
   263              | _ => update_const $ aux' ps $ t1 $ t2)
   264         fun aux ps =
   265           if not (is_precise_type datatypes T1) then
   266             update_const $ aux' ps $ Const (unrep, T1)
   267             $ (Const (@{const_name Some}, T2' --> T2) $ Const (unknown, T2'))
   268           else
   269             aux' ps
   270       in aux end
   271     (* typ list -> term -> term *)
   272     fun setify_mapify_funs Ts t =
   273       (case fastype_of1 (Ts, t) of
   274          Type ("fun", [T1, T2]) =>
   275          if is_plain_fun t then
   276            case T2 of
   277              @{typ bool} =>
   278              let
   279                val (maybe_opt, ts_pair) =
   280                  dest_plain_fun t ||> pairself (map (setify_mapify_funs Ts))
   281              in
   282                make_set maybe_opt T1 T2
   283                         (sort_wrt (truth_const_sort_key o snd) (op ~~ ts_pair))
   284              end
   285            | Type (@{type_name option}, [T2']) =>
   286              let
   287                val ts_pair = snd (dest_plain_fun t)
   288                              |> pairself (map (setify_mapify_funs Ts))
   289              in make_map T1 T2 T2' (rev (op ~~ ts_pair)) end
   290            | _ => raise SAME ()
   291          else
   292            raise SAME ()
   293        | _ => raise SAME ())
   294       handle SAME () =>
   295              case t of
   296                t1 $ t2 => setify_mapify_funs Ts t1 $ setify_mapify_funs Ts t2
   297              | Abs (s, T, t') => Abs (s, T, setify_mapify_funs (T :: Ts) t')
   298              | _ => t
   299     (* bool -> typ -> typ -> typ -> term list -> term list -> term *)
   300     fun make_fun maybe_opt T1 T2 T' ts1 ts2 =
   301       ts1 ~~ ts2 |> T1 = @{typ bisim_iterator} ? rev
   302                  |> make_plain_fun (maybe_opt andalso not for_auto) T1 T2
   303                  |> unbox_term
   304                  |> typecast_fun (unbox_type T') (unbox_type T1) (unbox_type T2)
   305     (* (typ * int) list -> typ -> typ -> int -> term *)
   306     fun term_for_atom seen (T as Type ("fun", [T1, T2])) T' j =
   307         let
   308           val k1 = card_of_type card_assigns T1
   309           val k2 = card_of_type card_assigns T2
   310         in
   311           term_for_rep seen T T' (Vect (k1, Atom (k2, 0)))
   312                        [nth_combination (replicate k1 (k2, 0)) j]
   313           handle General.Subscript =>
   314                  raise ARG ("Nitpick_Model.reconstruct_term.term_for_atom",
   315                             signed_string_of_int j ^ " for " ^
   316                             string_for_rep (Vect (k1, Atom (k2, 0))))
   317         end
   318       | term_for_atom seen (Type ("*", [T1, T2])) _ j =
   319         let val k1 = card_of_type card_assigns T1 in
   320           list_comb (HOLogic.pair_const T1 T2,
   321                      map2 (fn T => term_for_atom seen T T) [T1, T2]
   322                           [j div k1, j mod k1])
   323         end
   324       | term_for_atom seen @{typ prop} _ j =
   325         HOLogic.mk_Trueprop (term_for_atom seen bool_T bool_T j)
   326       | term_for_atom _ @{typ bool} _ j =
   327         if j = 0 then @{const False} else @{const True}
   328       | term_for_atom _ @{typ unit} _ _ = @{const Unity}
   329       | term_for_atom seen T _ j =
   330         if T = nat_T then
   331           HOLogic.mk_number nat_T j
   332         else if T = int_T then
   333           HOLogic.mk_number int_T
   334               (int_for_atom (card_of_type card_assigns int_T, 0) j)
   335         else if is_fp_iterator_type T then
   336           HOLogic.mk_number nat_T (card_of_type card_assigns T - j - 1)
   337         else if T = @{typ bisim_iterator} then
   338           HOLogic.mk_number nat_T j
   339         else case datatype_spec datatypes T of
   340           NONE => atom for_auto T j
   341         | SOME {shallow = true, ...} => atom for_auto T j
   342         | SOME {co, constrs, ...} =>
   343           let
   344             (* styp -> int list *)
   345             fun tuples_for_const (s, T) =
   346               tuple_list_for_name rel_table bounds (ConstName (s, T, Any))
   347             (* unit -> indexname * typ *)
   348             fun var () = ((atom_name "" T j, 0), T)
   349             val discr_jsss = map (tuples_for_const o discr_for_constr o #const)
   350                                  constrs
   351             val real_j = j + offset_of_type ofs T
   352             val constr_x as (constr_s, constr_T) =
   353               get_first (fn (jss, {const, ...}) =>
   354                             if member (op =) jss [real_j] then SOME const
   355                             else NONE)
   356                         (discr_jsss ~~ constrs) |> the
   357             val arg_Ts = curried_binder_types constr_T
   358             val sel_xs = map (boxed_nth_sel_for_constr ext_ctxt constr_x)
   359                              (index_seq 0 (length arg_Ts))
   360             val sel_Rs =
   361               map (fn x => get_first
   362                                (fn ConstName (s', T', R) =>
   363                                    if (s', T') = x then SOME R else NONE
   364                                  | u => raise NUT ("Nitpick_Model.reconstruct_\
   365                                                    \term.term_for_atom", [u]))
   366                                sel_names |> the) sel_xs
   367             val arg_Rs = map (snd o dest_Func) sel_Rs
   368             val sel_jsss = map tuples_for_const sel_xs
   369             val arg_jsss =
   370               map (map_filter (fn js => if hd js = real_j then SOME (tl js)
   371                                         else NONE)) sel_jsss
   372             val uncur_arg_Ts = binder_types constr_T
   373           in
   374             if co andalso member (op =) seen (T, j) then
   375               Var (var ())
   376             else
   377               let
   378                 val seen = seen |> co ? cons (T, j)
   379                 val ts =
   380                   if length arg_Ts = 0 then
   381                     []
   382                   else
   383                     map3 (fn Ts => term_for_rep seen Ts Ts) arg_Ts arg_Rs
   384                          arg_jsss
   385                     |> mk_tuple (HOLogic.mk_tupleT uncur_arg_Ts)
   386                     |> dest_n_tuple (length uncur_arg_Ts)
   387                 val t =
   388                   if constr_s = @{const_name Abs_Frac} then
   389                     let
   390                       val num_T = body_type T
   391                       (* int -> term *)
   392                       val mk_num = HOLogic.mk_number num_T
   393                     in
   394                       case ts of
   395                         [Const (@{const_name Pair}, _) $ t1 $ t2] =>
   396                         (case snd (HOLogic.dest_number t1) of
   397                            0 => mk_num 0
   398                          | n1 => case HOLogic.dest_number t2 |> snd of
   399                                    1 => mk_num n1
   400                                  | n2 => Const (@{const_name HOL.divide},
   401                                                 [num_T, num_T] ---> num_T)
   402                                          $ mk_num n1 $ mk_num n2)
   403                       | _ => raise TERM ("Nitpick_Model.reconstruct_term.term_\
   404                                          \for_atom (Abs_Frac)", ts)
   405                     end
   406                   else if not for_auto andalso is_abs_fun thy constr_x then
   407                     Const (abs_name, constr_T) $ the_single ts
   408                   else
   409                     list_comb (Const constr_x, ts)
   410               in
   411                 if co then
   412                   let val var = var () in
   413                     if exists_subterm (curry (op =) (Var var)) t then
   414                       Const (@{const_name The}, (T --> bool_T) --> T)
   415                       $ Abs ("\<omega>", T,
   416                              Const (@{const_name "op ="}, [T, T] ---> bool_T)
   417                              $ Bound 0 $ abstract_over (Var var, t))
   418                     else
   419                       t
   420                   end
   421                 else
   422                   t
   423               end
   424           end
   425     (* (typ * int) list -> int -> rep -> typ -> typ -> typ -> int list
   426        -> term *)
   427     and term_for_vect seen k R T1 T2 T' js =
   428       make_fun true T1 T2 T' (map (term_for_atom seen T1 T1) (index_seq 0 k))
   429                (map (term_for_rep seen T2 T2 R o single)
   430                     (batch_list (arity_of_rep R) js))
   431     (* (typ * int) list -> typ -> typ -> rep -> int list list -> term *)
   432     and term_for_rep seen T T' Unit [[]] = term_for_atom seen T T' 0
   433       | term_for_rep seen T T' (R as Atom (k, j0)) [[j]] =
   434         if j >= j0 andalso j < j0 + k then term_for_atom seen T T' (j - j0)
   435         else raise REP ("Nitpick_Model.reconstruct_term.term_for_rep", [R])
   436       | term_for_rep seen (Type ("*", [T1, T2])) _ (Struct [R1, R2]) [js] =
   437         let
   438           val arity1 = arity_of_rep R1
   439           val (js1, js2) = chop arity1 js
   440         in
   441           list_comb (HOLogic.pair_const T1 T2,
   442                      map3 (fn T => term_for_rep seen T T) [T1, T2] [R1, R2]
   443                           [[js1], [js2]])
   444         end
   445       | term_for_rep seen (Type ("fun", [T1, T2])) T' (R as Vect (k, R')) [js] =
   446         term_for_vect seen k R' T1 T2 T' js
   447       | term_for_rep seen (Type ("fun", [T1, T2])) T' (Func (R1, Formula Neut))
   448                      jss =
   449         let
   450           val jss1 = all_combinations_for_rep R1
   451           val ts1 = map (term_for_rep seen T1 T1 R1 o single) jss1
   452           val ts2 =
   453             map (fn js => term_for_rep seen T2 T2 (Atom (2, 0))
   454                                        [[int_for_bool (member (op =) jss js)]])
   455                 jss1
   456         in make_fun false T1 T2 T' ts1 ts2 end
   457       | term_for_rep seen (Type ("fun", [T1, T2])) T' (Func (R1, R2)) jss =
   458         let
   459           val arity1 = arity_of_rep R1
   460           val jss1 = all_combinations_for_rep R1
   461           val ts1 = map (term_for_rep seen T1 T1 R1 o single) jss1
   462           val grouped_jss2 = AList.group (op =) (map (chop arity1) jss)
   463           val ts2 = map (term_for_rep seen T2 T2 R2 o the_default []
   464                          o AList.lookup (op =) grouped_jss2) jss1
   465         in make_fun true T1 T2 T' ts1 ts2 end
   466       | term_for_rep seen T T' (Opt R) jss =
   467         if null jss then Const (unknown, T) else term_for_rep seen T T' R jss
   468       | term_for_rep seen T _ R jss =
   469         raise ARG ("Nitpick_Model.reconstruct_term.term_for_rep",
   470                    Refute.string_of_typ T ^ " " ^ string_for_rep R ^ " " ^
   471                    string_of_int (length jss))
   472   in
   473     (not for_auto ? setify_mapify_funs []) o unbox_term oooo term_for_rep []
   474   end
   475 
   476 (* scope -> nut list -> nut NameTable.table -> Kodkod.raw_bound list -> nut
   477    -> term *)
   478 fun term_for_name scope sel_names rel_table bounds name =
   479   let val T = type_of name in
   480     tuple_list_for_name rel_table bounds name
   481     |> reconstruct_term ("", "", "", "") scope sel_names rel_table bounds T T
   482                         (rep_of name)
   483   end
   484 
   485 (* Proof.context
   486    -> (string * string * string * string * string) * Proof.context *)
   487 fun add_wacky_syntax ctxt =
   488   let
   489     (* term -> string *)
   490     val name_of = fst o dest_Const
   491     val thy = ProofContext.theory_of ctxt |> Context.reject_draft
   492     val (maybe_t, thy) =
   493       Sign.declare_const ((@{binding nitpick_maybe}, @{typ "'a => 'a"}),
   494                           Mixfix (maybe_mixfix, [1000], 1000)) thy
   495     val (base_t, thy) =
   496       Sign.declare_const ((@{binding nitpick_base}, @{typ "'a => 'a"}),
   497                           Mixfix (base_mixfix, [1000], 1000)) thy
   498     val (step_t, thy) =
   499       Sign.declare_const ((@{binding nitpick_step}, @{typ "'a => 'a"}),
   500                           Mixfix (step_mixfix, [1000], 1000)) thy
   501     val (abs_t, thy) =
   502       Sign.declare_const ((@{binding nitpick_abs}, @{typ "'a => 'b"}),
   503                           Mixfix (abs_mixfix, [40], 40)) thy
   504   in
   505     ((name_of maybe_t, name_of base_t, name_of step_t, name_of abs_t),
   506      ProofContext.transfer_syntax thy ctxt)
   507   end
   508 
   509 (* term -> term *)
   510 fun unfold_outer_the_binders (t as Const (@{const_name The}, _)
   511                                    $ Abs (s, T, Const (@{const_name "op ="}, _)
   512                                                 $ Bound 0 $ t')) =
   513     betapply (Abs (s, T, t'), t) |> unfold_outer_the_binders
   514   | unfold_outer_the_binders t = t
   515 (* typ list -> int -> term * term -> bool *)
   516 fun bisimilar_values _ 0 _ = true
   517   | bisimilar_values coTs max_depth (t1, t2) =
   518     let val T = fastype_of t1 in
   519       if exists_subtype (member (op =) coTs) T then
   520         let
   521           val ((head1, args1), (head2, args2)) =
   522             pairself (strip_comb o unfold_outer_the_binders) (t1, t2)
   523           val max_depth = max_depth - (if member (op =) coTs T then 1 else 0)
   524         in
   525           head1 = head2
   526           andalso forall (bisimilar_values coTs max_depth) (args1 ~~ args2)
   527         end
   528       else
   529         t1 = t2
   530     end
   531 
   532 (* params -> scope -> (term option * int list) list -> styp list -> nut list
   533   -> nut list -> nut list -> nut NameTable.table -> Kodkod.raw_bound list
   534   -> Pretty.T * bool *)
   535 fun reconstruct_hol_model {show_skolems, show_datatypes, show_consts}
   536         ({ext_ctxt as {thy, ctxt, max_bisim_depth, boxes, user_axioms, debug,
   537                        wfs, destroy_constrs, specialize, skolemize,
   538                        star_linear_preds, uncurry, fast_descrs, tac_timeout,
   539                        evals, case_names, def_table, nondef_table, user_nondefs,
   540                        simp_table, psimp_table, intro_table, ground_thm_table,
   541                        ersatz_table, skolems, special_funs, unrolled_preds,
   542                        wf_cache, constr_cache},
   543          card_assigns, bisim_depth, datatypes, ofs} : scope) formats all_frees
   544         free_names sel_names nonsel_names rel_table bounds =
   545   let
   546     val (wacky_names as (_, base_name, step_name, _), ctxt) =
   547       add_wacky_syntax ctxt
   548     val ext_ctxt =
   549       {thy = thy, ctxt = ctxt, max_bisim_depth = max_bisim_depth, boxes = boxes,
   550        wfs = wfs, user_axioms = user_axioms, debug = debug,
   551        destroy_constrs = destroy_constrs, specialize = specialize,
   552        skolemize = skolemize, star_linear_preds = star_linear_preds,
   553        uncurry = uncurry, fast_descrs = fast_descrs, tac_timeout = tac_timeout,
   554        evals = evals, case_names = case_names, def_table = def_table,
   555        nondef_table = nondef_table, user_nondefs = user_nondefs,
   556        simp_table = simp_table, psimp_table = psimp_table,
   557        intro_table = intro_table, ground_thm_table = ground_thm_table,
   558        ersatz_table = ersatz_table, skolems = skolems,
   559        special_funs = special_funs, unrolled_preds = unrolled_preds,
   560        wf_cache = wf_cache, constr_cache = constr_cache}
   561     val scope = {ext_ctxt = ext_ctxt, card_assigns = card_assigns,
   562                  bisim_depth = bisim_depth, datatypes = datatypes, ofs = ofs}
   563     (* typ -> typ -> rep -> int list list -> term *)
   564     val term_for_rep = reconstruct_term wacky_names scope sel_names rel_table
   565                                         bounds
   566     (* typ -> typ -> typ *)
   567     fun nth_value_of_type T card n = term_for_rep T T (Atom (card, 0)) [[n]]
   568     (* dtype_spec list -> dtype_spec -> bool *)
   569     fun is_codatatype_wellformed (cos : dtype_spec list)
   570                                  ({typ, card, ...} : dtype_spec) =
   571       let
   572         val ts = map (nth_value_of_type typ card) (index_seq 0 card)
   573         val max_depth = Integer.sum (map #card cos)
   574       in
   575         forall (not o bisimilar_values (map #typ cos) max_depth)
   576                (all_distinct_unordered_pairs_of ts)
   577       end
   578     (* string -> Pretty.T *)
   579     fun pretty_for_assign name =
   580       let
   581         val (oper, (t1, T'), T) =
   582           case name of
   583             FreeName (s, T, _) =>
   584             let val t = Free (s, unbox_type T) in
   585               ("=", (t, format_term_type thy def_table formats t), T)
   586             end
   587           | ConstName (s, T, _) =>
   588             (assign_operator_for_const (s, T),
   589              user_friendly_const ext_ctxt (base_name, step_name) formats (s, T),
   590              T)
   591           | _ => raise NUT ("Nitpick_Model.reconstruct_hol_model.\
   592                             \pretty_for_assign", [name])
   593         val t2 = if rep_of name = Any then
   594                    Const (@{const_name undefined}, T')
   595                  else
   596                    tuple_list_for_name rel_table bounds name
   597                    |> term_for_rep T T' (rep_of name)
   598       in
   599         Pretty.block (Pretty.breaks
   600             [setmp_show_all_types (Syntax.pretty_term ctxt) t1,
   601              Pretty.str oper, Syntax.pretty_term ctxt t2])
   602       end
   603     (* dtype_spec -> Pretty.T *)
   604     fun pretty_for_datatype ({typ, card, precise, ...} : dtype_spec) =
   605       Pretty.block (Pretty.breaks
   606           [Syntax.pretty_typ ctxt (unbox_type typ), Pretty.str "=",
   607            Pretty.enum "," "{" "}"
   608                (map (Syntax.pretty_term ctxt o nth_value_of_type typ card)
   609                     (index_seq 0 card) @
   610                 (if precise then [] else [Pretty.str unrep]))])
   611     (* typ -> dtype_spec list *)
   612     fun integer_datatype T =
   613       [{typ = T, card = card_of_type card_assigns T, co = false,
   614         precise = false, shallow = false, constrs = []}]
   615       handle TYPE ("Nitpick_HOL.card_of_type", _, _) => []
   616     val (codatatypes, datatypes) =
   617       datatypes |> filter_out #shallow
   618                 |> List.partition #co
   619                 ||> append (integer_datatype nat_T @ integer_datatype int_T)
   620     val block_of_datatypes =
   621       if show_datatypes andalso not (null datatypes) then
   622         [Pretty.big_list ("Datatype" ^ plural_s_for_list datatypes ^ ":")
   623                          (map pretty_for_datatype datatypes)]
   624       else
   625         []
   626     val block_of_codatatypes =
   627       if show_datatypes andalso not (null codatatypes) then
   628         [Pretty.big_list ("Codatatype" ^ plural_s_for_list codatatypes ^ ":")
   629                          (map pretty_for_datatype codatatypes)]
   630       else
   631         []
   632     (* bool -> string -> nut list -> Pretty.T list *)
   633     fun block_of_names show title names =
   634       if show andalso not (null names) then
   635         Pretty.str (title ^ plural_s_for_list names ^ ":")
   636         :: map (Pretty.indent indent_size o pretty_for_assign)
   637                (sort_wrt (original_name o nickname_of) names)
   638       else
   639         []
   640     val (skolem_names, nonskolem_nonsel_names) =
   641       List.partition is_skolem_name nonsel_names
   642     val (eval_names, noneval_nonskolem_nonsel_names) =
   643       List.partition (String.isPrefix eval_prefix o nickname_of)
   644                      nonskolem_nonsel_names
   645       ||> filter_out (curry (op =) @{const_name bisim_iterator_max}
   646                       o nickname_of)
   647     val free_names =
   648       map (fn x as (s, T) =>
   649               case filter (curry (op =) x
   650                            o pairf nickname_of (unbox_type o type_of))
   651                           free_names of
   652                 [name] => name
   653               | [] => FreeName (s, T, Any)
   654               | _ => raise TERM ("Nitpick_Model.reconstruct_hol_model",
   655                                  [Const x])) all_frees
   656     val chunks = block_of_names true "Free variable" free_names @
   657                  block_of_names show_skolems "Skolem constant" skolem_names @
   658                  block_of_names true "Evaluated term" eval_names @
   659                  block_of_datatypes @ block_of_codatatypes @
   660                  block_of_names show_consts "Constant"
   661                                 noneval_nonskolem_nonsel_names
   662   in
   663     (Pretty.chunks (if null chunks then [Pretty.str "Empty assignment"]
   664                     else chunks),
   665      bisim_depth >= 0
   666      orelse forall (is_codatatype_wellformed codatatypes) codatatypes)
   667   end
   668 
   669 (* scope -> Time.time option -> nut list -> nut list -> nut NameTable.table
   670    -> Kodkod.raw_bound list -> term -> bool option *)
   671 fun prove_hol_model (scope as {ext_ctxt as {thy, ctxt, ...}, card_assigns, ...})
   672                     auto_timeout free_names sel_names rel_table bounds prop =
   673   let
   674     (* typ * int -> term *)
   675     fun free_type_assm (T, k) =
   676       let
   677         (* int -> term *)
   678         val atom = atom true T
   679         fun equation_for_atom j = HOLogic.eq_const T $ Bound 0 $ atom j
   680         val eqs = map equation_for_atom (index_seq 0 k)
   681         val compreh_assm =
   682           Const (@{const_name All}, (T --> bool_T) --> bool_T)
   683               $ Abs ("x", T, foldl1 HOLogic.mk_disj eqs)
   684         val distinct_assm = distinctness_formula T (map atom (index_seq 0 k))
   685       in HOLogic.mk_conj (compreh_assm, distinct_assm) end
   686     (* nut -> term *)
   687     fun free_name_assm name =
   688       HOLogic.mk_eq (Free (nickname_of name, type_of name),
   689                      term_for_name scope sel_names rel_table bounds name)
   690     val freeT_assms = map free_type_assm (filter (is_TFree o fst) card_assigns)
   691     val model_assms = map free_name_assm free_names
   692     val assm = List.foldr HOLogic.mk_conj @{const True}
   693                           (freeT_assms @ model_assms)
   694     (* bool -> bool *)
   695     fun try_out negate =
   696       let
   697         val concl = (negate ? curry (op $) @{const Not})
   698                     (ObjectLogic.atomize_term thy prop)
   699         val goal = HOLogic.mk_Trueprop (HOLogic.mk_imp (assm, concl))
   700                    |> map_types (map_type_tfree
   701                           (fn (s, []) => TFree (s, HOLogic.typeS)
   702                             | x => TFree x))
   703                    |> cterm_of thy |> Goal.init
   704       in
   705         (goal |> SINGLE (DETERM_TIMEOUT auto_timeout
   706                                         (auto_tac (clasimpset_of ctxt)))
   707               |> the |> Goal.finish ctxt; true)
   708         handle THM _ => false
   709              | TimeLimit.TimeOut => false
   710       end
   711   in
   712     if try_out false then SOME true
   713     else if try_out true then SOME false
   714     else NONE
   715   end
   716 
   717 end;