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