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