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