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