src/HOL/Tools/Nitpick/nitpick_model.ML
author blanchet
Tue Oct 06 09:27:31 2015 +0200 (2015-10-06)
changeset 61331 2007ea8615a2
parent 61324 d4ec7594f558
child 61333 24b5e7579fdd
permissions -rw-r--r--
avoid legacy syntax
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@33232
    10
  type scope = Nitpick_Scope.scope
blanchet@33232
    11
  type rep = Nitpick_Rep.rep
blanchet@33232
    12
  type nut = Nitpick_Nut.nut
blanchet@33192
    13
blanchet@36390
    14
  type params =
blanchet@55889
    15
    {show_types: bool,
blanchet@41993
    16
     show_skolems: bool,
blanchet@36390
    17
     show_consts: bool}
blanchet@36390
    18
blanchet@35712
    19
  type term_postprocessor =
blanchet@35712
    20
    Proof.context -> string -> (typ -> term list) -> typ -> term -> term
blanchet@33192
    21
blanchet@33192
    22
  structure NameTable : TABLE
blanchet@33192
    23
blanchet@35712
    24
  val irrelevant : string
blanchet@35712
    25
  val unknown : string
blanchet@35711
    26
  val register_term_postprocessor :
blanchet@38284
    27
    typ -> term_postprocessor -> morphism -> Context.generic -> Context.generic
blanchet@38240
    28
  val register_term_postprocessor_global :
blanchet@35711
    29
    typ -> term_postprocessor -> theory -> theory
blanchet@38284
    30
  val unregister_term_postprocessor :
blanchet@38284
    31
    typ -> morphism -> Context.generic -> Context.generic
blanchet@38240
    32
  val unregister_term_postprocessor_global : typ -> theory -> theory
blanchet@33192
    33
  val tuple_list_for_name :
blanchet@33192
    34
    nut NameTable.table -> Kodkod.raw_bound list -> nut -> int list list
blanchet@35712
    35
  val dest_plain_fun : term -> bool * (term list * term list)
blanchet@33192
    36
  val reconstruct_hol_model :
blanchet@37260
    37
    params -> scope -> (term option * int list) list
blanchet@55889
    38
    -> (typ option * string list) list -> (string * typ) list ->
blanchet@55889
    39
    (string * typ) list -> nut list -> nut list -> nut list ->
blanchet@55889
    40
    nut NameTable.table -> Kodkod.raw_bound list -> Pretty.T * bool
blanchet@33192
    41
end;
blanchet@33192
    42
blanchet@33232
    43
structure Nitpick_Model : NITPICK_MODEL =
blanchet@33192
    44
struct
blanchet@33192
    45
blanchet@33232
    46
open Nitpick_Util
blanchet@33232
    47
open Nitpick_HOL
blanchet@33232
    48
open Nitpick_Scope
blanchet@33232
    49
open Nitpick_Peephole
blanchet@33232
    50
open Nitpick_Rep
blanchet@33232
    51
open Nitpick_Nut
blanchet@33192
    52
blanchet@34126
    53
structure KK = Kodkod
blanchet@34126
    54
blanchet@36390
    55
type params =
blanchet@55889
    56
  {show_types: bool,
blanchet@41993
    57
   show_skolems: bool,
blanchet@36390
    58
   show_consts: bool}
blanchet@33192
    59
blanchet@35712
    60
type term_postprocessor =
blanchet@35712
    61
  Proof.context -> string -> (typ -> term list) -> typ -> term -> term
blanchet@35711
    62
wenzelm@41472
    63
structure Data = Generic_Data
wenzelm@41472
    64
(
blanchet@35711
    65
  type T = (typ * term_postprocessor) list
blanchet@35711
    66
  val empty = []
blanchet@35711
    67
  val extend = I
wenzelm@41472
    68
  fun merge data = AList.merge (op =) (K true) data
wenzelm@41472
    69
)
blanchet@35711
    70
blanchet@37261
    71
fun xsym s s' () = if print_mode_active Symbol.xsymbolsN then s else s'
blanchet@37261
    72
blanchet@35712
    73
val irrelevant = "_"
blanchet@33192
    74
val unknown = "?"
blanchet@61331
    75
val unrep_mixfix = xsym "\<dots>" "..."
blanchet@37261
    76
val maybe_mixfix = xsym "_\<^sup>?" "_?"
blanchet@37261
    77
val base_mixfix = xsym "_\<^bsub>base\<^esub>" "_.base"
blanchet@37261
    78
val step_mixfix = xsym "_\<^bsub>step\<^esub>" "_.step"
blanchet@37261
    79
val abs_mixfix = xsym "\<guillemotleft>_\<guillemotright>" "\"_\""
blanchet@35718
    80
val arg_var_prefix = "x"
blanchet@37261
    81
val cyclic_co_val_name = xsym "\<omega>" "w"
blanchet@37261
    82
val cyclic_const_prefix = xsym "\<xi>" "X"
blanchet@37261
    83
fun cyclic_type_name () = nitpick_prefix ^ cyclic_const_prefix ()
blanchet@34982
    84
val opt_flag = nitpick_prefix ^ "opt"
blanchet@34982
    85
val non_opt_flag = nitpick_prefix ^ "non_opt"
blanchet@33192
    86
blanchet@35076
    87
type atom_pool = ((string * int) * int list) list
blanchet@35076
    88
blanchet@35718
    89
fun add_wacky_syntax ctxt =
blanchet@35718
    90
  let
blanchet@35718
    91
    val name_of = fst o dest_Const
wenzelm@52696
    92
    val thy = Proof_Context.theory_of ctxt
blanchet@61331
    93
    val (unrep_s, thy) = thy
