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