blanchet@61331
    94
      |> Sign.declare_const_global ((@{binding nitpick_unrep}, @{typ 'a}),
blanchet@61331
    95
        Mixfix (unrep_mixfix (), [], 1000))
blanchet@61331
    96
      |>> name_of
blanchet@61331
    97
    val (maybe_s, thy) = thy
blanchet@61331
    98
      |> Sign.declare_const_global ((@{binding nitpick_maybe}, @{typ "'a => 'a"}),
blanchet@61331
    99
        Mixfix (maybe_mixfix (), [1000], 1000))
blanchet@61331
   100
      |>> name_of
blanchet@61331
   101
    val (abs_s, thy) = thy
blanchet@61331
   102
      |> Sign.declare_const_global ((@{binding nitpick_abs}, @{typ "'a => 'b"}),
blanchet@61331
   103
        Mixfix (abs_mixfix (), [40], 40))
blanchet@61331
   104
      |>> name_of
blanchet@61331
   105
    val (base_s, thy) = thy
blanchet@61331
   106
      |> Sign.declare_const_global ((@{binding nitpick_base}, @{typ "'a => 'a"}),
blanchet@61331
   107
        Mixfix (base_mixfix (), [1000], 1000))
blanchet@61331
   108
      |>> name_of
blanchet@61331
   109
    val (step_s, thy) = thy
blanchet@61331
   110
      |> Sign.declare_const_global ((@{binding nitpick_step}, @{typ "'a => 'a"}),
blanchet@61331
   111
        Mixfix (step_mixfix (), [1000], 1000))
blanchet@61331
   112
      |>> name_of
blanchet@35718
   113
  in
blanchet@61331
   114
    (((unrep_s, maybe_s, abs_s), (base_s, step_s)),
wenzelm@55725
   115
     Proof_Context.transfer thy ctxt)
blanchet@35718
   116
  end
blanchet@35718
   117
blanchet@35718
   118
(** Term reconstruction **)
blanchet@35718
   119
blanchet@37260
   120
fun nth_atom_number pool T j =
blanchet@37260
   121
  case AList.lookup (op =) (!pool) T of
blanchet@37260
   122
    SOME js =>
blanchet@37260
   123
    (case find_index (curry (op =) j) js of
blanchet@37260
   124
       ~1 => (Unsynchronized.change pool (cons (T, j :: js));
blanchet@37260
   125
              length js + 1)
blanchet@37260
   126
     | n => length js - n)
blanchet@37260
   127
  | NONE => (Unsynchronized.change pool (cons (T, [j])); 1)
blanchet@55889
   128
blanchet@37260
   129
fun atom_suffix s =
blanchet@37260
   130
  nat_subscript
wenzelm@40627
   131
  #> (s <> "" andalso Symbol.is_ascii_digit (List.last (raw_explode s)))  (* FIXME Symbol.explode (?) *)
wenzelm@53015
   132
     ? prefix "\<^sub>,"
blanchet@55889
   133
blanchet@37260
   134
fun nth_atom_name thy atomss pool prefix T j =
blanchet@37260
   135
  let
blanchet@37260
   136
    val ss = these (triple_lookup (type_match thy) atomss T)
blanchet@37260
   137
    val m = nth_atom_number pool T j
blanchet@37260
   138
  in
blanchet@37260
   139
    if m <= length ss then
blanchet@37260
   140
      nth ss (m - 1)
blanchet@37260
   141
    else case T of
blanchet@37260
   142
      Type (s, _) =>
blanchet@37260
   143
      let val s' = shortest_name s in
blanchet@37260
   144
        prefix ^
blanchet@41039
   145
        (if T = @{typ string} then "s"
blanchet@41039
   146
         else if String.isPrefix "\\" s' then s'
blanchet@41039
   147
         else substring (s', 0, 1)) ^ atom_suffix s m
blanchet@37260
   148
      end
blanchet@37260
   149
    | TFree (s, _) => prefix ^ perhaps (try (unprefix "'")) s ^ atom_suffix s m
blanchet@37260
   150
    | _ => raise TYPE ("Nitpick_Model.nth_atom_name", [T], [])
blanchet@37260
   151
  end
blanchet@55889
   152
blanchet@37260
   153
fun nth_atom thy atomss pool for_auto T j =
blanchet@33192
   154
  if for_auto then
wenzelm@56220
   155
    Free (nth_atom_name thy atomss pool (hd (Long_Name.explode nitpick_prefix))
blanchet@37260
   156
                        T j, T)
blanchet@33192
   157
  else
blanchet@37260
   158
    Const (nth_atom_name thy atomss pool "" T j, T)
blanchet@33192
   159
blanchet@35177
   160
fun extract_real_number (Const (@{const_name divide}, _) $ t1 $ t2) =
blanchet@34126
   161
    real (snd (HOLogic.dest_number t1)) / real (snd (HOLogic.dest_number t2))
blanchet@34126
   162
  | extract_real_number t = real (snd (HOLogic.dest_number t))
blanchet@55889
   163
blanchet@34124
   164
fun nice_term_ord (Abs (_, _, t1), Abs (_, _, t2)) = nice_term_ord (t1, t2)
wenzelm@59058
   165
  | nice_term_ord tp = Real.compare (apply2 extract_real_number tp)
blanchet@34124
   166
    handle TERM ("dest_number", _) =>
blanchet@34126
   167
           case tp of
blanchet@34124
   168
             (t11 $ t12, t21 $ t22) =>
blanchet@34124
   169
             (case nice_term_ord (t11, t21) of
blanchet@34124
   170
                EQUAL => nice_term_ord (t12, t22)
blanchet@34124
   171
              | ord => ord)
wenzelm@35408
   172
           | _ => Term_Ord.fast_term_ord tp
blanchet@34124
   173
blanchet@38284
   174
fun register_term_postprocessor_generic T postproc =
blanchet@38284
   175
  Data.map (cons (T, postproc))
blanchet@55889
   176
blanchet@38284
   177
(* TODO: Consider morphism. *)
blanchet@38284
   178
fun register_term_postprocessor T postproc (_ : morphism) =
blanchet@38284
   179
  register_term_postprocessor_generic T postproc
blanchet@55889
   180
blanchet@38240
   181
val register_term_postprocessor_global =
blanchet@38240
   182
  Context.theory_map oo register_term_postprocessor_generic
blanchet@38240
   183
blanchet@38240
   184
fun unregister_term_postprocessor_generic T = Data.map (AList.delete (op =) T)
blanchet@38284
   185
(* TODO: Consider morphism. *)
blanchet@55889
   186
blanchet@38284
   187
fun unregister_term_postprocessor T (_ : morphism) =
blanchet@38284
   188
  unregister_term_postprocessor_generic T
blanchet@55889
   189
blanchet@38240
   190
val unregister_term_postprocessor_global =
blanchet@38240
   191
  Context.theory_map o unregister_term_postprocessor_generic
blanchet@35711
   192
blanchet@33192
   193
fun tuple_list_for_name rel_table bounds name =
blanchet@33192
   194
  the (AList.lookup (op =) bounds (the_rel rel_table name)) handle NUT _ => [[]]
blanchet@33192
   195
blanchet@41052
   196
fun unarize_unbox_etc_term (Const (@{const_name FunBox}, _) $ t1) =
blanchet@35665
   197
    unarize_unbox_etc_term t1
blanchet@35665
   198
  | unarize_unbox_etc_term
blanchet@35665
   199
        (Const (@{const_name PairBox},
blanchet@35665
   200
                Type (@{type_name fun}, [T1, Type (@{type_name fun}, [T2, _])]))
blanchet@35665
   201
         $ t1 $ t2) =
blanchet@35665
   202
    let val Ts = map uniterize_unarize_unbox_etc_type [T1, T2] in
blanchet@38190
   203
      Const (@{const_name Pair}, Ts ---> Type (@{type_name prod}, Ts))
blanchet@35665
   204
      $ unarize_unbox_etc_term t1 $ unarize_unbox_etc_term t2
blanchet@33192
   205
    end
blanchet@35665
   206
  | unarize_unbox_etc_term (Const (s, T)) =
blanchet@35665
   207
    Const (s, uniterize_unarize_unbox_etc_type T)
blanchet@35665
   208
  | unarize_unbox_etc_term (t1 $ t2) =
blanchet@35665
   209
    unarize_unbox_etc_term t1 $ unarize_unbox_etc_term t2
blanchet@35665
   210
  | unarize_unbox_etc_term (Free (s, T)) =
blanchet@35665
   211
    Free (s, uniterize_unarize_unbox_etc_type T)
blanchet@35665
   212
  | unarize_unbox_etc_term (Var (x, T)) =
blanchet@35665
   213
    Var (x, uniterize_unarize_unbox_etc_type T)
blanchet@35665
   214
  | unarize_unbox_etc_term (Bound j) = Bound j
blanchet@35665
   215
  | unarize_unbox_etc_term (Abs (s, T, t')) =
blanchet@35665
   216
    Abs (s, uniterize_unarize_unbox_etc_type T, unarize_unbox_etc_term t')
blanchet@33192
   217
blanchet@38190
   218
fun factor_out_types (T1 as Type (@{type_name prod}, [T11, T12]))
blanchet@38190
   219
                     (T2 as Type (@{type_name prod}, [T21, T22])) =
wenzelm@59058
   220
    let val (n1, n2) = apply2 num_factors_in_type (T11, T21) in
blanchet@33192
   221
      if n1 = n2 then
blanchet@33192
   222
        let
blanchet@33192
   223
          val ((T11', opt_T12'), (T21', opt_T22')) = factor_out_types T12 T22
blanchet@33192
   224
        in
blanchet@38190
   225
          ((Type (@{type_name prod}, [T11, T11']), opt_T12'),
blanchet@38190
   226
           (Type (@{type_name prod}, [T21, T21']), opt_T22'))
blanchet@33192
   227
        end
blanchet@33192
   228
      else if n1 < n2 then
blanchet@33192
   229
        case factor_out_types T1 T21 of
blanchet@33192
   230
          (p1, (T21', NONE)) => (p1, (T21', SOME T22))
blanchet@33192
   231
        | (p1, (T21', SOME T22')) =>
blanchet@38190
   232
          (p1, (T21', SOME (Type (@{type_name prod}, [T22', T22]))))
blanchet@33192
   233
      else
blanchet@33192
   234
        swap (factor_out_types T2 T1)
blanchet@33192
   235
    end
blanchet@38190
   236
  | factor_out_types (Type (@{type_name prod}, [T11, T12])) T2 =
blanchet@35665
   237
    ((T11, SOME T12), (T2, NONE))
blanchet@38190
   238
  | factor_out_types T1 (Type (@{type_name prod}, [T21, T22])) =
blanchet@35665
   239
    ((T1, NONE), (T21, SOME T22))
blanchet@33192
   240
  | factor_out_types T1 T2 = ((T1, NONE), (T2, NONE))
blanchet@33192
   241
blanchet@46083
   242
(* Term-encoded data structure for holding key-value pairs as well as an "opt"
blanchet@46083
   243
   flag indicating whether the function is approximated. *)
blanchet@33192
   244
fun make_plain_fun maybe_opt T1 T2 =
blanchet@33192
   245
  let
blanchet@33192
   246
    fun aux T1 T2 [] =
blanchet@34982
   247
        Const (if maybe_opt then opt_flag else non_opt_flag, T1 --> T2)
blanchet@35712
   248
      | aux T1 T2 ((t1, t2) :: tps) =
blanchet@34124
   249
        Const (@{const_name fun_upd}, (T1 --> T2) --> T1 --> T2 --> T1 --> T2)
blanchet@35712
   250
        $ aux T1 T2 tps $ t1 $ t2
blanchet@33192
   251
  in aux T1 T2 o rev end
blanchet@55889
   252
blanchet@34982
   253
fun is_plain_fun (Const (s, _)) = (s = opt_flag orelse s = non_opt_flag)
blanchet@33192
   254
  | is_plain_fun (Const (@{const_name fun_upd}, _) $ t0 $ _ $ _) =
blanchet@33192
   255
    is_plain_fun t0
blanchet@33192
   256
  | is_plain_fun _ = false
blanchet@33192
   257
val dest_plain_fun =
blanchet@33192
   258
  let
blanchet@35712
   259
    fun aux (Abs (_, _, Const (s, _))) = (s <> irrelevant, ([], []))
blanchet@35712
   260
      | aux (Const (s, _)) = (s <> non_opt_flag, ([], []))
blanchet@33192
   261
      | aux (Const (@{const_name fun_upd}, _) $ t0 $ t1 $ t2) =
blanchet@35712
   262
        let val (maybe_opt, (ts1, ts2)) = aux t0 in
blanchet@35712
   263
          (maybe_opt, (t1 :: ts1, t2 :: ts2))
blanchet@35712
   264
        end
blanchet@33232
   265
      | aux t = raise TERM ("Nitpick_Model.dest_plain_fun", [t])
wenzelm@59058
   266
  in apsnd (apply2 rev) o aux end
blanchet@33192
   267
blanchet@33565
   268
fun break_in_two T T1 T2 t =
blanchet@33565
   269
  let
blanchet@33565
   270
    val ps = HOLogic.flat_tupleT_paths T
blanchet@33565
   271
    val cut = length (HOLogic.strip_tupleT T1)
wenzelm@59058
   272
    val (ps1, ps2) = apply2 HOLogic.flat_tupleT_paths (T1, T2)
blanchet@33565
   273
    val (ts1, ts2) = t |> HOLogic.strip_ptuple ps |> chop cut
blanchet@33565
   274
  in (HOLogic.mk_ptuple ps1 T1 ts1, HOLogic.mk_ptuple ps2 T2 ts2) end
blanchet@55889
   275
blanchet@38190
   276
fun pair_up (Type (@{type_name prod}, [T1', T2']))
blanchet@33192
   277
            (t1 as Const (@{const_name Pair},
blanchet@35665
   278
                          Type (@{type_name fun},
blanchet@35665
   279
                                [_, Type (@{type_name fun}, [_, T1])]))
blanchet@35665
   280
             $ t11 $ t12) t2 =
blanchet@33192
   281
    if T1 = T1' then HOLogic.mk_prod (t1, t2)
blanchet@33192
   282
    else HOLogic.mk_prod (t11, pair_up T2' t12 t2)
blanchet@33192
   283
  | pair_up _ t1 t2 = HOLogic.mk_prod (t1, t2)
blanchet@55889
   284
blanchet@33192
   285
fun multi_pair_up T1 t1 (ts2, ts3) = map2 (pair o pair_up T1 t1) ts2 ts3
blanchet@33192
   286
blanchet@46083
   287
fun format_fun T' T1 T2 t =
blanchet@46083
   288
  let
blanchet@46083
   289
    val T1' = pseudo_domain_type T'
blanchet@46083
   290
    val T2' = pseudo_range_type T'
blanchet@46083
   291
    fun do_curry T1 T1a T1b T2 t =
blanchet@46083
   292
      let
blanchet@46083
   293
        val (maybe_opt, tsp) = dest_plain_fun t
blanchet@46083
   294
        val tps =
blanchet@46083
   295
          tsp |>> map (break_in_two T1 T1a T1b)
blanchet@46083
   296
              |> uncurry (map2 (fn (t1a, t1b) => fn t2 => (t1a, (t1b, t2))))
blanchet@46083
   297
              |> AList.coalesce (op =)
blanchet@46083
   298
              |> map (apsnd (make_plain_fun maybe_opt T1b T2))
blanchet@46083
   299
      in make_plain_fun maybe_opt T1a (T1b --> T2) tps end
blanchet@46083
   300
    and do_uncurry T1 T2 t =
blanchet@46083
   301
      let
blanchet@46083
   302
        val (maybe_opt, tsp) = dest_plain_fun t
blanchet@46083
   303
        val tps =
blanchet@46083
   304
          tsp |> op ~~
blanchet@46083
   305
              |> maps (fn (t1, t2) =>
blanchet@46083
   306
                          multi_pair_up T1 t1 (snd (dest_plain_fun t2)))
blanchet@46083
   307
      in make_plain_fun maybe_opt T1 T2 tps end
blanchet@46083
   308
    and do_arrow T1' T2' _ _ (Const (s, _)) = Const (s, T1' --> T2')
blanchet@46083
   309
      | do_arrow T1' T2' T1 T2
blanchet@46083
   310
                 (Const (@{const_name fun_upd}, _) $ t0 $ t1 $ t2) =
blanchet@46083
   311
        Const (@{const_name fun_upd},
blanchet@46083
   312
               (T1' --> T2') --> T1' --> T2' --> T1' --> T2')
blanchet@46083
   313
        $ do_arrow T1' T2' T1 T2 t0 $ do_term T1' T1 t1 $ do_term T2' T2 t2
blanchet@46083
   314
      | do_arrow _ _ _ _ t =
blanchet@46083
   315
        raise TERM ("Nitpick_Model.format_fun.do_arrow", [t])
blanchet@46083
   316
    and do_fun T1' T2' T1 T2 t =
blanchet@46083
   317
      case factor_out_types T1' T1 of
blanchet@46083
   318
        ((_, NONE), (_, NONE)) => t |> do_arrow T1' T2' T1 T2
blanchet@46083
   319
      | ((_, NONE), (T1a, SOME T1b)) =>
blanchet@46083
   320
        t |> do_curry T1 T1a T1b T2 |> do_arrow T1' T2' T1a (T1b --> T2)
blanchet@46083
   321
      | ((T1a', SOME T1b'), (_, NONE)) =>
blanchet@46083
   322
        t |> do_arrow T1a' (T1b' --> T2') T1 T2 |> do_uncurry T1' T2'
blanchet@46083
   323
      | _ => raise TYPE ("Nitpick_Model.format_fun.do_fun", [T1, T1'], [])
blanchet@46083
   324
    and do_term (Type (@{type_name fun}, [T1', T2']))
blanchet@46083
   325
                (Type (@{type_name fun}, [T1, T2])) t =
blanchet@46083
   326
        do_fun T1' T2' T1 T2 t
blanchet@46083
   327
      | do_term (T' as Type (@{type_name prod}, Ts' as [T1', T2']))
blanchet@46083
   328
                (Type (@{type_name prod}, [T1, T2]))
blanchet@46083
   329
                (Const (@{const_name Pair}, _) $ t1 $ t2) =
blanchet@46083
   330
        Const (@{const_name Pair}, Ts' ---> T')
blanchet@46083
   331
        $ do_term T1' T1 t1 $ do_term T2' T2 t2
blanchet@46083
   332
      | do_term T' T t =
blanchet@46083
   333
        if T = T' then t
blanchet@46083
   334
        else raise TYPE ("Nitpick_Model.format_fun.do_term", [T, T'], [])
blanchet@46083
   335
  in if T1' = T1 andalso T2' = T2 then t else do_fun T1' T2' T1 T2 t end
blanchet@33192
   336
blanchet@33192
   337
fun truth_const_sort_key @{const True} = "0"
blanchet@33192
   338
  | truth_const_sort_key @{const False} = "2"
blanchet@33192
   339
  | truth_const_sort_key _ = "1"
blanchet@33192
   340
blanchet@38190
   341
fun mk_tuple (Type (@{type_name prod}, [T1, T2])) ts =
blanchet@33192
   342
    HOLogic.mk_prod (mk_tuple T1 ts,
blanchet@33192
   343
        mk_tuple T2 (List.drop (ts, length (HOLogic.flatten_tupleT T1))))
blanchet@33192
   344
  | mk_tuple _ (t :: _) = t
blanchet@34124
   345
  | mk_tuple T [] = raise TYPE ("Nitpick_Model.mk_tuple", [T], [])
blanchet@33192
   346
blanchet@38240
   347
fun varified_type_match ctxt (candid_T, pat_T) =
wenzelm@42361
   348
  let val thy = Proof_Context.theory_of ctxt in
blanchet@38240
   349
    strict_type_match thy (candid_T, varify_type ctxt pat_T)
blanchet@38240
   350
  end
blanchet@35711
   351
blanchet@35712
   352
fun all_values_of_type pool wacky_names (scope as {card_assigns, ...} : scope)
blanchet@37260
   353
                       atomss sel_names rel_table bounds card T =
blanchet@35712
   354
  let
blanchet@35712
   355
    val card = if card = 0 then card_of_type card_assigns T else card
blanchet@35712
   356
    fun nth_value_of_type n =
blanchet@35712
   357
      let
blanchet@35712
   358
        fun term unfold =
blanchet@37262
   359
          reconstruct_term true unfold pool wacky_names scope atomss sel_names
blanchet@37260
   360
                           rel_table bounds T T (Atom (card, 0)) [[n]]
blanchet@35712
   361
      in
blanchet@35712
   362
        case term false of
blanchet@35712
   363
          t as Const (s, _) =>
blanchet@37261
   364
          if String.isPrefix (cyclic_const_prefix ()) s then
blanchet@35712
   365
            HOLogic.mk_eq (t, term true)
blanchet@35712
   366
          else
blanchet@35712
   367
            t
blanchet@35712
   368
        | t => t
blanchet@35712
   369
      end
blanchet@35712
   370
  in index_seq 0 card |> map nth_value_of_type |> sort nice_term_ord end
blanchet@37262
   371
and reconstruct_term maybe_opt unfold pool
blanchet@61331
   372
        (wacky_names as ((unrep_name, maybe_name, abs_name), _))
blanchet@55888
   373
        (scope as {hol_ctxt as {thy, ctxt, ...}, binarize, card_assigns, bits,
blanchet@55890
   374
                   data_types, ofs, ...})
blanchet@37260
   375
        atomss sel_names rel_table bounds =
blanchet@33192
   376
  let
blanchet@33192
   377
    val for_auto = (maybe_name = "")
blanchet@34124
   378
    fun value_of_bits jss =
blanchet@34124
   379
      let
blanchet@34124
   380
        val j0 = offset_of_type ofs @{typ unsigned_bit}
blanchet@34124
   381
        val js = map (Integer.add (~ j0) o the_single) jss
blanchet@34124
   382
      in
blanchet@34124
   383
        fold (fn j => Integer.add (reasonable_power 2 j |> j = bits ? op ~))
blanchet@34124
   384
             js 0
blanchet@34124
   385
      end
blanchet@35712
   386
    val all_values =
blanchet@37260
   387
      all_values_of_type pool wacky_names scope atomss sel_names rel_table
blanchet@37260
   388
                         bounds 0
blanchet@35712
   389
    fun postprocess_term (Type (@{type_name fun}, _)) = I
blanchet@35712
   390
      | postprocess_term T =
blanchet@38240
   391
        case Data.get (Context.Proof ctxt) of
blanchet@38240
   392
          [] => I
blanchet@38240
   393
        | postprocs =>
blanchet@38240
   394
          case AList.lookup (varified_type_match ctxt) postprocs T of
blanchet@38240
   395
            SOME postproc => postproc ctxt maybe_name all_values T
blanchet@38240
   396
          | NONE => I
blanchet@35712
   397
    fun postprocess_subterms Ts (t1 $ t2) =
blanchet@35712
   398
        let val t = postprocess_subterms Ts t1 $ postprocess_subterms Ts t2 in
blanchet@35712
   399
          postprocess_term (fastype_of1 (Ts, t)) t
blanchet@35712
   400
        end
blanchet@35712
   401
      | postprocess_subterms Ts (Abs (s, T, t')) =
blanchet@35712
   402
        Abs (s, T, postprocess_subterms (T :: Ts) t')
blanchet@35712
   403
      | postprocess_subterms Ts t = postprocess_term (fastype_of1 (Ts, t)) t
blanchet@46083
   404
    fun make_set maybe_opt T tps =
blanchet@33192
   405
      let
blanchet@46097
   406
        val set_T = HOLogic.mk_setT T
blanchet@46097
   407
        val empty_const = Const (@{const_abbrev Set.empty}, set_T)
blanchet@46097
   408
        val insert_const = Const (@{const_name insert}, T --> set_T --> set_T)
blanchet@33192
   409
        fun aux [] =
blanchet@55890
   410
            if maybe_opt andalso not (is_complete_type data_types false T) then
blanchet@61331
   411
              insert_const $ Const (unrep_name, T) $ empty_const
blanchet@33192
   412
            else
blanchet@33192
   413
              empty_const
blanchet@33192
   414
          | aux ((t1, t2) :: zs) =
blanchet@35388
   415
            aux zs
blanchet@35388
   416
            |> t2 <> @{const False}
blanchet@35388
   417
               ? curry (op $)
blanchet@35388
   418
                       (insert_const
blanchet@35388
   419
                        $ (t1 |> t2 <> @{const True}
blanchet@35388
   420
                                 ? curry (op $)
blanchet@46083
   421
                                         (Const (maybe_name, T --> T))))
blanchet@35388
   422
      in
blanchet@35388
   423
        if forall (fn (_, t) => t <> @{const True} andalso t <> @{const False})
blanchet@35388
   424
                  tps then
blanchet@46097
   425
          Const (unknown, set_T)
blanchet@35388
   426
        else
blanchet@35388
   427
          aux tps
blanchet@35388
   428
      end
blanchet@35665
   429
    fun make_map maybe_opt T1 T2 T2' =
blanchet@33192
   430
      let
blanchet@33192
   431
        val update_const = Const (@{const_name fun_upd},
blanchet@34124
   432
                                  (T1 --> T2) --> T1 --> T2 --> T1 --> T2)
wenzelm@35402
   433
        fun aux' [] = Const (@{const_abbrev Map.empty}, T1 --> T2)
blanchet@35712
   434
          | aux' ((t1, t2) :: tps) =
blanchet@33192
   435
            (case t2 of
blanchet@35712
   436
               Const (@{const_name None}, _) => aux' tps
blanchet@35712
   437
             | _ => update_const $ aux' tps $ t1 $ t2)
blanchet@35712
   438
        fun aux tps =
blanchet@55890
   439
          if maybe_opt andalso not (is_complete_type data_types false T1) then
blanchet@61331
   440
            update_const $ aux' tps $ Const (unrep_name, T1)
blanchet@33192
   441
            $ (Const (@{const_name Some}, T2' --> T2) $ Const (unknown, T2'))
blanchet@33192
   442
          else
blanchet@35712
   443
            aux' tps
blanchet@33192
   444
      in aux end
blanchet@34982
   445
    fun polish_funs Ts t =
blanchet@33192
   446
      (case fastype_of1 (Ts, t) of
blanchet@35665
   447
         Type (@{type_name fun}, [T1, T2]) =>
blanchet@33192
   448
         if is_plain_fun t then
blanchet@33192
   449
           case T2 of
blanchet@46083
   450
             Type (@{type_name option}, [T2']) =>
blanchet@33192
   451
             let
blanchet@35665
   452
               val (maybe_opt, ts_pair) =
wenzelm@59058
   453
                 dest_plain_fun t ||> apply2 (map (polish_funs Ts))
blanchet@35665
   454
             in make_map maybe_opt T1 T2 T2' (rev (op ~~ ts_pair)) end
blanchet@33192
   455
           | _ => raise SAME ()
blanchet@33192
   456
         else
blanchet@33192
   457
           raise SAME ()
blanchet@33192
   458
       | _ => raise SAME ())
blanchet@33192
   459
      handle SAME () =>
blanchet@33192
   460
             case t of
blanchet@34982
   461
               (t1 as Const (@{const_name fun_upd}, _) $ t11 $ _)
blanchet@34982
   462
               $ (t2 as Const (s, _)) =>
blanchet@34982
   463
               if s = unknown then polish_funs Ts t11
blanchet@34982
   464
               else polish_funs Ts t1 $ polish_funs Ts t2
blanchet@34982
   465
             | t1 $ t2 => polish_funs Ts t1 $ polish_funs Ts t2
blanchet@34982
   466
             | Abs (s, T, t') => Abs (s, T, polish_funs (T :: Ts) t')
blanchet@35665
   467
             | Const (s, Type (@{type_name fun}, [T1, T2])) =>
blanchet@34982
   468
               if s = opt_flag orelse s = non_opt_flag then
blanchet@35712
   469
                 Abs ("x", T1,
blanchet@55890
   470
                      Const (if is_complete_type data_types false T1 then
blanchet@35712
   471
                               irrelevant
blanchet@35712
   472
                             else
blanchet@35712
   473
                               unknown, T2))
blanchet@34982
   474
               else
blanchet@34982
   475
                 t
blanchet@34982
   476
             | t => t
blanchet@46083
   477
    fun make_fun_or_set maybe_opt T T1 T2 T' ts1 ts2 =
blanchet@46083
   478
      ts1 ~~ ts2
wenzelm@59058
   479
      |> sort (nice_term_ord o apply2 fst)
blanchet@46083
   480
      |> (case T of
blanchet@46083
   481
            Type (@{type_name set}, _) =>
wenzelm@60924
   482
            sort_by (truth_const_sort_key o snd)
blanchet@46083
   483
            #> make_set maybe_opt T'
blanchet@46083
   484
          | _ =>
blanchet@46083
   485
            make_plain_fun maybe_opt T1 T2
blanchet@46083
   486
            #> unarize_unbox_etc_term
blanchet@46083
   487
            #> format_fun (uniterize_unarize_unbox_etc_type T')
blanchet@46083
   488
                          (uniterize_unarize_unbox_etc_type T1)
blanchet@46083
   489
                          (uniterize_unarize_unbox_etc_type T2))
blanchet@46112
   490
blanchet@46112
   491
    fun term_for_fun_or_set seen T T' j =
blanchet@33192
   492
        let
blanchet@46112
   493
          val k1 = card_of_type card_assigns (pseudo_domain_type T)
blanchet@46112
   494
          val k2 = card_of_type card_assigns (pseudo_range_type T)
blanchet@33192
   495
        in
blanchet@35665
   496
          term_for_rep true seen T T' (Vect (k1, Atom (k2, 0)))
blanchet@33192
   497
                       [nth_combination (replicate k1 (k2, 0)) j]
blanchet@33192
   498
          handle General.Subscript =>
blanchet@46112
   499
                 raise ARG ("Nitpick_Model.reconstruct_term.\
blanchet@46112
   500
                            \term_for_fun_or_set",
blanchet@33192
   501
                            signed_string_of_int j ^ " for " ^
blanchet@33192
   502
                            string_for_rep (Vect (k1, Atom (k2, 0))))
blanchet@33192
   503
        end
blanchet@46112
   504
    and term_for_atom seen (T as Type (@{type_name fun}, _)) T' j _ =
blanchet@46112
   505
        term_for_fun_or_set seen T T' j
blanchet@46112
   506
      | term_for_atom seen (T as Type (@{type_name set}, _)) T' j _ =
blanchet@46112
   507
        term_for_fun_or_set seen T T' j
blanchet@38190
   508
      | term_for_atom seen (Type (@{type_name prod}, [T1, T2])) _ j k =
blanchet@35075
   509
        let
blanchet@35075
   510
          val k1 = card_of_type card_assigns T1
blanchet@35075
   511
          val k2 = k div k1
blanchet@35075
   512
        in
blanchet@33192
   513
          list_comb (HOLogic.pair_const T1 T2,
wenzelm@58634
   514
                     @{map 3} (fn T => term_for_atom seen T T) [T1, T2]
blanchet@46112
   515
                          (* ### k2 or k1? FIXME *)
blanchet@46112
   516
                          [j div k2, j mod k2] [k1, k2])
blanchet@33192
   517
        end
blanchet@35075
   518
      | term_for_atom seen @{typ prop} _ j k =
blanchet@35075
   519
        HOLogic.mk_Trueprop (term_for_atom seen bool_T bool_T j k)
blanchet@35075
   520
      | term_for_atom _ @{typ bool} _ j _ =
blanchet@33192
   521
        if j = 0 then @{const False} else @{const True}
blanchet@35075
   522
      | term_for_atom seen T _ j k =
blanchet@55888
   523
        if T = nat_T then
blanchet@33192
   524
          HOLogic.mk_number nat_T j
blanchet@33192
   525
        else if T = int_T then
blanchet@35075
   526
          HOLogic.mk_number int_T (int_for_atom (k, 0) j)
blanchet@33192
   527
        else if is_fp_iterator_type T then
blanchet@35075
   528
          HOLogic.mk_number nat_T (k - j - 1)
blanchet@33192
   529
        else if T = @{typ bisim_iterator} then
blanchet@33192
   530
          HOLogic.mk_number nat_T j
blanchet@55890
   531
        else case data_type_spec data_types T of
blanchet@37260
   532
          NONE => nth_atom thy atomss pool for_auto T j
blanchet@37260
   533
        | SOME {deep = false, ...} => nth_atom thy atomss pool for_auto T j
blanchet@55888
   534
        | SOME {co, constrs, ...} =>
blanchet@33192
   535
          let
blanchet@33192
   536
            fun tuples_for_const (s, T) =
blanchet@33192
   537
              tuple_list_for_name rel_table bounds (ConstName (s, T, Any))
blanchet@35180
   538
            fun cyclic_atom () =
blanchet@37261
   539
              nth_atom thy atomss pool for_auto (Type (cyclic_type_name (), []))
blanchet@37261
   540
                       j
blanchet@37260
   541
            fun cyclic_var () =
blanchet@37260
   542
              Var ((nth_atom_name thy atomss pool "" T j, 0), T)
blanchet@33192
   543
            val discr_jsss = map (tuples_for_const o discr_for_constr o #const)
blanchet@33192
   544
                                 constrs
blanchet@33192
   545
            val real_j = j + offset_of_type ofs T
blanchet@33192
   546
            val constr_x as (constr_s, constr_T) =
blanchet@33192
   547
              get_first (fn (jss, {const, ...}) =>
blanchet@34121
   548
                            if member (op =) jss [real_j] then SOME const
blanchet@34121
   549
                            else NONE)
blanchet@33192
   550
                        (discr_jsss ~~ constrs) |> the
blanchet@33192
   551
            val arg_Ts = curried_binder_types constr_T
blanchet@35190
   552
            val sel_xs =
blanchet@35190
   553
              map (binarized_and_boxed_nth_sel_for_constr hol_ctxt binarize
blanchet@35190
   554
                                                          constr_x)
blanchet@35190
   555
                  (index_seq 0 (length arg_Ts))
blanchet@33192
   556
            val sel_Rs =
blanchet@33192
   557
              map (fn x => get_first
blanchet@33192
   558
                               (fn ConstName (s', T', R) =>
blanchet@33192
   559
                                   if (s', T') = x then SOME R else NONE
blanchet@33232
   560
                                 | u => raise NUT ("Nitpick_Model.reconstruct_\
blanchet@33192
   561
                                                   \term.term_for_atom", [u]))
blanchet@33192
   562
                               sel_names |> the) sel_xs
blanchet@33192
   563
            val arg_Rs = map (snd o dest_Func) sel_Rs
blanchet@33192
   564
            val sel_jsss = map tuples_for_const sel_xs
blanchet@33192
   565
            val arg_jsss =
blanchet@33192
   566
              map (map_filter (fn js => if hd js = real_j then SOME (tl js)
blanchet@33192
   567
                                        else NONE)) sel_jsss
blanchet@33192
   568
            val uncur_arg_Ts = binder_types constr_T
blanchet@33192
   569
          in
blanchet@55888
   570
            if co andalso not (null seen) andalso
blanchet@35188
   571
               member (op =) (seen |> unfold ? (fst o split_last)) (T, j) then
blanchet@35180
   572
              cyclic_var ()
blanchet@34124
   573
            else if constr_s = @{const_name Word} then
blanchet@34124
   574
              HOLogic.mk_number
blanchet@34124
   575
                  (if T = @{typ "unsigned_bit word"} then nat_T else int_T)
blanchet@34124
   576
                  (value_of_bits (the_single arg_jsss))
blanchet@33192
   577
            else
blanchet@33192
   578
              let
blanchet@55888
   579
                val seen = seen |> co ? cons (T, j)
blanchet@33192
   580
                val ts =
blanchet@33192
   581
                  if length arg_Ts = 0 then
blanchet@33192
   582
                    []
blanchet@33192
   583
                  else
wenzelm@58634
   584
                    @{map 3} (fn Ts => term_for_rep true seen Ts Ts) arg_Ts arg_Rs
blanchet@41052
   585
                         arg_jsss
blanchet@33192
   586
                    |> mk_tuple (HOLogic.mk_tupleT uncur_arg_Ts)
blanchet@33192
   587
                    |> dest_n_tuple (length uncur_arg_Ts)
blanchet@33192
   588
                val t =
blanchet@61324
   589
                  if constr_s = @{const_name Abs_Frac} then
blanchet@35711
   590
                    case ts of
blanchet@35711
   591
                      [Const (@{const_name Pair}, _) $ t1 $ t2] =>
blanchet@35711
   592
                      frac_from_term_pair (body_type T) t1 t2
blanchet@35711
   593
                    | _ => raise TERM ("Nitpick_Model.reconstruct_term.\
blanchet@35711
   594
                                       \term_for_atom (Abs_Frac)", ts)
blanchet@34936
   595
                  else if not for_auto andalso
blanchet@37256
   596
                          (is_abs_fun ctxt constr_x orelse
blanchet@34936
   597
                           constr_s = @{const_name Quot}) then
blanchet@33192
   598
                    Const (abs_name, constr_T) $ the_single ts
blanchet@33192
   599
                  else
blanchet@33192
   600
                    list_comb (Const constr_x, ts)
blanchet@33192
   601
              in
blanchet@55888
   602
                if co then
blanchet@35180
   603
                  let val var = cyclic_var () in
blanchet@55888
   604
                    if exists_subterm (curry (op =) var) t then
blanchet@35179
   605
                      if co then
blanchet@35179
   606
                        Const (@{const_name The}, (T --> bool_T) --> T)
blanchet@37261
   607
                        $ Abs (cyclic_co_val_name (), T,
haftmann@38864
   608
                               Const (@{const_name HOL.eq}, T --> T --> bool_T)
blanchet@35180
   609
                               $ Bound 0 $ abstract_over (var, t))
blanchet@35179
   610
                      else
blanchet@35180
   611
                        cyclic_atom ()
blanchet@33192
   612
                    else
blanchet@33192
   613
                      t
blanchet@33192
   614
                  end
blanchet@33192
   615
                else
blanchet@33192
   616
                  t
blanchet@33192
   617
              end
blanchet@33192
   618
          end
blanchet@46083
   619
    and term_for_vect seen k R T T' js =
blanchet@46083
   620
      let
blanchet@46083
   621
        val T1 = pseudo_domain_type T
blanchet@46083
   622
        val T2 = pseudo_range_type T
blanchet@46083
   623
      in
blanchet@46083
   624
        make_fun_or_set true T T1 T2 T'
blanchet@46083
   625
            (map (fn j => term_for_atom seen T1 T1 j k) (index_seq 0 k))
blanchet@46083
   626
            (map (term_for_rep true seen T2 T2 R o single)
blanchet@48323
   627
                 (chunk_list (arity_of_rep R) js))
blanchet@46083
   628
      end
blanchet@38190
   629
    and term_for_rep _ seen T T' (R as Atom (k, j0)) [[j]] =
blanchet@35075
   630
        if j >= j0 andalso j < j0 + k then term_for_atom seen T T' (j - j0) k
blanchet@33232
   631
        else raise REP ("Nitpick_Model.reconstruct_term.term_for_rep", [R])
blanchet@38190
   632
      | term_for_rep _ seen (Type (@{type_name prod}, [T1, T2])) _
blanchet@35665
   633
                     (Struct [R1, R2]) [js] =
blanchet@33192
   634
        let
blanchet@33192
   635
          val arity1 = arity_of_rep R1
blanchet@33192
   636
          val (js1, js2) = chop arity1 js
blanchet@33192
   637
        in
blanchet@33192
   638
          list_comb (HOLogic.pair_const T1 T2,
wenzelm@58634
   639
                     @{map 3} (fn T => term_for_rep true seen T T) [T1, T2] [R1, R2]
blanchet@33192
   640
                          [[js1], [js2]])
blanchet@33192
   641
        end
blanchet@46083
   642
      | term_for_rep _ seen T T' (Vect (k, R')) [js] =
blanchet@46083
   643
        term_for_vect seen k R' T T' js
blanchet@46083
   644
      | term_for_rep maybe_opt seen T T' (Func (R1, Formula Neut)) jss =
blanchet@33192
   645
        let
blanchet@46083
   646
          val T1 = pseudo_domain_type T
blanchet@46083
   647
          val T2 = pseudo_range_type T
blanchet@33192
   648
          val jss1 = all_combinations_for_rep R1
blanchet@35665
   649
          val ts1 = map (term_for_rep true seen T1 T1 R1 o single) jss1
blanchet@33192
   650
          val ts2 =
blanchet@35665
   651
            map (fn js => term_for_rep true seen T2 T2 (Atom (2, 0))
blanchet@35385
   652
                                       [[int_from_bool (member (op =) jss js)]])
blanchet@34121
   653
                jss1
blanchet@46083
   654
        in make_fun_or_set maybe_opt T T1 T2 T' ts1 ts2 end
blanchet@46083
   655
      | term_for_rep maybe_opt seen T T' (Func (R1, R2)) jss =
blanchet@33192
   656
        let
blanchet@46083
   657
          val T1 = pseudo_domain_type T
blanchet@46083
   658
          val T2 = pseudo_range_type T
blanchet@33192
   659
          val arity1 = arity_of_rep R1
blanchet@33192
   660
          val jss1 = all_combinations_for_rep R1
blanchet@35665
   661
          val ts1 = map (term_for_rep false seen T1 T1 R1 o single) jss1
blanchet@33192
   662
          val grouped_jss2 = AList.group (op =) (map (chop arity1) jss)
blanchet@35665
   663
          val ts2 = map (term_for_rep false seen T2 T2 R2 o the_default []
blanchet@33192
   664
                         o AList.lookup (op =) grouped_jss2) jss1
blanchet@46083
   665
        in make_fun_or_set maybe_opt T T1 T2 T' ts1 ts2 end
blanchet@35665
   666
      | term_for_rep _ seen T T' (Opt R) jss =
blanchet@35665
   667
        if null jss then Const (unknown, T)
blanchet@35665
   668
        else term_for_rep true seen T T' R jss
blanchet@35665
   669
      | term_for_rep _ _ T _ R jss =
blanchet@33232
   670
        raise ARG ("Nitpick_Model.reconstruct_term.term_for_rep",
blanchet@37260
   671
                   Syntax.string_of_typ ctxt T ^ " " ^ string_for_rep R ^ " " ^
blanchet@33192
   672
                   string_of_int (length jss))
blanchet@35712
   673
  in
blanchet@35712
   674
    postprocess_subterms [] o polish_funs [] o unarize_unbox_etc_term
blanchet@37262
   675
    oooo term_for_rep maybe_opt []
blanchet@35712
   676
  end
blanchet@33192
   677
blanchet@35718
   678
(** Constant postprocessing **)
blanchet@35718
   679
blanchet@35718
   680
fun dest_n_tuple_type 1 T = [T]
blanchet@35718
   681
  | dest_n_tuple_type n (Type (_, [T1, T2])) =
blanchet@35718
   682
    T1 :: dest_n_tuple_type (n - 1) T2
blanchet@35718
   683
  | dest_n_tuple_type _ T =
blanchet@35718
   684
    raise TYPE ("Nitpick_Model.dest_n_tuple_type", [T], [])
blanchet@35718
   685
blanchet@41791
   686
fun const_format thy def_tables (x as (s, T)) =
blanchet@35718
   687
  if String.isPrefix unrolled_prefix s then
blanchet@41791
   688
    const_format thy def_tables (original_name s, range_type T)
blanchet@35718
   689
  else if String.isPrefix skolem_prefix s then
blanchet@35718
   690
    let
blanchet@35718
   691
      val k = unprefix skolem_prefix s
blanchet@35718
   692
              |> strip_first_name_sep |> fst |> space_explode "@"
blanchet@35718
   693
              |> hd |> Int.fromString |> the
blanchet@35718
   694
    in [k, num_binder_types T - k] end
blanchet@35718
   695
  else if original_name s <> s then
blanchet@35718
   696
    [num_binder_types T]
blanchet@41791
   697
  else case def_of_const thy def_tables x of
blanchet@35718
   698
    SOME t' => if fixpoint_kind_of_rhs t' <> NoFp then
blanchet@35718
   699
                 let val k = length (strip_abs_vars t') in
blanchet@35718
   700
                   [k, num_binder_types T - k]
blanchet@35718
   701
                 end
blanchet@35718
   702
               else
blanchet@35718
   703
                 [num_binder_types T]
blanchet@35718
   704
  | NONE => [num_binder_types T]
blanchet@55889
   705
blanchet@35718
   706
fun intersect_formats _ [] = []
blanchet@35718
   707
  | intersect_formats [] _ = []
blanchet@35718
   708
  | intersect_formats ks1 ks2 =
wenzelm@59058
   709
    let val ((ks1', k1), (ks2', k2)) = apply2 split_last (ks1, ks2) in
blanchet@35718
   710
      intersect_formats (ks1' @ (if k1 > k2 then [k1 - k2] else []))
blanchet@35718
   711
                        (ks2' @ (if k2 > k1 then [k2 - k1] else [])) @
blanchet@35718
   712
      [Int.min (k1, k2)]
blanchet@35718
   713
    end
blanchet@35718
   714
blanchet@41791
   715
fun lookup_format thy def_tables formats t =
blanchet@35718
   716
  case AList.lookup (fn (SOME x, SOME y) =>
blanchet@35718
   717
                        (term_match thy) (x, y) | _ => false)
blanchet@35718
   718
                    formats (SOME t) of
blanchet@35718
   719
    SOME format => format
blanchet@35718
   720
  | NONE => let val format = the (AList.lookup (op =) formats NONE) in
blanchet@35718
   721
              case t of
blanchet@35718
   722
                Const x => intersect_formats format
blanchet@41791
   723
                                             (const_format thy def_tables x)
blanchet@35718
   724
              | _ => format
blanchet@35718
   725
            end
blanchet@35718
   726
blanchet@35718
   727
fun format_type default_format format T =
blanchet@35718
   728
  let
blanchet@35718
   729
    val T = uniterize_unarize_unbox_etc_type T
blanchet@35718
   730
    val format = format |> filter (curry (op <) 0)
blanchet@35718
   731
  in
blanchet@35718
   732
    if forall (curry (op =) 1) format then
blanchet@35718
   733
      T
blanchet@35718
   734
    else
blanchet@35718
   735
      let
blanchet@35718
   736
        val (binder_Ts, body_T) = strip_type T
blanchet@35718
   737
        val batched =
blanchet@35718
   738
          binder_Ts
blanchet@35718
   739
          |> map (format_type default_format default_format)
blanchet@35718
   740
          |> rev |> chunk_list_unevenly (rev format)
blanchet@35718
   741
          |> map (HOLogic.mk_tupleT o rev)
blanchet@35718
   742
      in List.foldl (op -->) body_T batched end
blanchet@35718
   743
  end
blanchet@55889
   744
blanchet@41791
   745
fun format_term_type thy def_tables formats t =
blanchet@35718
   746
  format_type (the (AList.lookup (op =) formats NONE))
blanchet@41791
   747
              (lookup_format thy def_tables formats t) (fastype_of t)
blanchet@35718
   748
blanchet@35718
   749
fun repair_special_format js m format =
blanchet@35718
   750
  m - 1 downto 0 |> chunk_list_unevenly (rev format)
blanchet@35718
   751
                 |> map (rev o filter_out (member (op =) js))
blanchet@35718
   752
                 |> filter_out null |> map length |> rev
blanchet@35718
   753
blanchet@41791
   754
fun user_friendly_const ({thy, evals, def_tables, skolems, special_funs, ...}
blanchet@35718
   755
                         : hol_context) (base_name, step_name) formats =
blanchet@35718
   756
  let
blanchet@35718
   757
    val default_format = the (AList.lookup (op =) formats NONE)
blanchet@35718
   758
    fun do_const (x as (s, T)) =
blanchet@35718
   759
      (if String.isPrefix special_prefix s then
blanchet@35718
   760
         let
blanchet@35718
   761
           val do_term = map_aterms (fn Const x => fst (do_const x) | t' => t')
blanchet@35718
   762
           val (x' as (_, T'), js, ts) =
blanchet@35718
   763
             AList.find (op =) (!special_funs) (s, unarize_unbox_etc_type T)
blanchet@35718
   764
             |> the_single
blanchet@35718
   765
           val max_j = List.last js
blanchet@35718
   766
           val Ts = List.take (binder_types T', max_j + 1)
blanchet@35718
   767
           val missing_js = filter_out (member (op =) js) (0 upto max_j)
blanchet@35718
   768
           val missing_Ts = filter_indices missing_js Ts
blanchet@35718
   769
           fun nth_missing_var n =
blanchet@35718
   770
             ((arg_var_prefix ^ nat_subscript (n + 1), 0), nth missing_Ts n)
blanchet@35718
   771
           val missing_vars = map nth_missing_var (0 upto length missing_js - 1)
blanchet@35718
   772
           val vars = special_bounds ts @ missing_vars
blanchet@35718
   773
           val ts' =
blanchet@35718
   774
             map (fn j =>
blanchet@35718
   775
                     case AList.lookup (op =) (js ~~ ts) j of
blanchet@35718
   776
                       SOME t => do_term t
blanchet@35718
   777
                     | NONE =>
blanchet@35718
   778
                       Var (nth missing_vars
blanchet@35718
   779
                                (find_index (curry (op =) j) missing_js)))
blanchet@35718
   780
                 (0 upto max_j)
blanchet@35718
   781
           val t = do_const x' |> fst
blanchet@35718
   782
           val format =
blanchet@35718
   783
             case AList.lookup (fn (SOME t1, SOME t2) => term_match thy (t1, t2)
blanchet@35718
   784
                                 | _ => false) formats (SOME t) of
blanchet@35718
   785
               SOME format =>
blanchet@35718
   786
               repair_special_format js (num_binder_types T') format
blanchet@35718
   787
             | NONE =>
blanchet@41791
   788
               const_format thy def_tables x'
blanchet@35718
   789
               |> repair_special_format js (num_binder_types T')
blanchet@35718
   790
               |> intersect_formats default_format
blanchet@35718
   791
         in
blanchet@35718
   792
           (list_comb (t, ts') |> fold_rev abs_var vars,
blanchet@35718
   793
            format_type default_format format T)
blanchet@35718
   794
         end
blanchet@35718
   795
       else if String.isPrefix uncurry_prefix s then
blanchet@35718
   796
         let
blanchet@35718
   797
           val (ss, s') = unprefix uncurry_prefix s
blanchet@35718
   798
                          |> strip_first_name_sep |>> space_explode "@"
blanchet@35718
   799
         in
blanchet@35718
   800
           if String.isPrefix step_prefix s' then
blanchet@35718
   801
             do_const (s', T)
blanchet@35718
   802
           else
blanchet@35718
   803
             let
blanchet@35718
   804
               val k = the (Int.fromString (hd ss))
blanchet@35718
   805
               val j = the (Int.fromString (List.last ss))
blanchet@35718
   806
               val (before_Ts, (tuple_T, rest_T)) =
blanchet@35718
   807
                 strip_n_binders j T ||> (strip_n_binders 1 #>> hd)
blanchet@35718
   808
               val T' = before_Ts ---> dest_n_tuple_type k tuple_T ---> rest_T
blanchet@35718
   809
             in do_const (s', T') end
blanchet@35718
   810
         end
blanchet@35718
   811
       else if String.isPrefix unrolled_prefix s then
blanchet@35718
   812
         let val t = Const (original_name s, range_type T) in
blanchet@35718
   813
           (lambda (Free (iter_var_prefix, nat_T)) t,
blanchet@35718
   814
            format_type default_format
blanchet@41791
   815
                        (lookup_format thy def_tables formats t) T)
blanchet@35718
   816
         end
blanchet@35718
   817
       else if String.isPrefix base_prefix s then
blanchet@35718
   818
         (Const (base_name, T --> T) $ Const (unprefix base_prefix s, T),
blanchet@35718
   819
          format_type default_format default_format T)
blanchet@35718
   820
       else if String.isPrefix step_prefix s then
blanchet@35718
   821
         (Const (step_name, T --> T) $ Const (unprefix step_prefix s, T),
blanchet@35718
   822
          format_type default_format default_format T)
blanchet@35718
   823
       else if String.isPrefix quot_normal_prefix s then
blanchet@38207
   824
         let val t = Const (nitpick_prefix ^ "quotient normal form", T) in
blanchet@41791
   825
           (t, format_term_type thy def_tables formats t)
blanchet@35718
   826
         end
blanchet@35718
   827
       else if String.isPrefix skolem_prefix s then
blanchet@35718
   828
         let
blanchet@35718
   829
           val ss = the (AList.lookup (op =) (!skolems) s)
blanchet@35718
   830
           val (Ts, Ts') = chop (length ss) (binder_types T)
blanchet@35718
   831
           val frees = map Free (ss ~~ Ts)
blanchet@35718
   832
           val s' = original_name s
blanchet@35718
   833
         in
blanchet@35718
   834
           (fold lambda frees (Const (s', Ts' ---> T)),
blanchet@35718
   835
            format_type default_format
blanchet@41791
   836
                        (lookup_format thy def_tables formats (Const x)) T)
blanchet@35718
   837
         end
blanchet@35718
   838
       else if String.isPrefix eval_prefix s then
blanchet@35718
   839
         let
blanchet@35718
   840
           val t = nth evals (the (Int.fromString (unprefix eval_prefix s)))
blanchet@41791
   841
         in (t, format_term_type thy def_tables formats t) end
blanchet@35718
   842
       else
blanchet@45479
   843
         (* The selector case can occur in conjunction with fractional types.
blanchet@45479
   844
            It's not pretty. *)
blanchet@45479
   845
         let val t = Const (s |> not (is_sel s) ? original_name, T) in
blanchet@41791
   846
           (t, format_term_type thy def_tables formats t)
blanchet@35718
   847
         end)
blanchet@35718
   848
      |>> map_types uniterize_unarize_unbox_etc_type
blanchet@35718
   849
      |>> shorten_names_in_term |>> Term.map_abs_vars shortest_name
blanchet@35718
   850
  in do_const end
blanchet@35718
   851
blanchet@35718
   852
fun assign_operator_for_const (s, T) =
blanchet@35718
   853
  if String.isPrefix ubfp_prefix s then
blanchet@46104
   854
    xsym "\<le>" "<=" ()
blanchet@35718
   855
  else if String.isPrefix lbfp_prefix s then
blanchet@46104
   856
    xsym "\<ge>" ">=" ()
blanchet@35718
   857
  else if original_name s <> s then
blanchet@35718
   858
    assign_operator_for_const (strip_first_name_sep s |> snd, T)
blanchet@35718
   859
  else
blanchet@35718
   860
    "="
blanchet@35718
   861
blanchet@35718
   862
(** Model reconstruction **)
blanchet@35718
   863
blanchet@33192
   864
fun unfold_outer_the_binders (t as Const (@{const_name The}, _)
haftmann@38864
   865
                                   $ Abs (s, T, Const (@{const_name HOL.eq}, _)
blanchet@33192
   866
                                                $ Bound 0 $ t')) =
blanchet@33192
   867
    betapply (Abs (s, T, t'), t) |> unfold_outer_the_binders
blanchet@33192
   868
  | unfold_outer_the_binders t = t
blanchet@55889
   869
blanchet@33192
   870
fun bisimilar_values _ 0 _ = true
blanchet@33192
   871
  | bisimilar_values coTs max_depth (t1, t2) =
blanchet@33192
   872
    let val T = fastype_of t1 in
blanchet@33192
   873
      if exists_subtype (member (op =) coTs) T then
blanchet@33192
   874
        let
blanchet@33192
   875
          val ((head1, args1), (head2, args2)) =
wenzelm@59058
   876
            apply2 (strip_comb o unfold_outer_the_binders) (t1, t2)
blanchet@34121
   877
          val max_depth = max_depth - (if member (op =) coTs T then 1 else 0)
blanchet@33192
   878
        in
blanchet@34936
   879
          head1 = head2 andalso
blanchet@34936
   880
          forall (bisimilar_values coTs max_depth) (args1 ~~ args2)
blanchet@33192
   881
        end
blanchet@33192
   882
      else
blanchet@33192
   883
        t1 = t2
blanchet@33192
   884
    end
blanchet@33192
   885
blanchet@60193
   886
fun pretty_term_auto_global ctxt t0 =
blanchet@60139
   887
  let
blanchet@60193
   888
    val t = map_aterms (fn t as Const (s, _) =>
blanchet@60193
   889
      if s = irrelevant orelse s = unknown then Term.dummy else t | t => t) t0
blanchet@60193
   890
blanchet@60139
   891
    fun add_fake_const s =
blanchet@60139
   892
      Sign.declare_const_global ((Binding.name s, @{typ 'a}), NoSyn)
blanchet@60139
   893
      #> #2
blanchet@60139
   894
blanchet@60139
   895
    val globals = Term.add_const_names t []
blanchet@60139
   896
      |> filter_out (String.isSubstring Long_Name.separator)
blanchet@60139
   897
blanchet@60139
   898
    val fake_ctxt =
blanchet@60139
   899
      ctxt |> Proof_Context.background_theory (fn thy =>
blanchet@60139
   900
        thy
blanchet@60139
   901
        |> Sign.map_naming (K Name_Space.global_naming)
blanchet@60139
   902
        |> fold (perhaps o try o add_fake_const) globals
blanchet@60139
   903
        |> Sign.restore_naming thy)
blanchet@60139
   904
  in
blanchet@60139
   905
    Syntax.pretty_term fake_ctxt t
blanchet@60139
   906
  end
blanchet@60139
   907
blanchet@55889
   908
fun reconstruct_hol_model {show_types, show_skolems, show_consts}
blanchet@55888
   909
        ({hol_ctxt = {thy, ctxt, max_bisim_depth, boxes, wfs, user_axioms,
blanchet@38209
   910
                      debug, whacks, binary_ints, destroy_constrs, specialize,
blanchet@41875
   911
                      star_linear_preds, total_consts, needs, tac_timeout,
blanchet@42415
   912
                      evals, case_names, def_tables, nondef_table, nondefs,
blanchet@41803
   913
                      simp_table, psimp_table, choice_spec_table, intro_table,
blanchet@36388
   914
                      ground_thm_table, ersatz_table, skolems, special_funs,
blanchet@41803
   915
                      unrolled_preds, wf_cache, constr_cache}, binarize,
blanchet@55890
   916
                      card_assigns, bits, bisim_depth, data_types, ofs} : scope)
blanchet@38170
   917
        formats atomss real_frees pseudo_frees free_names sel_names nonsel_names
blanchet@38170
   918
        rel_table bounds =
blanchet@33192
   919
  let
blanchet@35180
   920
    val pool = Unsynchronized.ref []
blanchet@60139
   921
    val (wacky_names as (_, base_step_names), ctxt) = add_wacky_syntax ctxt
blanchet@35070
   922
    val hol_ctxt =
blanchet@33192
   923
      {thy = thy, ctxt = ctxt, max_bisim_depth = max_bisim_depth, boxes = boxes,
blanchet@55888
   924
       wfs = wfs, user_axioms = user_axioms, debug = debug, whacks = whacks,
blanchet@55888
   925
       binary_ints = binary_ints, destroy_constrs = destroy_constrs,
blanchet@55888
   926
       specialize = specialize, star_linear_preds = star_linear_preds,
blanchet@55888
   927
       total_consts = total_consts, needs = needs, tac_timeout = tac_timeout,
blanchet@55888
   928
       evals = evals, case_names = case_names, def_tables = def_tables,
blanchet@42415
   929
       nondef_table = nondef_table, nondefs = nondefs, simp_table = simp_table,
blanchet@42415
   930
       psimp_table = psimp_table, choice_spec_table = choice_spec_table,
blanchet@42415
   931
       intro_table = intro_table, ground_thm_table = ground_thm_table,
blanchet@42415
   932
       ersatz_table = ersatz_table, skolems = skolems,
blanchet@42415
   933
       special_funs = special_funs, unrolled_preds = unrolled_preds,
blanchet@42415
   934
       wf_cache = wf_cache, constr_cache = constr_cache}
blanchet@36388
   935
    val scope =
blanchet@36388
   936
      {hol_ctxt = hol_ctxt, binarize = binarize, card_assigns = card_assigns,
blanchet@55890
   937
       bits = bits, bisim_depth = bisim_depth, data_types = data_types,
blanchet@55890
   938
       ofs = ofs}
blanchet@37262
   939
    fun term_for_rep maybe_opt unfold =
blanchet@37262
   940
      reconstruct_term maybe_opt unfold pool wacky_names scope atomss
blanchet@37262
   941
                       sel_names rel_table bounds
blanchet@35712
   942
    val all_values =
blanchet@37260
   943
      all_values_of_type pool wacky_names scope atomss sel_names rel_table
blanchet@37260
   944
                         bounds
blanchet@55890
   945
    fun is_codatatype_wellformed (cos : data_type_spec list)
blanchet@55890
   946
                                 ({typ, card, ...} : data_type_spec) =
blanchet@33192
   947
      let
blanchet@35712
   948
        val ts = all_values card typ
blanchet@33192
   949
        val max_depth = Integer.sum (map #card cos)
blanchet@33192
   950
      in
blanchet@33192
   951
        forall (not o bisimilar_values (map #typ cos) max_depth)
blanchet@33192
   952
               (all_distinct_unordered_pairs_of ts)
blanchet@33192
   953
      end
blanchet@33192
   954
    fun pretty_for_assign name =
blanchet@33192
   955
      let
blanchet@33192
   956
        val (oper, (t1, T'), T) =
blanchet@33192
   957
          case name of
blanchet@33192
   958
            FreeName (s, T, _) =>
blanchet@35665
   959
            let val t = Free (s, uniterize_unarize_unbox_etc_type T) in
blanchet@41791
   960
              ("=", (t, format_term_type thy def_tables formats t), T)
blanchet@33192
   961
            end
blanchet@33192
   962
          | ConstName (s, T, _) =>
blanchet@33192
   963
            (assign_operator_for_const (s, T),
blanchet@35280
   964
             user_friendly_const hol_ctxt base_step_names formats (s, T), T)
blanchet@33232
   965
          | _ => raise NUT ("Nitpick_Model.reconstruct_hol_model.\
blanchet@33192
   966
                            \pretty_for_assign", [name])
blanchet@33192
   967
        val t2 = if rep_of name = Any then
blanchet@33192
   968
                   Const (@{const_name undefined}, T')
blanchet@33192
   969
                 else
blanchet@33192
   970
                   tuple_list_for_name rel_table bounds name
blanchet@37262
   971
                   |> term_for_rep (not (is_fully_representable_set name)) false
blanchet@37262
   972
                                   T T' (rep_of name)
blanchet@33192
   973
      in
blanchet@33192
   974
        Pretty.block (Pretty.breaks
blanchet@60139
   975
            [pretty_term_auto_global ctxt t1, Pretty.str oper,
blanchet@60139
   976
             pretty_term_auto_global ctxt t2])
blanchet@33192
   977
      end
blanchet@55890
   978
    fun pretty_for_data_type ({typ, card, complete, ...} : data_type_spec) =
blanchet@33192
   979
      Pretty.block (Pretty.breaks
blanchet@38189
   980
          (pretty_for_type ctxt typ ::
blanchet@35665
   981
           (case typ of
blanchet@41052
   982
              Type (@{type_name fun_box}, _) => [Pretty.str "[boxed]"]
blanchet@35665
   983
            | Type (@{type_name pair_box}, _) => [Pretty.str "[boxed]"]
blanchet@35665
   984
            | _ => []) @
blanchet@35665
   985
           [Pretty.str "=",
blanchet@35665
   986
            Pretty.enum "," "{" "}"
blanchet@60139
   987
                (map (pretty_term_auto_global ctxt) (all_values card typ) @
blanchet@35665
   988
                 (if fun_from_pair complete false then []
blanchet@61331
   989
                  else [Pretty.str (unrep_mixfix ())]))]))
blanchet@55890
   990
    fun integer_data_type T =
blanchet@33192
   991
      [{typ = T, card = card_of_type card_assigns T, co = false,
blanchet@55888
   992
        self_rec = true, complete = (false, false), concrete = (true, true),
blanchet@55888
   993
        deep = true, constrs = []}]
blanchet@33232
   994
      handle TYPE ("Nitpick_HOL.card_of_type", _, _) => []
blanchet@55890
   995
    val data_types =
blanchet@55890
   996
      data_types |> filter #deep
blanchet@55890
   997
                 |> append (maps integer_data_type [nat_T, int_T])
blanchet@55890
   998
    val block_of_data_types =
blanchet@55890
   999
      if show_types andalso not (null data_types) then
blanchet@55890
  1000
        [Pretty.big_list ("Type" ^ plural_s_for_list data_types ^ ":")
blanchet@55890
  1001
                         (map pretty_for_data_type data_types)]
blanchet@33192
  1002
      else
blanchet@33192
  1003
        []
blanchet@33192
  1004
    fun block_of_names show title names =
blanchet@33192
  1005
      if show andalso not (null names) then
blanchet@33192
  1006
        Pretty.str (title ^ plural_s_for_list names ^ ":")
blanchet@33192
  1007
        :: map (Pretty.indent indent_size o pretty_for_assign)
wenzelm@60924
  1008
               (sort_by (original_name o nickname_of) names)
blanchet@33192
  1009
      else
blanchet@33192
  1010
        []
blanchet@38170
  1011
    fun free_name_for_term keep_all (x as (s, T)) =
blanchet@38170
  1012
      case filter (curry (op =) x
blanchet@38170
  1013
                   o pairf nickname_of (uniterize_unarize_unbox_etc_type
blanchet@38170
  1014
                                        o type_of)) free_names of
blanchet@38170
  1015
        [name] => SOME name
blanchet@38170
  1016
      | [] => if keep_all then SOME (FreeName (s, T, Any)) else NONE
blanchet@38170
  1017
      | _ => raise TERM ("Nitpick_Model.reconstruct_hol_model.\
blanchet@38170
  1018
                         \free_name_for_term", [Const x])
blanchet@33192
  1019
    val (skolem_names, nonskolem_nonsel_names) =
blanchet@33192
  1020
      List.partition is_skolem_name nonsel_names
blanchet@33192
  1021
    val (eval_names, noneval_nonskolem_nonsel_names) =
blanchet@33192
  1022
      List.partition (String.isPrefix eval_prefix o nickname_of)
blanchet@33192
  1023
                     nonskolem_nonsel_names
blanchet@35665
  1024
      ||> filter_out (member (op =) [@{const_name bisim},
blanchet@35665
  1025
                                     @{const_name bisim_iterator_max}]
blanchet@34121
  1026
                      o nickname_of)
blanchet@38170
  1027
      ||> append (map_filter (free_name_for_term false) pseudo_frees)
blanchet@38170
  1028
    val real_free_names = map_filter (free_name_for_term true) real_frees
blanchet@38170
  1029
    val chunks = block_of_names true "Free variable" real_free_names @
blanchet@41993
  1030
                 block_of_names show_skolems "Skolem constant" skolem_names @
blanchet@33192
  1031
                 block_of_names true "Evaluated term" eval_names @
blanchet@55890
  1032
                 block_of_data_types @
blanchet@33192
  1033
                 block_of_names show_consts "Constant"
blanchet@33192
  1034
                                noneval_nonskolem_nonsel_names
blanchet@55890
  1035
    val codatatypes = filter #co data_types;
blanchet@33192
  1036
  in
blanchet@33192
  1037
    (Pretty.chunks (if null chunks then [Pretty.str "Empty assignment"]
blanchet@33192
  1038
                    else chunks),
blanchet@34936
  1039
     bisim_depth >= 0 orelse
blanchet@34936
  1040
     forall (is_codatatype_wellformed codatatypes) codatatypes)
blanchet@33192
  1041
  end
blanchet@33192
  1042
blanchet@33192
  1043
end;