src/HOL/Tools/Nitpick/nitpick_kodkod.ML
author blanchet
Mon Mar 03 22:33:22 2014 +0100 (2014-03-03)
changeset 55888 cac1add157e8
parent 54632 7a14f831d02d
child 55889 6bfbec3dff62
permissions -rw-r--r--
removed nonstandard models from Nitpick
blanchet@33982
     1
(*  Title:      HOL/Tools/Nitpick/nitpick_kodkod.ML
blanchet@33192
     2
    Author:     Jasmin Blanchette, TU Muenchen
blanchet@34982
     3
    Copyright   2008, 2009, 2010
blanchet@33192
     4
blanchet@33192
     5
Kodkod problem generator part of Kodkod.
blanchet@33192
     6
*)
blanchet@33192
     7
blanchet@33192
     8
signature NITPICK_KODKOD =
blanchet@33192
     9
sig
blanchet@35070
    10
  type hol_context = Nitpick_HOL.hol_context
blanchet@38126
    11
  type datatype_spec = Nitpick_Scope.datatype_spec
blanchet@33232
    12
  type kodkod_constrs = Nitpick_Peephole.kodkod_constrs
blanchet@33232
    13
  type nut = Nitpick_Nut.nut
blanchet@33192
    14
blanchet@33192
    15
  structure NameTable : TABLE
blanchet@33192
    16
blanchet@33192
    17
  val univ_card :
blanchet@33192
    18
    int -> int -> int -> Kodkod.bound list -> Kodkod.formula -> int
blanchet@34124
    19
  val check_bits : int -> Kodkod.formula -> unit
blanchet@38182
    20
  val check_arity : string -> int -> int -> unit
blanchet@33192
    21
  val kk_tuple : bool -> int -> int list -> Kodkod.tuple
blanchet@33192
    22
  val tuple_set_from_atom_schema : (int * int) list -> Kodkod.tuple_set
blanchet@33192
    23
  val sequential_int_bounds : int -> Kodkod.int_bound list
blanchet@35280
    24
  val pow_of_two_int_bounds : int -> int -> Kodkod.int_bound list
blanchet@38126
    25
  val bounds_and_axioms_for_built_in_rels_in_formulas :
blanchet@39345
    26
    bool -> int -> int -> int -> int -> Kodkod.formula list
blanchet@38126
    27
    -> Kodkod.bound list * Kodkod.formula list
blanchet@33192
    28
  val bound_for_plain_rel : Proof.context -> bool -> nut -> Kodkod.bound
blanchet@33192
    29
  val bound_for_sel_rel :
blanchet@41995
    30
    Proof.context -> bool -> (typ * (nut * int) list option) list
blanchet@41995
    31
    -> datatype_spec list -> nut -> Kodkod.bound
blanchet@33192
    32
  val merge_bounds : Kodkod.bound list -> Kodkod.bound list
blanchet@41802
    33
  val kodkod_formula_from_nut :
blanchet@41802
    34
    int Typtab.table -> kodkod_constrs -> nut -> Kodkod.formula
blanchet@41995
    35
  val needed_values_for_datatype :
blanchet@41995
    36
    nut list -> int Typtab.table -> datatype_spec -> (nut * int) list option
blanchet@33192
    37
  val declarative_axiom_for_plain_rel : kodkod_constrs -> nut -> Kodkod.formula
blanchet@33192
    38
  val declarative_axioms_for_datatypes :
blanchet@41995
    39
    hol_context -> bool -> nut list -> (typ * (nut * int) list option) list
blanchet@41995
    40
    -> int -> int -> int Typtab.table -> kodkod_constrs -> nut NameTable.table
blanchet@41995
    41
    -> datatype_spec list -> Kodkod.formula list
blanchet@33192
    42
end;
blanchet@33192
    43
blanchet@33232
    44
structure Nitpick_Kodkod : NITPICK_KODKOD =
blanchet@33192
    45
struct
blanchet@33192
    46
blanchet@33232
    47
open Nitpick_Util
blanchet@33232
    48
open Nitpick_HOL
blanchet@33232
    49
open Nitpick_Scope
blanchet@33232
    50
open Nitpick_Peephole
blanchet@33232
    51
open Nitpick_Rep
blanchet@33232
    52
open Nitpick_Nut
blanchet@33192
    53
blanchet@34126
    54
structure KK = Kodkod
blanchet@34126
    55
blanchet@38126
    56
fun pull x xs = x :: filter_out (curry (op =) x) xs
blanchet@33192
    57
blanchet@55888
    58
fun is_datatype_acyclic ({co = false, deep = true, ...} : datatype_spec) = true
blanchet@38196
    59
  | is_datatype_acyclic _ = false
blanchet@33192
    60
blanchet@34126
    61
fun flip_nums n = index_seq 1 n @ [0] |> map KK.Num
blanchet@33192
    62
blanchet@33192
    63
fun univ_card nat_card int_card main_j0 bounds formula =
blanchet@33192
    64
  let
blanchet@33192
    65
    fun rel_expr_func r k =
blanchet@33192
    66
      Int.max (k, case r of
blanchet@34126
    67
                    KK.Atom j => j + 1
blanchet@34126
    68
                  | KK.AtomSeq (k', j0) => j0 + k'
blanchet@33192
    69
                  | _ => 0)
blanchet@33192
    70
    fun tuple_func t k =
blanchet@33192
    71
      case t of
blanchet@34126
    72
        KK.Tuple js => fold Integer.max (map (Integer.add 1) js) k
blanchet@33192
    73
      | _ => k
blanchet@33192
    74
    fun tuple_set_func ts k =
blanchet@34126
    75
      Int.max (k, case ts of KK.TupleAtomSeq (k', j0) => j0 + k' | _ => 0)
blanchet@33192
    76
    val expr_F = {formula_func = K I, rel_expr_func = rel_expr_func,
blanchet@33192
    77
                  int_expr_func = K I}
blanchet@33192
    78
    val tuple_F = {tuple_func = tuple_func, tuple_set_func = tuple_set_func}
blanchet@34126
    79
    val card = fold (KK.fold_bound expr_F tuple_F) bounds 1
blanchet@34126
    80
               |> KK.fold_formula expr_F formula
blanchet@33192
    81
  in Int.max (main_j0 + fold Integer.max [2, nat_card, int_card] 0, card) end
blanchet@33192
    82
blanchet@34124
    83
fun check_bits bits formula =
blanchet@34124
    84
  let
blanchet@34126
    85
    fun int_expr_func (KK.Num k) () =
blanchet@34124
    86
        if is_twos_complement_representable bits k then
blanchet@34124
    87
          ()
blanchet@34124
    88
        else
blanchet@34124
    89
          raise TOO_SMALL ("Nitpick_Kodkod.check_bits",
blanchet@34124
    90
                           "\"bits\" value " ^ string_of_int bits ^
blanchet@34124
    91
                           " too small for problem")
blanchet@34124
    92
      | int_expr_func _ () = ()
blanchet@34124
    93
    val expr_F = {formula_func = K I, rel_expr_func = K I,
blanchet@34124
    94
                  int_expr_func = int_expr_func}
blanchet@34126
    95
  in KK.fold_formula expr_F formula () end
blanchet@33192
    96
blanchet@38182
    97
fun check_arity guilty_party univ_card n =
blanchet@34126
    98
  if n > KK.max_arity univ_card then
blanchet@34124
    99
    raise TOO_LARGE ("Nitpick_Kodkod.check_arity",
blanchet@38182
   100
                     "arity " ^ string_of_int n ^
blanchet@38182
   101
                     (if guilty_party = "" then
blanchet@38182
   102
                        ""
blanchet@38182
   103
                      else
blanchet@38182
   104
                        " of Kodkod relation associated with " ^
blanchet@41045
   105
                        quote (original_name guilty_party)) ^
blanchet@52201
   106
                     " too large for a universe of size " ^
blanchet@38182
   107
                     string_of_int univ_card)
blanchet@33192
   108
  else
blanchet@33192
   109
    ()
blanchet@33192
   110
blanchet@33192
   111
fun kk_tuple debug univ_card js =
blanchet@33192
   112
  if debug then
blanchet@34126
   113
    KK.Tuple js
blanchet@33192
   114
  else
blanchet@34126
   115
    KK.TupleIndex (length js,
blanchet@34126
   116
                   fold (fn j => fn accum => accum * univ_card + j) js 0)
blanchet@33192
   117
blanchet@42436
   118
(* This code is not just a silly optimization: It works around a limitation in
blanchet@42436
   119
   Kodkodi, whereby {} (i.e., KK.TupleProduct) is always given the cardinality
blanchet@42436
   120
   of the bound in which it appears, resulting in Kodkod arity errors. *)
blanchet@42436
   121
fun tuple_product (ts as KK.TupleSet []) _ = ts
blanchet@42436
   122
  | tuple_product _ (ts as KK.TupleSet []) = ts
blanchet@42436
   123
  | tuple_product ts1 ts2 = KK.TupleProduct (ts1, ts2)
blanchet@42436
   124
blanchet@42436
   125
val tuple_set_from_atom_schema = fold1 tuple_product o map KK.TupleAtomSeq
blanchet@33192
   126
val upper_bound_for_rep = tuple_set_from_atom_schema o atom_schema_of_rep
blanchet@33192
   127
blanchet@34126
   128
val single_atom = KK.TupleSet o single o KK.Tuple o single
blanchet@34124
   129
fun sequential_int_bounds n = [(NONE, map single_atom (index_seq 0 n))]
blanchet@35280
   130
fun pow_of_two_int_bounds bits j0 =
blanchet@34124
   131
  let
blanchet@34124
   132
    fun aux 0  _ _ = []
blanchet@35220
   133
      | aux 1 pow_of_two j = [(SOME (~ pow_of_two), [single_atom j])]
blanchet@34124
   134
      | aux iter pow_of_two j =
blanchet@34124
   135
        (SOME pow_of_two, [single_atom j]) ::
blanchet@34124
   136
        aux (iter - 1) (2 * pow_of_two) (j + 1)
blanchet@34124
   137
  in aux (bits + 1) 1 j0 end
blanchet@33192
   138
blanchet@38126
   139
fun built_in_rels_in_formulas formulas =
blanchet@33192
   140
  let
blanchet@39345
   141
    fun rel_expr_func (KK.Rel (x as (_, j))) =
blanchet@38126
   142
        (j < 0 andalso x <> unsigned_bit_word_sel_rel andalso
blanchet@38126
   143
         x <> signed_bit_word_sel_rel)
blanchet@38126
   144
        ? insert (op =) x
blanchet@34124
   145
      | rel_expr_func _ = I
blanchet@33192
   146
    val expr_F = {formula_func = K I, rel_expr_func = rel_expr_func,
blanchet@33192
   147
                  int_expr_func = K I}
blanchet@38126
   148
  in fold (KK.fold_formula expr_F) formulas [] end
blanchet@33192
   149
blanchet@33192
   150
val max_table_size = 65536
blanchet@33192
   151
blanchet@33192
   152
fun check_table_size k =
blanchet@33192
   153
  if k > max_table_size then
blanchet@34124
   154
    raise TOO_LARGE ("Nitpick_Kodkod.check_table_size",
blanchet@34124
   155
                     "precomputed table too large (" ^ string_of_int k ^ ")")
blanchet@33192
   156
  else
blanchet@33192
   157
    ()
blanchet@33192
   158
blanchet@33192
   159
fun tabulate_func1 debug univ_card (k, j0) f =
blanchet@33192
   160
  (check_table_size k;
blanchet@33192
   161
   map_filter (fn j1 => let val j2 = f j1 in
blanchet@33192
   162
                          if j2 >= 0 then
blanchet@33192
   163
                            SOME (kk_tuple debug univ_card [j1 + j0, j2 + j0])
blanchet@33192
   164
                          else
blanchet@33192
   165
                            NONE
blanchet@33192
   166
                        end) (index_seq 0 k))
blanchet@33192
   167
fun tabulate_op2 debug univ_card (k, j0) res_j0 f =
blanchet@33192
   168
  (check_table_size (k * k);
blanchet@33192
   169
   map_filter (fn j => let
blanchet@33192
   170
                         val j1 = j div k
blanchet@33192
   171
                         val j2 = j - j1 * k
blanchet@33192
   172
                         val j3 = f (j1, j2)
blanchet@33192
   173
                       in
blanchet@33192
   174
                         if j3 >= 0 then
blanchet@33192
   175
                           SOME (kk_tuple debug univ_card
blanchet@33192
   176
                                          [j1 + j0, j2 + j0, j3 + res_j0])
blanchet@33192
   177
                         else
blanchet@33192
   178
                           NONE
blanchet@33192
   179
                       end) (index_seq 0 (k * k)))
blanchet@33192
   180
fun tabulate_op2_2 debug univ_card (k, j0) res_j0 f =
blanchet@33192
   181
  (check_table_size (k * k);
blanchet@33192
   182
   map_filter (fn j => let
blanchet@33192
   183
                         val j1 = j div k
blanchet@33192
   184
                         val j2 = j - j1 * k
blanchet@33192
   185
                         val (j3, j4) = f (j1, j2)
blanchet@33192
   186
                       in
blanchet@33192
   187
                         if j3 >= 0 andalso j4 >= 0 then
blanchet@33192
   188
                           SOME (kk_tuple debug univ_card
blanchet@33192
   189
                                          [j1 + j0, j2 + j0, j3 + res_j0,
blanchet@33192
   190
                                           j4 + res_j0])
blanchet@33192
   191
                         else
blanchet@33192
   192
                           NONE
blanchet@33192
   193
                       end) (index_seq 0 (k * k)))
blanchet@33192
   194
fun tabulate_nat_op2 debug univ_card (k, j0) f =
blanchet@33192
   195
  tabulate_op2 debug univ_card (k, j0) j0 (atom_for_nat (k, 0) o f)
blanchet@33192
   196
fun tabulate_int_op2 debug univ_card (k, j0) f =
blanchet@33192
   197
  tabulate_op2 debug univ_card (k, j0) j0
blanchet@33192
   198
               (atom_for_int (k, 0) o f o pairself (int_for_atom (k, 0)))
blanchet@33192
   199
fun tabulate_int_op2_2 debug univ_card (k, j0) f =
blanchet@33192
   200
  tabulate_op2_2 debug univ_card (k, j0) j0
blanchet@33192
   201
                 (pairself (atom_for_int (k, 0)) o f
blanchet@33192
   202
                  o pairself (int_for_atom (k, 0)))
blanchet@33192
   203
blanchet@33192
   204
fun isa_div (m, n) = m div n handle General.Div => 0
blanchet@33192
   205
fun isa_mod (m, n) = m mod n handle General.Div => m
blanchet@33192
   206
fun isa_gcd (m, 0) = m
blanchet@33192
   207
  | isa_gcd (m, n) = isa_gcd (n, isa_mod (m, n))
blanchet@33192
   208
fun isa_lcm (m, n) = isa_div (m * n, isa_gcd (m, n))
blanchet@33192
   209
val isa_zgcd = isa_gcd o pairself abs
blanchet@33192
   210
fun isa_norm_frac (m, n) =
blanchet@33192
   211
  if n < 0 then isa_norm_frac (~m, ~n)
blanchet@33192
   212
  else if m = 0 orelse n = 0 then (0, 1)
blanchet@33192
   213
  else let val p = isa_zgcd (m, n) in (isa_div (m, p), isa_div (n, p)) end
blanchet@33192
   214
blanchet@39345
   215
fun tabulate_built_in_rel debug univ_card nat_card int_card j0
blanchet@38124
   216
                          (x as (n, _)) =
blanchet@38182
   217
  (check_arity "" univ_card n;
blanchet@34124
   218
   if x = not3_rel then
blanchet@33192
   219
     ("not3", tabulate_func1 debug univ_card (2, j0) (curry (op -) 1))
blanchet@34124
   220
   else if x = suc_rel then
blanchet@38126
   221
     ("suc", tabulate_func1 debug univ_card (univ_card - j0 - 1, j0)
blanchet@38126
   222
                            (Integer.add 1))
blanchet@34124
   223
   else if x = nat_add_rel then
blanchet@33192
   224
     ("nat_add", tabulate_nat_op2 debug univ_card (nat_card, j0) (op +))
blanchet@34124
   225
   else if x = int_add_rel then
blanchet@33192
   226
     ("int_add", tabulate_int_op2 debug univ_card (int_card, j0) (op +))
blanchet@34124
   227
   else if x = nat_subtract_rel then
blanchet@33192
   228
     ("nat_subtract",
blanchet@33705
   229
      tabulate_op2 debug univ_card (nat_card, j0) j0 (uncurry nat_minus))
blanchet@34124
   230
   else if x = int_subtract_rel then
blanchet@33192
   231
     ("int_subtract", tabulate_int_op2 debug univ_card (int_card, j0) (op -))
blanchet@34124
   232
   else if x = nat_multiply_rel then
blanchet@33192
   233
     ("nat_multiply", tabulate_nat_op2 debug univ_card (nat_card, j0) (op * ))
blanchet@34124
   234
   else if x = int_multiply_rel then
blanchet@33192
   235
     ("int_multiply", tabulate_int_op2 debug univ_card (int_card, j0) (op * ))
blanchet@34124
   236
   else if x = nat_divide_rel then
blanchet@33192
   237
     ("nat_divide", tabulate_nat_op2 debug univ_card (nat_card, j0) isa_div)
blanchet@34124
   238
   else if x = int_divide_rel then
blanchet@33192
   239
     ("int_divide", tabulate_int_op2 debug univ_card (int_card, j0) isa_div)
blanchet@34124
   240
   else if x = nat_less_rel then
blanchet@33192
   241
     ("nat_less", tabulate_nat_op2 debug univ_card (nat_card, j0)
blanchet@35385
   242
                                   (int_from_bool o op <))
blanchet@34124
   243
   else if x = int_less_rel then
blanchet@33192
   244
     ("int_less", tabulate_int_op2 debug univ_card (int_card, j0)
blanchet@35385
   245
                                   (int_from_bool o op <))
blanchet@34124
   246
   else if x = gcd_rel then
blanchet@33192
   247
     ("gcd", tabulate_nat_op2 debug univ_card (nat_card, j0) isa_gcd)
blanchet@34124
   248
   else if x = lcm_rel then
blanchet@33192
   249
     ("lcm", tabulate_nat_op2 debug univ_card (nat_card, j0) isa_lcm)
blanchet@34124
   250
   else if x = norm_frac_rel then
blanchet@33192
   251
     ("norm_frac", tabulate_int_op2_2 debug univ_card (int_card, j0)
blanchet@33192
   252
                                      isa_norm_frac)
blanchet@33192
   253
   else
blanchet@33232
   254
     raise ARG ("Nitpick_Kodkod.tabulate_built_in_rel", "unknown relation"))
blanchet@33192
   255
blanchet@39345
   256
fun bound_for_built_in_rel debug univ_card nat_card int_card main_j0
blanchet@38126
   257
                           (x as (n, j)) =
blanchet@38126
   258
  if n = 2 andalso j <= suc_rels_base then
blanchet@38126
   259
    let val (y as (k, j0), tabulate) = atom_seq_for_suc_rel x in
blanchet@38126
   260
      ([(x, "suc")],
blanchet@38126
   261
       if tabulate then
blanchet@38126
   262
         [KK.TupleSet (tabulate_func1 debug univ_card (k - 1, j0)
blanchet@38126
   263
                       (Integer.add 1))]
blanchet@38126
   264
       else
blanchet@38126
   265
         [KK.TupleSet [], tuple_set_from_atom_schema [y, y]])
blanchet@38126
   266
    end
blanchet@38126
   267
  else
blanchet@38126
   268
    let
blanchet@39345
   269
      val (nick, ts) = tabulate_built_in_rel debug univ_card nat_card int_card
blanchet@39345
   270
                                             main_j0 x
blanchet@38126
   271
    in ([(x, nick)], [KK.TupleSet ts]) end
blanchet@33192
   272
blanchet@38126
   273
fun axiom_for_built_in_rel (x as (n, j)) =
blanchet@38126
   274
  if n = 2 andalso j <= suc_rels_base then
blanchet@38126
   275
    let val (y as (k, j0), tabulate) = atom_seq_for_suc_rel x in
blanchet@38160
   276
      if tabulate then
blanchet@38126
   277
        NONE
blanchet@38160
   278
      else if k < 2 then
blanchet@38160
   279
        SOME (KK.No (KK.Rel x))
blanchet@38126
   280
      else
blanchet@38126
   281
        SOME (KK.TotalOrdering (x, KK.AtomSeq y, KK.Atom j0, KK.Atom (j0 + 1)))
blanchet@38126
   282
    end
blanchet@38126
   283
  else
blanchet@38126
   284
    NONE
blanchet@39345
   285
fun bounds_and_axioms_for_built_in_rels_in_formulas debug univ_card nat_card
blanchet@38126
   286
                                                    int_card main_j0 formulas =
blanchet@38126
   287
  let val rels = built_in_rels_in_formulas formulas in
blanchet@39345
   288
    (map (bound_for_built_in_rel debug univ_card nat_card int_card main_j0)
blanchet@38126
   289
         rels,
blanchet@38126
   290
     map_filter axiom_for_built_in_rel rels)
blanchet@39316
   291
  end
blanchet@33192
   292
blanchet@34124
   293
fun bound_comment ctxt debug nick T R =
blanchet@34124
   294
  short_name nick ^
blanchet@34982
   295
  (if debug then " :: " ^ unyxml (Syntax.string_of_typ ctxt T) else "") ^
blanchet@34982
   296
  " : " ^ string_for_rep R
blanchet@34124
   297
blanchet@33192
   298
fun bound_for_plain_rel ctxt debug (u as FreeRel (x, T, R, nick)) =
blanchet@33192
   299
    ([(x, bound_comment ctxt debug nick T R)],
blanchet@33192
   300
     if nick = @{const_name bisim_iterator_max} then
blanchet@33192
   301
       case R of
blanchet@34124
   302
         Atom (k, j0) => [single_atom (k - 1 + j0)]
blanchet@33232
   303
       | _ => raise NUT ("Nitpick_Kodkod.bound_for_plain_rel", [u])
blanchet@33192
   304
     else
blanchet@34126
   305
       [KK.TupleSet [], upper_bound_for_rep R])
blanchet@33192
   306
  | bound_for_plain_rel _ _ u =
blanchet@33232
   307
    raise NUT ("Nitpick_Kodkod.bound_for_plain_rel", [u])
blanchet@33192
   308
blanchet@41997
   309
fun is_datatype_nat_like ({typ, constrs, ...} : datatype_spec) =
blanchet@42000
   310
  case constrs of
blanchet@42000
   311
    [_, _] =>
blanchet@42000
   312
    (case constrs |> map (snd o #const) |> List.partition is_fun_type of
blanchet@42000
   313
       ([Type (_, Ts1)], [T2]) => forall (curry (op =) typ) (T2 :: Ts1)
blanchet@42000
   314
     | _ => false)
blanchet@41997
   315
  | _ => false
blanchet@41997
   316
blanchet@41998
   317
fun needed_values need_vals T =
blanchet@41998
   318
  AList.lookup (op =) need_vals T |> the_default NONE |> these
blanchet@41998
   319
blanchet@41998
   320
fun all_values_are_needed need_vals ({typ, card, ...} : datatype_spec) =
blanchet@41998
   321
  length (needed_values need_vals typ) = card
blanchet@41998
   322
blanchet@41998
   323
fun is_sel_of_constr x (Construct (sel_us, _, _, _), _) =
blanchet@41998
   324
    exists (fn FreeRel (x', _, _, _) => x = x' | _ => false) sel_us
blanchet@41998
   325
  | is_sel_of_constr _ _ = false
blanchet@41998
   326
blanchet@41995
   327
fun bound_for_sel_rel ctxt debug need_vals dtypes
blanchet@35665
   328
        (FreeRel (x, T as Type (@{type_name fun}, [T1, T2]),
blanchet@35665
   329
                  R as Func (Atom (_, j0), R2), nick)) =
blanchet@33192
   330
    let
blanchet@41995
   331
      val constr_s = original_name nick
blanchet@35280
   332
      val {delta, epsilon, exclusive, explicit_max, ...} =
blanchet@41995
   333
        constr_spec dtypes (constr_s, T1)
blanchet@41995
   334
      val dtype as {card, ...} = datatype_spec dtypes T1 |> the
blanchet@41998
   335
      val T1_need_vals = needed_values need_vals T1
blanchet@33192
   336
    in
blanchet@33192
   337
      ([(x, bound_comment ctxt debug nick T R)],
blanchet@41995
   338
       let
blanchet@42001
   339
         val discr = (R2 = Formula Neut)
blanchet@41998
   340
         val complete_need_vals = (length T1_need_vals = card)
blanchet@41995
   341
         val (my_need_vals, other_need_vals) =
blanchet@41998
   342
           T1_need_vals |> List.partition (is_sel_of_constr x)
blanchet@42001
   343
         fun atom_seq_for_self_rec j =
blanchet@42001
   344
           if is_datatype_nat_like dtype then (1, j + j0 - 1) else (j, j0)
blanchet@42001
   345
         fun exact_bound_for_perhaps_needy_atom j =
blanchet@42001
   346
           case AList.find (op =) my_need_vals j of
blanchet@42001
   347
             [constr_u] =>
blanchet@42001
   348
             let
blanchet@42001
   349
               val n = sel_no_from_name nick
blanchet@42001
   350
               val arg_u =
blanchet@42001
   351
                 case constr_u of
blanchet@42001
   352
                   Construct (_, _, _, arg_us) => nth arg_us n
blanchet@42001
   353
                 | _ => raise Fail "expected \"Construct\""
blanchet@42001
   354
               val T2_need_vals = needed_values need_vals T2
blanchet@42001
   355
             in
blanchet@42001
   356
               case AList.lookup (op =) T2_need_vals arg_u of
blanchet@42001
   357
                 SOME arg_j => SOME (KK.TupleAtomSeq (1, arg_j))
blanchet@42001
   358
               | _ => NONE
blanchet@42001
   359
             end
blanchet@42001
   360
           | _ => NONE
blanchet@42001
   361
         fun n_fold_tuple_union [] = KK.TupleSet []
blanchet@42001
   362
           | n_fold_tuple_union (ts :: tss) =
blanchet@42001
   363
             fold (curry (KK.TupleUnion o swap)) tss ts
blanchet@42001
   364
         fun tuple_perhaps_needy_atom upper j =
blanchet@42001
   365
           single_atom j
blanchet@42001
   366
           |> not discr
blanchet@42436
   367
              ? (fn ts => tuple_product ts
blanchet@42436
   368
                              (case exact_bound_for_perhaps_needy_atom j of
blanchet@42436
   369
                                 SOME ts => ts
blanchet@42436
   370
                               | NONE => if upper then upper_bound_for_rep R2
blanchet@42436
   371
                                         else KK.TupleSet []))
blanchet@42001
   372
         fun bound_tuples upper =
blanchet@42001
   373
           if null T1_need_vals then
blanchet@42001
   374
             if upper then
blanchet@42001
   375
               KK.TupleAtomSeq (epsilon - delta, delta + j0)
blanchet@42001
   376
               |> not discr
blanchet@42436
   377
                  ? (fn ts => tuple_product ts (upper_bound_for_rep R2))
blanchet@42001
   378
             else
blanchet@42001
   379
               KK.TupleSet []
blanchet@41996
   380
           else
blanchet@42001
   381
             (if complete_need_vals then
blanchet@42001
   382
                my_need_vals |> map snd
blanchet@42001
   383
              else
blanchet@42001
   384
                index_seq (delta + j0) (epsilon - delta)
blanchet@42001
   385
                |> filter_out (member (op = o apsnd snd) other_need_vals))
blanchet@42001
   386
             |> map (tuple_perhaps_needy_atom upper)
blanchet@42001
   387
             |> n_fold_tuple_union
blanchet@41995
   388
       in
blanchet@41995
   389
         if explicit_max = 0 orelse
blanchet@41998
   390
            (complete_need_vals andalso null my_need_vals) then
blanchet@41995
   391
           [KK.TupleSet []]
blanchet@41995
   392
         else
blanchet@42001
   393
           if discr then
blanchet@42001
   394
             [bound_tuples true]
blanchet@41998
   395
             |> not (exclusive orelse all_values_are_needed need_vals dtype)
blanchet@41998
   396
                ? cons (KK.TupleSet [])
blanchet@33192
   397
           else
blanchet@42001
   398
             [bound_tuples false,
blanchet@35178
   399
              if T1 = T2 andalso epsilon > delta andalso
blanchet@41995
   400
                 is_datatype_acyclic dtype then
blanchet@35072
   401
                index_seq delta (epsilon - delta)
blanchet@42436
   402
                |> map (fn j => tuple_product (KK.TupleSet [KK.Tuple [j + j0]])
blanchet@42436
   403
                                    (KK.TupleAtomSeq (atom_seq_for_self_rec j)))
blanchet@42001
   404
                |> n_fold_tuple_union
blanchet@35072
   405
              else
blanchet@42001
   406
                bound_tuples true]
blanchet@42001
   407
             |> distinct (op =)
blanchet@33192
   408
         end)
blanchet@33192
   409
    end
blanchet@41995
   410
  | bound_for_sel_rel _ _ _ _ u =
blanchet@33232
   411
    raise NUT ("Nitpick_Kodkod.bound_for_sel_rel", [u])
blanchet@33192
   412
blanchet@33192
   413
fun merge_bounds bs =
blanchet@33192
   414
  let
blanchet@33192
   415
    fun arity (zs, _) = fst (fst (hd zs))
blanchet@33192
   416
    fun add_bound ds b [] = List.revAppend (ds, [b])
blanchet@33192
   417
      | add_bound ds b (c :: cs) =
blanchet@33192
   418
        if arity b = arity c andalso snd b = snd c then
blanchet@33192
   419
          List.revAppend (ds, (fst c @ fst b, snd c) :: cs)
blanchet@33192
   420
        else
blanchet@33192
   421
          add_bound (c :: ds) b cs
blanchet@33192
   422
  in fold (add_bound []) bs [] end
blanchet@33192
   423
blanchet@34126
   424
fun unary_var_seq j0 n = map (curry KK.Var 1) (index_seq j0 n)
blanchet@33192
   425
blanchet@34126
   426
val singleton_from_combination = foldl1 KK.Product o map KK.Atom
blanchet@33192
   427
fun all_singletons_for_rep R =
blanchet@33192
   428
  if is_lone_rep R then
blanchet@33192
   429
    all_combinations_for_rep R |> map singleton_from_combination
blanchet@33192
   430
  else
blanchet@33232
   431
    raise REP ("Nitpick_Kodkod.all_singletons_for_rep", [R])
blanchet@33192
   432
blanchet@34126
   433
fun unpack_products (KK.Product (r1, r2)) =
blanchet@33192
   434
    unpack_products r1 @ unpack_products r2
blanchet@33192
   435
  | unpack_products r = [r]
blanchet@34126
   436
fun unpack_joins (KK.Join (r1, r2)) = unpack_joins r1 @ unpack_joins r2
blanchet@33192
   437
  | unpack_joins r = [r]
blanchet@33192
   438
blanchet@33192
   439
val empty_rel_for_rep = empty_n_ary_rel o arity_of_rep
blanchet@33192
   440
fun full_rel_for_rep R =
blanchet@33192
   441
  case atom_schema_of_rep R of
blanchet@33232
   442
    [] => raise REP ("Nitpick_Kodkod.full_rel_for_rep", [R])
blanchet@34126
   443
  | schema => foldl1 KK.Product (map KK.AtomSeq schema)
blanchet@33192
   444
blanchet@33192
   445
fun decls_for_atom_schema j0 schema =
blanchet@34126
   446
  map2 (fn j => fn x => KK.DeclOne ((1, j), KK.AtomSeq x))
blanchet@33192
   447
       (index_seq j0 (length schema)) schema
blanchet@33192
   448
blanchet@33192
   449
fun d_n_ary_function ({kk_all, kk_join, kk_lone, kk_one, ...} : kodkod_constrs)
blanchet@33192
   450
                     R r =
blanchet@33192
   451
  let val body_R = body_rep R in
blanchet@33192
   452
    if is_lone_rep body_R then
blanchet@33192
   453
      let
blanchet@33192
   454
        val binder_schema = atom_schema_of_reps (binder_reps R)
blanchet@33192
   455
        val body_schema = atom_schema_of_rep body_R
blanchet@33192
   456
        val one = is_one_rep body_R
blanchet@34126
   457
        val opt_x = case r of KK.Rel x => SOME x | _ => NONE
blanchet@33192
   458
      in
blanchet@34936
   459
        if opt_x <> NONE andalso length binder_schema = 1 andalso
blanchet@34936
   460
           length body_schema = 1 then
blanchet@34126
   461
          (if one then KK.Function else KK.Functional)
blanchet@34126
   462
              (the opt_x, KK.AtomSeq (hd binder_schema),
blanchet@34126
   463
               KK.AtomSeq (hd body_schema))
blanchet@33192
   464
        else
blanchet@33192
   465
          let
blanchet@33192
   466
            val decls = decls_for_atom_schema ~1 binder_schema
blanchet@33192
   467
            val vars = unary_var_seq ~1 (length binder_schema)
blanchet@33192
   468
            val kk_xone = if one then kk_one else kk_lone
blanchet@33192
   469
          in kk_all decls (kk_xone (fold kk_join vars r)) end
blanchet@33192
   470
      end
blanchet@33192
   471
    else
blanchet@34126
   472
      KK.True
blanchet@33192
   473
  end
blanchet@34126
   474
fun kk_n_ary_function kk R (r as KK.Rel x) =
blanchet@33192
   475
    if not (is_opt_rep R) then
blanchet@34124
   476
      if x = suc_rel then
blanchet@34126
   477
        KK.False
blanchet@34124
   478
      else if x = nat_add_rel then
blanchet@33192
   479
        formula_for_bool (card_of_rep (body_rep R) = 1)
blanchet@34124
   480
      else if x = nat_multiply_rel then
blanchet@33192
   481
        formula_for_bool (card_of_rep (body_rep R) <= 2)
blanchet@33192
   482
      else
blanchet@33192
   483
        d_n_ary_function kk R r
blanchet@34124
   484
    else if x = nat_subtract_rel then
blanchet@34126
   485
      KK.True
blanchet@33192
   486
    else
blanchet@33192
   487
      d_n_ary_function kk R r
blanchet@33192
   488
  | kk_n_ary_function kk R r = d_n_ary_function kk R r
blanchet@33192
   489
blanchet@34126
   490
fun kk_disjoint_sets _ [] = KK.True
blanchet@33192
   491
  | kk_disjoint_sets (kk as {kk_and, kk_no, kk_intersect, ...} : kodkod_constrs)
blanchet@33192
   492
                     (r :: rs) =
blanchet@33192
   493
    fold (kk_and o kk_no o kk_intersect r) rs (kk_disjoint_sets kk rs)
blanchet@33192
   494
blanchet@34124
   495
fun basic_rel_rel_let j ({kk_rel_let, ...} : kodkod_constrs) f r =
blanchet@33192
   496
  if inline_rel_expr r then
blanchet@33192
   497
    f r
blanchet@33192
   498
  else
blanchet@34126
   499
    let val x = (KK.arity_of_rel_expr r, j) in
blanchet@34126
   500
      kk_rel_let [KK.AssignRelReg (x, r)] (f (KK.RelReg x))
blanchet@33192
   501
    end
blanchet@34124
   502
val single_rel_rel_let = basic_rel_rel_let 0
blanchet@34124
   503
fun double_rel_rel_let kk f r1 r2 =
blanchet@34124
   504
  single_rel_rel_let kk (fn r1 => basic_rel_rel_let 1 kk (f r1) r2) r1
blanchet@35386
   505
fun triple_rel_rel_let kk f r1 r2 r3 =
blanchet@34124
   506
  double_rel_rel_let kk
blanchet@34124
   507
      (fn r1 => fn r2 => basic_rel_rel_let 2 kk (f r1 r2) r3) r1 r2
blanchet@33192
   508
blanchet@33192
   509
fun atom_from_formula ({kk_rel_if, ...} : kodkod_constrs) j0 f =
blanchet@34126
   510
  kk_rel_if f (KK.Atom (j0 + 1)) (KK.Atom j0)
blanchet@33192
   511
fun rel_expr_from_formula kk R f =
blanchet@33192
   512
  case unopt_rep R of
blanchet@33192
   513
    Atom (2, j0) => atom_from_formula kk j0 f
blanchet@33232
   514
  | _ => raise REP ("Nitpick_Kodkod.rel_expr_from_formula", [R])
blanchet@33192
   515
blanchet@33192
   516
fun unpack_vect_in_chunks ({kk_project_seq, ...} : kodkod_constrs) chunk_arity
blanchet@33192
   517
                          num_chunks r =
blanchet@33192
   518
  List.tabulate (num_chunks, fn j => kk_project_seq r (j * chunk_arity)
blanchet@33192
   519
                                                    chunk_arity)
blanchet@33192
   520
blanchet@33192
   521
fun kk_n_fold_join
blanchet@33192
   522
        (kk as {kk_intersect, kk_product, kk_join, kk_project_seq, ...}) one R1
blanchet@33192
   523
        res_R r1 r2 =
blanchet@33192
   524
  case arity_of_rep R1 of
blanchet@33192
   525
    1 => kk_join r1 r2
blanchet@33192
   526
  | arity1 =>
blanchet@38164
   527
    let val unpacked_rs1 = unpack_products r1 in
blanchet@33192
   528
      if one andalso length unpacked_rs1 = arity1 then
blanchet@33192
   529
        fold kk_join unpacked_rs1 r2
blanchet@38164
   530
      else if one andalso inline_rel_expr r1 then
blanchet@38164
   531
        fold kk_join (unpack_vect_in_chunks kk 1 arity1 r1) r2
blanchet@33192
   532
      else
blanchet@33192
   533
        kk_project_seq
blanchet@33192
   534
            (kk_intersect (kk_product r1 (full_rel_for_rep res_R)) r2)
blanchet@33192
   535
            arity1 (arity_of_rep res_R)
blanchet@33192
   536
    end
blanchet@33192
   537
blanchet@33192
   538
fun kk_case_switch (kk as {kk_union, kk_product, ...}) R1 R2 r rs1 rs2 =
blanchet@33192
   539
  if rs1 = rs2 then r
blanchet@33192
   540
  else kk_n_fold_join kk true R1 R2 r (fold1 kk_union (map2 kk_product rs1 rs2))
blanchet@33192
   541
blanchet@33192
   542
val lone_rep_fallback_max_card = 4096
blanchet@33192
   543
val some_j0 = 0
blanchet@33192
   544
blanchet@33192
   545
fun lone_rep_fallback kk new_R old_R r =
blanchet@33192
   546
  if old_R = new_R then
blanchet@33192
   547
    r
blanchet@33192
   548
  else
blanchet@33192
   549
    let val card = card_of_rep old_R in
blanchet@34936
   550
      if is_lone_rep old_R andalso is_lone_rep new_R andalso
blanchet@34936
   551
         card = card_of_rep new_R then
blanchet@33192
   552
        if card >= lone_rep_fallback_max_card then
blanchet@34124
   553
          raise TOO_LARGE ("Nitpick_Kodkod.lone_rep_fallback",
blanchet@34124
   554
                           "too high cardinality (" ^ string_of_int card ^ ")")
blanchet@33192
   555
        else
blanchet@33192
   556
          kk_case_switch kk old_R new_R r (all_singletons_for_rep old_R)
blanchet@33192
   557
                         (all_singletons_for_rep new_R)
blanchet@33192
   558
      else
blanchet@33232
   559
        raise REP ("Nitpick_Kodkod.lone_rep_fallback", [old_R, new_R])
blanchet@33192
   560
    end
blanchet@35280
   561
and atom_from_rel_expr kk x old_R r =
blanchet@33192
   562
  case old_R of
blanchet@33192
   563
    Func (R1, R2) =>
blanchet@33192
   564
    let
blanchet@33192
   565
      val dom_card = card_of_rep R1
blanchet@33192
   566
      val R2' = case R2 of Atom _ => R2 | _ => Atom (card_of_rep R2, some_j0)
blanchet@33192
   567
    in
blanchet@33192
   568
      atom_from_rel_expr kk x (Vect (dom_card, R2'))
blanchet@33192
   569
                         (vect_from_rel_expr kk dom_card R2' old_R r)
blanchet@33192
   570
    end
blanchet@33232
   571
  | Opt _ => raise REP ("Nitpick_Kodkod.atom_from_rel_expr", [old_R])
blanchet@33192
   572
  | _ => lone_rep_fallback kk (Atom x) old_R r
blanchet@33192
   573
and struct_from_rel_expr kk Rs old_R r =
blanchet@33192
   574
  case old_R of
blanchet@33192
   575
    Atom _ => lone_rep_fallback kk (Struct Rs) old_R r
blanchet@33192
   576
  | Struct Rs' =>
blanchet@38190
   577
    if Rs' = Rs then
blanchet@38190
   578
      r
blanchet@38190
   579
    else if map card_of_rep Rs' = map card_of_rep Rs then
blanchet@38190
   580
      let
blanchet@38190
   581
        val old_arities = map arity_of_rep Rs'
blanchet@38190
   582
        val old_offsets = offset_list old_arities
blanchet@38190
   583
        val old_rs = map2 (#kk_project_seq kk r) old_offsets old_arities
blanchet@38190
   584
      in
blanchet@38190
   585
        fold1 (#kk_product kk)
blanchet@38190
   586
              (map3 (rel_expr_from_rel_expr kk) Rs Rs' old_rs)
blanchet@38190
   587
      end
blanchet@38190
   588
    else
blanchet@38190
   589
      lone_rep_fallback kk (Struct Rs) old_R r
blanchet@33232
   590
  | _ => raise REP ("Nitpick_Kodkod.struct_from_rel_expr", [old_R])
blanchet@33192
   591
and vect_from_rel_expr kk k R old_R r =
blanchet@33192
   592
  case old_R of
blanchet@33192
   593
    Atom _ => lone_rep_fallback kk (Vect (k, R)) old_R r
blanchet@33192
   594
  | Vect (k', R') =>
blanchet@33192
   595
    if k = k' andalso R = R' then r
blanchet@33192
   596
    else lone_rep_fallback kk (Vect (k, R)) old_R r
blanchet@33192
   597
  | Func (R1, Formula Neut) =>
blanchet@33192
   598
    if k = card_of_rep R1 then
blanchet@33192
   599
      fold1 (#kk_product kk)
blanchet@33192
   600
            (map (fn arg_r =>
blanchet@33192
   601
                     rel_expr_from_formula kk R (#kk_subset kk arg_r r))
blanchet@33192
   602
                 (all_singletons_for_rep R1))
blanchet@33192
   603
    else
blanchet@33232
   604
      raise REP ("Nitpick_Kodkod.vect_from_rel_expr", [old_R])
blanchet@33192
   605
  | Func (R1, R2) =>
blanchet@33192
   606
    fold1 (#kk_product kk)
blanchet@33192
   607
          (map (fn arg_r =>
blanchet@33192
   608
                   rel_expr_from_rel_expr kk R R2
blanchet@33192
   609
                                         (kk_n_fold_join kk true R1 R2 arg_r r))
blanchet@33192
   610
               (all_singletons_for_rep R1))
blanchet@33232
   611
  | _ => raise REP ("Nitpick_Kodkod.vect_from_rel_expr", [old_R])
blanchet@33192
   612
and func_from_no_opt_rel_expr kk R1 R2 (Atom x) r =
blanchet@33192
   613
    let
blanchet@33192
   614
      val dom_card = card_of_rep R1
blanchet@33192
   615
      val R2' = case R2 of Atom _ => R2 | _ => Atom (card_of_rep R2, some_j0)
blanchet@33192
   616
    in
blanchet@33192
   617
      func_from_no_opt_rel_expr kk R1 R2 (Vect (dom_card, R2'))
blanchet@33192
   618
                                (vect_from_rel_expr kk dom_card R2' (Atom x) r)
blanchet@33192
   619
    end
blanchet@33192
   620
  | func_from_no_opt_rel_expr kk R1 (Formula Neut) old_R r =
blanchet@33192
   621
    (case old_R of
blanchet@33192
   622
       Vect (k, Atom (2, j0)) =>
blanchet@33192
   623
       let
blanchet@33192
   624
         val args_rs = all_singletons_for_rep R1
blanchet@33192
   625
         val vals_rs = unpack_vect_in_chunks kk 1 k r
blanchet@33192
   626
         fun empty_or_singleton_set_for arg_r val_r =
blanchet@34126
   627
           #kk_join kk val_r (#kk_product kk (KK.Atom (j0 + 1)) arg_r)
blanchet@33192
   628
       in
blanchet@33192
   629
         fold1 (#kk_union kk) (map2 empty_or_singleton_set_for args_rs vals_rs)
blanchet@33192
   630
       end
blanchet@33192
   631
     | Func (R1', Formula Neut) =>
blanchet@33192
   632
       if R1 = R1' then
blanchet@33192
   633
         r
blanchet@33192
   634
       else
blanchet@33192
   635
         let
blanchet@33192
   636
           val schema = atom_schema_of_rep R1
blanchet@33192
   637
           val r1 = fold1 (#kk_product kk) (unary_var_seq ~1 (length schema))
blanchet@33192
   638
                    |> rel_expr_from_rel_expr kk R1' R1
blanchet@33582
   639
           val kk_xeq = (if is_one_rep R1' then #kk_subset else #kk_rel_eq) kk
blanchet@33192
   640
         in
blanchet@33582
   641
           #kk_comprehension kk (decls_for_atom_schema ~1 schema) (kk_xeq r1 r)
blanchet@33192
   642
         end
blanchet@33192
   643
     | Func (R1', Atom (2, j0)) =>
blanchet@33192
   644
       func_from_no_opt_rel_expr kk R1 (Formula Neut)
blanchet@34126
   645
           (Func (R1', Formula Neut)) (#kk_join kk r (KK.Atom (j0 + 1)))
blanchet@33232
   646
     | _ => raise REP ("Nitpick_Kodkod.func_from_no_opt_rel_expr",
blanchet@33192
   647
                       [old_R, Func (R1, Formula Neut)]))
blanchet@33192
   648
  | func_from_no_opt_rel_expr kk R1 R2 old_R r =
blanchet@33192
   649
    case old_R of
blanchet@33192
   650
      Vect (k, R) =>
blanchet@33192
   651
      let
blanchet@33192
   652
        val args_rs = all_singletons_for_rep R1
blanchet@33192
   653
        val vals_rs = unpack_vect_in_chunks kk (arity_of_rep R) k r
blanchet@33192
   654
                      |> map (rel_expr_from_rel_expr kk R2 R)
blanchet@33192
   655
      in fold1 (#kk_union kk) (map2 (#kk_product kk) args_rs vals_rs) end
blanchet@33192
   656
    | Func (R1', Formula Neut) =>
blanchet@33192
   657
      (case R2 of
blanchet@33192
   658
         Atom (x as (2, j0)) =>
blanchet@33192
   659
         let val schema = atom_schema_of_rep R1 in
blanchet@33192
   660
           if length schema = 1 then
blanchet@34126
   661
             #kk_override kk (#kk_product kk (KK.AtomSeq (hd schema))
blanchet@34126
   662
                                             (KK.Atom j0))
blanchet@34126
   663
                             (#kk_product kk r (KK.Atom (j0 + 1)))
blanchet@33192
   664
           else
blanchet@33192
   665
             let
blanchet@33192
   666
               val r1 = fold1 (#kk_product kk) (unary_var_seq ~1 (length schema))
blanchet@33192
   667
                        |> rel_expr_from_rel_expr kk R1' R1
blanchet@34126
   668
               val r2 = KK.Var (1, ~(length schema) - 1)
blanchet@33192
   669
               val r3 = atom_from_formula kk j0 (#kk_subset kk r1 r)
blanchet@33192
   670
             in
blanchet@33192
   671
               #kk_comprehension kk (decls_for_atom_schema ~1 (schema @ [x]))
blanchet@33582
   672
                                 (#kk_subset kk r2 r3)
blanchet@33192
   673
             end
blanchet@33192
   674
           end
blanchet@33232
   675
         | _ => raise REP ("Nitpick_Kodkod.func_from_no_opt_rel_expr",
blanchet@33192
   676
                           [old_R, Func (R1, R2)]))
blanchet@33192
   677
    | Func (R1', R2') =>
blanchet@33192
   678
      if R1 = R1' andalso R2 = R2' then
blanchet@33192
   679
        r
blanchet@33192
   680
      else
blanchet@33192
   681
        let
blanchet@33192
   682
          val dom_schema = atom_schema_of_rep R1
blanchet@33192
   683
          val ran_schema = atom_schema_of_rep R2
blanchet@33192
   684
          val dom_prod = fold1 (#kk_product kk)
blanchet@33192
   685
                               (unary_var_seq ~1 (length dom_schema))
blanchet@33192
   686
                         |> rel_expr_from_rel_expr kk R1' R1
blanchet@33192
   687
          val ran_prod = fold1 (#kk_product kk)
blanchet@33192
   688
                               (unary_var_seq (~(length dom_schema) - 1)
blanchet@33192
   689
                                              (length ran_schema))
blanchet@33192
   690
                         |> rel_expr_from_rel_expr kk R2' R2
blanchet@33192
   691
          val app = kk_n_fold_join kk true R1' R2' dom_prod r
blanchet@33582
   692
          val kk_xeq = (if is_one_rep R2' then #kk_subset else #kk_rel_eq) kk
blanchet@33192
   693
        in
blanchet@33192
   694
          #kk_comprehension kk (decls_for_atom_schema ~1
blanchet@33192
   695
                                                      (dom_schema @ ran_schema))
blanchet@33582
   696
                               (kk_xeq ran_prod app)
blanchet@33192
   697
        end
blanchet@33232
   698
    | _ => raise REP ("Nitpick_Kodkod.func_from_no_opt_rel_expr",
blanchet@33192
   699
                      [old_R, Func (R1, R2)])
blanchet@33192
   700
and rel_expr_from_rel_expr kk new_R old_R r =
blanchet@33192
   701
  let
blanchet@33192
   702
    val unopt_old_R = unopt_rep old_R
blanchet@33192
   703
    val unopt_new_R = unopt_rep new_R
blanchet@33192
   704
  in
blanchet@33192
   705
    if unopt_old_R <> old_R andalso unopt_new_R = new_R then
blanchet@33232
   706
      raise REP ("Nitpick_Kodkod.rel_expr_from_rel_expr", [old_R, new_R])
blanchet@33192
   707
    else if unopt_new_R = unopt_old_R then
blanchet@33192
   708
      r
blanchet@33192
   709
    else
blanchet@33192
   710
      (case unopt_new_R of
blanchet@33192
   711
         Atom x => atom_from_rel_expr kk x
blanchet@33192
   712
       | Struct Rs => struct_from_rel_expr kk Rs
blanchet@33192
   713
       | Vect (k, R') => vect_from_rel_expr kk k R'
blanchet@33192
   714
       | Func (R1, R2) => func_from_no_opt_rel_expr kk R1 R2
blanchet@33232
   715
       | _ => raise REP ("Nitpick_Kodkod.rel_expr_from_rel_expr",
blanchet@33192
   716
                         [old_R, new_R]))
blanchet@33192
   717
          unopt_old_R r
blanchet@33192
   718
  end
blanchet@33192
   719
and rel_expr_to_func kk R1 R2 = rel_expr_from_rel_expr kk (Func (R1, R2))
blanchet@33192
   720
blanchet@34124
   721
fun bit_set_from_atom ({kk_join, ...} : kodkod_constrs) T r =
blanchet@34126
   722
  kk_join r (KK.Rel (if T = @{typ "unsigned_bit word"} then
blanchet@34126
   723
                       unsigned_bit_word_sel_rel
blanchet@34126
   724
                     else
blanchet@34126
   725
                       signed_bit_word_sel_rel))
blanchet@34126
   726
val int_expr_from_atom = KK.SetSum ooo bit_set_from_atom
blanchet@34124
   727
fun atom_from_int_expr (kk as {kk_rel_eq, kk_comprehension, ...}
blanchet@34124
   728
                        : kodkod_constrs) T R i =
blanchet@34124
   729
  kk_comprehension (decls_for_atom_schema ~1 (atom_schema_of_rep R))
blanchet@34126
   730
                   (kk_rel_eq (bit_set_from_atom kk T (KK.Var (1, ~1)))
blanchet@34126
   731
                              (KK.Bits i))
blanchet@34124
   732
blanchet@35280
   733
fun kodkod_formula_from_nut ofs
blanchet@33192
   734
        (kk as {kk_all, kk_exist, kk_formula_let, kk_formula_if, kk_or, kk_not,
blanchet@35072
   735
                kk_iff, kk_implies, kk_and, kk_subset, kk_rel_eq, kk_no,
blanchet@39456
   736
                kk_lone, kk_some, kk_rel_let, kk_rel_if, kk_union,
blanchet@35072
   737
                kk_difference, kk_intersect, kk_product, kk_join, kk_closure,
blanchet@35072
   738
                kk_comprehension, kk_project, kk_project_seq, kk_not3,
blanchet@35072
   739
                kk_nat_less, kk_int_less, ...}) u =
blanchet@33192
   740
  let
blanchet@33192
   741
    val main_j0 = offset_of_type ofs bool_T
blanchet@33192
   742
    val bool_j0 = main_j0
blanchet@33192
   743
    val bool_atom_R = Atom (2, main_j0)
blanchet@34126
   744
    val false_atom = KK.Atom bool_j0
blanchet@34126
   745
    val true_atom = KK.Atom (bool_j0 + 1)
blanchet@33192
   746
    fun formula_from_opt_atom polar j0 r =
blanchet@33192
   747
      case polar of
blanchet@34126
   748
        Neg => kk_not (kk_rel_eq r (KK.Atom j0))
blanchet@34126
   749
      | _ => kk_rel_eq r (KK.Atom (j0 + 1))
blanchet@33192
   750
    val formula_from_atom = formula_from_opt_atom Pos
blanchet@33192
   751
    val unpack_formulas =
blanchet@33192
   752
      map (formula_from_atom bool_j0) oo unpack_vect_in_chunks kk 1
blanchet@33192
   753
    fun kk_vect_set_bool_op connective k r1 r2 =
blanchet@33192
   754
      fold1 kk_and (map2 connective (unpack_formulas k r1)
blanchet@33192
   755
                         (unpack_formulas k r2))
blanchet@33192
   756
    fun to_f u =
blanchet@33192
   757
      case rep_of u of
blanchet@33192
   758
        Formula polar =>
blanchet@33192
   759
        (case u of
blanchet@34126
   760
           Cst (False, _, _) => KK.False
blanchet@34126
   761
         | Cst (True, _, _) => KK.True
blanchet@33854
   762
         | Op1 (Not, _, _, u1) =>
blanchet@33854
   763
           kk_not (to_f_with_polarity (flip_polarity polar) u1)
blanchet@33192
   764
         | Op1 (Finite, _, _, u1) =>
blanchet@33192
   765
           let val opt1 = is_opt_rep (rep_of u1) in
blanchet@33192
   766
             case polar of
blanchet@34936
   767
               Neut =>
blanchet@34936
   768
               if opt1 then raise NUT ("Nitpick_Kodkod.to_f (Finite)", [u])
blanchet@34936
   769
               else KK.True
blanchet@33192
   770
             | Pos => formula_for_bool (not opt1)
blanchet@34126
   771
             | Neg => KK.True
blanchet@33192
   772
           end
blanchet@34936
   773
         | Op1 (IsUnknown, _, _, u1) => kk_no (to_r u1)
blanchet@33192
   774
         | Op1 (Cast, _, _, u1) => to_f_with_polarity polar u1
blanchet@33854
   775
         | Op2 (All, _, _, u1, u2) =>
blanchet@33854
   776
           kk_all (untuple to_decl u1) (to_f_with_polarity polar u2)
blanchet@33854
   777
         | Op2 (Exist, _, _, u1, u2) =>
blanchet@33854
   778
           kk_exist (untuple to_decl u1) (to_f_with_polarity polar u2)
blanchet@33854
   779
         | Op2 (Or, _, _, u1, u2) =>
blanchet@33854
   780
           kk_or (to_f_with_polarity polar u1) (to_f_with_polarity polar u2)
blanchet@33854
   781
         | Op2 (And, _, _, u1, u2) =>
blanchet@33854
   782
           kk_and (to_f_with_polarity polar u1) (to_f_with_polarity polar u2)
blanchet@33192
   783
         | Op2 (Less, T, Formula polar, u1, u2) =>
blanchet@33192
   784
           formula_from_opt_atom polar bool_j0
blanchet@33192
   785
               (to_r (Op2 (Less, T, Opt bool_atom_R, u1, u2)))
blanchet@33192
   786
         | Op2 (Subset, _, _, u1, u2) =>
blanchet@33192
   787
           let
blanchet@46086
   788
             val dom_T = pseudo_domain_type (type_of u1)
blanchet@33192
   789
             val R1 = rep_of u1
blanchet@33192
   790
             val R2 = rep_of u2
blanchet@33192
   791
             val (dom_R, ran_R) =
blanchet@33192
   792
               case min_rep R1 R2 of
blanchet@38190
   793
                 Func Rp => Rp
blanchet@33192
   794
               | R => (Atom (card_of_domain_from_rep 2 R,
blanchet@33192
   795
                             offset_of_type ofs dom_T),
blanchet@33192
   796
                       if is_opt_rep R then Opt bool_atom_R else Formula Neut)
blanchet@33192
   797
             val set_R = Func (dom_R, ran_R)
blanchet@33192
   798
           in
blanchet@33192
   799
             if not (is_opt_rep ran_R) then
blanchet@33192
   800
               to_set_bool_op kk_implies kk_subset u1 u2
blanchet@33192
   801
             else if polar = Neut then
blanchet@33232
   802
               raise NUT ("Nitpick_Kodkod.to_f (Subset)", [u])
blanchet@33192
   803
             else
blanchet@33192
   804
               let
blanchet@33886
   805
                 (* FIXME: merge with similar code below *)
blanchet@33192
   806
                 fun set_to_r widen u =
blanchet@33192
   807
                   if widen then
blanchet@33192
   808
                     kk_difference (full_rel_for_rep dom_R)
blanchet@33192
   809
                                   (kk_join (to_rep set_R u) false_atom)
blanchet@33192
   810
                   else
blanchet@33192
   811
                     kk_join (to_rep set_R u) true_atom
blanchet@33192
   812
                 val widen1 = (polar = Pos andalso is_opt_rep R1)
blanchet@33192
   813
                 val widen2 = (polar = Neg andalso is_opt_rep R2)
blanchet@33192
   814
               in kk_subset (set_to_r widen1 u1) (set_to_r widen2 u2) end
blanchet@33192
   815
           end
blanchet@33192
   816
         | Op2 (DefEq, _, _, u1, u2) =>
blanchet@33192
   817
           (case min_rep (rep_of u1) (rep_of u2) of
blanchet@38190
   818
              Formula polar =>
blanchet@33192
   819
              kk_iff (to_f_with_polarity polar u1) (to_f_with_polarity polar u2)
blanchet@33192
   820
            | min_R =>
blanchet@33192
   821
              let
blanchet@33192
   822
                fun args (Op2 (Apply, _, _, u1, u2)) = u2 :: args u1
blanchet@33192
   823
                  | args (Tuple (_, _, us)) = us
blanchet@33192
   824
                  | args _ = []
blanchet@33192
   825
                val opt_arg_us = filter (is_opt_rep o rep_of) (args u1)
blanchet@33192
   826
              in
blanchet@34936
   827
                if null opt_arg_us orelse not (is_Opt min_R) orelse
blanchet@34936
   828
                   is_eval_name u1 then
blanchet@33192
   829
                  fold (kk_or o (kk_no o to_r)) opt_arg_us
blanchet@33192
   830
                       (kk_rel_eq (to_rep min_R u1) (to_rep min_R u2))
blanchet@33192
   831
                else
blanchet@34121
   832
                  kk_subset (to_rep min_R u1) (to_rep min_R u2)
blanchet@33192
   833
              end)
blanchet@35280
   834
         | Op2 (Eq, _, _, u1, u2) =>
blanchet@33192
   835
           (case min_rep (rep_of u1) (rep_of u2) of
blanchet@38190
   836
              Formula polar =>
blanchet@33192
   837
              kk_iff (to_f_with_polarity polar u1) (to_f_with_polarity polar u2)
blanchet@33192
   838
            | min_R =>
blanchet@33192
   839
              if is_opt_rep min_R then
blanchet@33192
   840
                if polar = Neut then
blanchet@33192
   841
                  (* continuation of hackish optimization *)
blanchet@33192
   842
                  kk_rel_eq (to_rep min_R u1) (to_rep min_R u2)
blanchet@33192
   843
                else if is_Cst Unrep u1 then
blanchet@33192
   844
                  to_could_be_unrep (polar = Neg) u2
blanchet@33192
   845
                else if is_Cst Unrep u2 then
blanchet@33192
   846
                  to_could_be_unrep (polar = Neg) u1
blanchet@33192
   847
                else
blanchet@33192
   848
                  let
blanchet@33192
   849
                    val r1 = to_rep min_R u1
blanchet@33192
   850
                    val r2 = to_rep min_R u2
blanchet@33192
   851
                    val both_opt = forall (is_opt_rep o rep_of) [u1, u2]
blanchet@33192
   852
                  in
blanchet@33192
   853
                    (if polar = Pos then
blanchet@33192
   854
                       if not both_opt then
blanchet@33192
   855
                         kk_rel_eq r1 r2
blanchet@34936
   856
                       else if is_lone_rep min_R andalso
blanchet@34936
   857
                               arity_of_rep min_R = 1 then
blanchet@33192
   858
                         kk_some (kk_intersect r1 r2)
blanchet@33192
   859
                       else
blanchet@33192
   860
                         raise SAME ()
blanchet@33192
   861
                     else
blanchet@33192
   862
                       if is_lone_rep min_R then
blanchet@33192
   863
                         if arity_of_rep min_R = 1 then
blanchet@35072
   864
                           kk_lone (kk_union r1 r2)
blanchet@33192
   865
                         else if not both_opt then
blanchet@33192
   866
                           (r1, r2) |> is_opt_rep (rep_of u2) ? swap
blanchet@34121
   867
                                    |-> kk_subset
blanchet@33192
   868
                         else
blanchet@33192
   869
                           raise SAME ()
blanchet@33192
   870
                       else
blanchet@33192
   871
                         raise SAME ())
blanchet@33192
   872
                    handle SAME () =>
blanchet@33192
   873
                           formula_from_opt_atom polar bool_j0
blanchet@33192
   874
                               (to_guard [u1, u2] bool_atom_R
blanchet@33192
   875
                                         (rel_expr_from_formula kk bool_atom_R
blanchet@33192
   876
                                                            (kk_rel_eq r1 r2)))
blanchet@33192
   877
                  end
blanchet@33192
   878
              else
blanchet@33192
   879
                let
blanchet@33192
   880
                  val r1 = to_rep min_R u1
blanchet@33192
   881
                  val r2 = to_rep min_R u2
blanchet@33192
   882
                in
blanchet@33192
   883
                  if is_one_rep min_R then
blanchet@33192
   884
                    let
blanchet@33192
   885
                      val rs1 = unpack_products r1
blanchet@33192
   886
                      val rs2 = unpack_products r2
blanchet@33192
   887
                    in
blanchet@34936
   888
                      if length rs1 = length rs2 andalso
blanchet@34936
   889
                         map KK.arity_of_rel_expr rs1
blanchet@34936
   890
                         = map KK.arity_of_rel_expr rs2 then
blanchet@33192
   891
                        fold1 kk_and (map2 kk_subset rs1 rs2)
blanchet@33192
   892
                      else
blanchet@33192
   893
                        kk_subset r1 r2
blanchet@33192
   894
                    end
blanchet@33192
   895
                  else
blanchet@33192
   896
                    kk_rel_eq r1 r2
blanchet@33192
   897
                end)
blanchet@33192
   898
         | Op2 (Apply, T, _, u1, u2) =>
blanchet@33192
   899
           (case (polar, rep_of u1) of
blanchet@33192
   900
              (Neg, Func (R, Formula Neut)) => kk_subset (to_opt R u2) (to_r u1)
blanchet@33192
   901
            | _ =>
blanchet@33192
   902
              to_f_with_polarity polar
blanchet@33192
   903
                 (Op2 (Apply, T, Opt (Atom (2, offset_of_type ofs T)), u1, u2)))
blanchet@33192
   904
         | Op3 (Let, _, _, u1, u2, u3) =>
blanchet@33854
   905
           kk_formula_let [to_expr_assign u1 u2] (to_f_with_polarity polar u3)
blanchet@33192
   906
         | Op3 (If, _, _, u1, u2, u3) =>
blanchet@33854
   907
           kk_formula_if (to_f u1) (to_f_with_polarity polar u2)
blanchet@33854
   908
                         (to_f_with_polarity polar u3)
blanchet@34126
   909
         | FormulaReg (j, _, _) => KK.FormulaReg j
blanchet@33232
   910
         | _ => raise NUT ("Nitpick_Kodkod.to_f", [u]))
blanchet@33192
   911
      | Atom (2, j0) => formula_from_atom j0 (to_r u)
blanchet@33232
   912
      | _ => raise NUT ("Nitpick_Kodkod.to_f", [u])
blanchet@33192
   913
    and to_f_with_polarity polar u =
blanchet@33192
   914
      case rep_of u of
blanchet@33192
   915
        Formula _ => to_f u
blanchet@33192
   916
      | Atom (2, j0) => formula_from_atom j0 (to_r u)
blanchet@33192
   917
      | Opt (Atom (2, j0)) => formula_from_opt_atom polar j0 (to_r u)
blanchet@33232
   918
      | _ => raise NUT ("Nitpick_Kodkod.to_f_with_polarity", [u])
blanchet@33192
   919
    and to_r u =
blanchet@33192
   920
      case u of
blanchet@33192
   921
        Cst (False, _, Atom _) => false_atom
blanchet@33192
   922
      | Cst (True, _, Atom _) => true_atom
blanchet@35280
   923
      | Cst (Iden, _, Func (Struct [R1, R2], Formula Neut)) =>
blanchet@33192
   924
        if R1 = R2 andalso arity_of_rep R1 = 1 then
blanchet@34126
   925
          kk_intersect KK.Iden (kk_product (full_rel_for_rep R1) KK.Univ)
blanchet@33192
   926
        else
blanchet@33192
   927
          let
blanchet@33192
   928
            val schema1 = atom_schema_of_rep R1
blanchet@33192
   929
            val schema2 = atom_schema_of_rep R2
blanchet@33192
   930
            val arity1 = length schema1
blanchet@33192
   931
            val arity2 = length schema2
blanchet@33192
   932
            val r1 = fold1 kk_product (unary_var_seq 0 arity1)
blanchet@33192
   933
            val r2 = fold1 kk_product (unary_var_seq arity1 arity2)
blanchet@33192
   934
            val min_R = min_rep R1 R2
blanchet@33192
   935
          in
blanchet@33192
   936
            kk_comprehension
blanchet@33192
   937
                (decls_for_atom_schema 0 (schema1 @ schema2))
blanchet@33192
   938
                (kk_rel_eq (rel_expr_from_rel_expr kk min_R R1 r1)
blanchet@33192
   939
                           (rel_expr_from_rel_expr kk min_R R2 r2))
blanchet@33192
   940
          end
blanchet@35280
   941
      | Cst (Iden, _, Func (Atom (1, j0), Formula Neut)) => KK.Atom j0
blanchet@46100
   942
      | Cst (Iden, T as Type (@{type_name set}, [T1]), R as Func (R1, _)) =>
blanchet@33192
   943
        to_rep R (Cst (Iden, T, Func (one_rep ofs T1 R1, Formula Neut)))
blanchet@34124
   944
      | Cst (Num j, T, R) =>
blanchet@34124
   945
        if is_word_type T then
blanchet@34126
   946
          atom_from_int_expr kk T R (KK.Num j)
blanchet@34124
   947
        else if T = int_T then
blanchet@34124
   948
          case atom_for_int (card_of_rep R, offset_of_type ofs int_T) j of
blanchet@34126
   949
            ~1 => if is_opt_rep R then KK.None
blanchet@33232
   950
                  else raise NUT ("Nitpick_Kodkod.to_r (Num)", [u])
blanchet@34126
   951
          | j' => KK.Atom j'
blanchet@34124
   952
        else
blanchet@34126
   953
          if j < card_of_rep R then KK.Atom (j + offset_of_type ofs T)
blanchet@34126
   954
          else if is_opt_rep R then KK.None
blanchet@34124
   955
          else raise NUT ("Nitpick_Kodkod.to_r (Num)", [u])
blanchet@33192
   956
      | Cst (Unknown, _, R) => empty_rel_for_rep R
blanchet@33192
   957
      | Cst (Unrep, _, R) => empty_rel_for_rep R
blanchet@34126
   958
      | Cst (Suc, T as @{typ "unsigned_bit word => unsigned_bit word"}, R) =>
blanchet@34126
   959
        to_bit_word_unary_op T R (curry KK.Add (KK.Num 1))
blanchet@34126
   960
      | Cst (Suc, @{typ "nat => nat"}, Func (Atom x, _)) =>
blanchet@34126
   961
        kk_intersect (KK.Rel suc_rel) (kk_product KK.Univ (KK.AtomSeq x))
blanchet@35280
   962
      | Cst (Suc, _, Func (Atom _, _)) => KK.Rel suc_rel
blanchet@35665
   963
      | Cst (Add, Type (_, [@{typ nat}, _]), _) => KK.Rel nat_add_rel
blanchet@35665
   964
      | Cst (Add, Type (_, [@{typ int}, _]), _) => KK.Rel int_add_rel
blanchet@35665
   965
      | Cst (Add, T as Type (_, [@{typ "unsigned_bit word"}, _]), R) =>
blanchet@34126
   966
        to_bit_word_binary_op T R NONE (SOME (curry KK.Add))
blanchet@35665
   967
      | Cst (Add, T as Type (_, [@{typ "signed_bit word"}, _]), R) =>
blanchet@34124
   968
        to_bit_word_binary_op T R
blanchet@34124
   969
            (SOME (fn i1 => fn i2 => fn i3 =>
blanchet@34126
   970
                 kk_implies (KK.LE (KK.Num 0, KK.BitXor (i1, i2)))
blanchet@34126
   971
                            (KK.LE (KK.Num 0, KK.BitXor (i2, i3)))))
blanchet@34126
   972
            (SOME (curry KK.Add))
blanchet@35665
   973
      | Cst (Subtract, Type (_, [@{typ nat}, _]), _) =>
blanchet@34126
   974
        KK.Rel nat_subtract_rel
blanchet@35665
   975
      | Cst (Subtract, Type (_, [@{typ int}, _]), _) =>
blanchet@34126
   976
        KK.Rel int_subtract_rel
blanchet@35665
   977
      | Cst (Subtract, T as Type (_, [@{typ "unsigned_bit word"}, _]), R) =>
blanchet@34124
   978
        to_bit_word_binary_op T R NONE
blanchet@34124
   979
            (SOME (fn i1 => fn i2 =>
blanchet@34126
   980
                      KK.IntIf (KK.LE (i1, i2), KK.Num 0, KK.Sub (i1, i2))))
blanchet@35665
   981
      | Cst (Subtract, T as Type (_, [@{typ "signed_bit word"}, _]), R) =>
blanchet@34124
   982
        to_bit_word_binary_op T R
blanchet@34124
   983
            (SOME (fn i1 => fn i2 => fn i3 =>
blanchet@34126
   984
                 kk_implies (KK.LT (KK.BitXor (i1, i2), KK.Num 0))
blanchet@34126
   985
                            (KK.LT (KK.BitXor (i2, i3), KK.Num 0))))
blanchet@34126
   986
            (SOME (curry KK.Sub))
blanchet@35665
   987
      | Cst (Multiply, Type (_, [@{typ nat}, _]), _) =>
blanchet@34126
   988
        KK.Rel nat_multiply_rel
blanchet@35665
   989
      | Cst (Multiply, Type (_, [@{typ int}, _]), _) =>
blanchet@34126
   990
        KK.Rel int_multiply_rel
blanchet@34124
   991
      | Cst (Multiply,
blanchet@35665
   992
             T as Type (_, [Type (@{type_name word}, [bit_T]), _]), R) =>
blanchet@34124
   993
        to_bit_word_binary_op T R
blanchet@34124
   994
            (SOME (fn i1 => fn i2 => fn i3 =>
blanchet@34126
   995
                kk_or (KK.IntEq (i2, KK.Num 0))
blanchet@34126
   996
                      (KK.IntEq (KK.Div (i3, i2), i1)
blanchet@34124
   997
                       |> bit_T = @{typ signed_bit}
blanchet@34126
   998
                          ? kk_and (KK.LE (KK.Num 0,
blanchet@34126
   999
                                           foldl1 KK.BitAnd [i1, i2, i3])))))
blanchet@34126
  1000
            (SOME (curry KK.Mult))
blanchet@35665
  1001
      | Cst (Divide, Type (_, [@{typ nat}, _]), _) => KK.Rel nat_divide_rel
blanchet@35665
  1002
      | Cst (Divide, Type (_, [@{typ int}, _]), _) => KK.Rel int_divide_rel
blanchet@35665
  1003
      | Cst (Divide, T as Type (_, [@{typ "unsigned_bit word"}, _]), R) =>
blanchet@34124
  1004
        to_bit_word_binary_op T R NONE
blanchet@34124
  1005
            (SOME (fn i1 => fn i2 =>
blanchet@34126
  1006
                      KK.IntIf (KK.IntEq (i2, KK.Num 0),
blanchet@34126
  1007
                                KK.Num 0, KK.Div (i1, i2))))
blanchet@35665
  1008
      | Cst (Divide, T as Type (_, [@{typ "signed_bit word"}, _]), R) =>
blanchet@34124
  1009
        to_bit_word_binary_op T R
blanchet@34124
  1010
            (SOME (fn i1 => fn i2 => fn i3 =>
blanchet@34126
  1011
                      KK.LE (KK.Num 0, foldl1 KK.BitAnd [i1, i2, i3])))
blanchet@34124
  1012
            (SOME (fn i1 => fn i2 =>
blanchet@34126
  1013
                 KK.IntIf (kk_and (KK.LT (i1, KK.Num 0))
blanchet@34126
  1014
                                  (KK.LT (KK.Num 0, i2)),
blanchet@34126
  1015
                     KK.Sub (KK.Div (KK.Add (i1, KK.Num 1), i2), KK.Num 1),
blanchet@34126
  1016
                     KK.IntIf (kk_and (KK.LT (KK.Num 0, i1))
blanchet@34126
  1017
                                      (KK.LT (i2, KK.Num 0)),
blanchet@34126
  1018
                         KK.Sub (KK.Div (KK.Sub (i1, KK.Num 1), i2), KK.Num 1),
blanchet@34126
  1019
                         KK.IntIf (KK.IntEq (i2, KK.Num 0),
blanchet@34126
  1020
                                   KK.Num 0, KK.Div (i1, i2))))))
blanchet@34126
  1021
      | Cst (Gcd, _, _) => KK.Rel gcd_rel
blanchet@34126
  1022
      | Cst (Lcm, _, _) => KK.Rel lcm_rel
blanchet@34126
  1023
      | Cst (Fracs, _, Func (Atom (1, _), _)) => KK.None
blanchet@33192
  1024
      | Cst (Fracs, _, Func (Struct _, _)) =>
blanchet@34126
  1025
        kk_project_seq (KK.Rel norm_frac_rel) 2 2
blanchet@34126
  1026
      | Cst (NormFrac, _, _) => KK.Rel norm_frac_rel
blanchet@35665
  1027
      | Cst (NatToInt, Type (_, [@{typ nat}, _]), Func (Atom _, Atom _)) =>
blanchet@34126
  1028
        KK.Iden
blanchet@35665
  1029
      | Cst (NatToInt, Type (_, [@{typ nat}, _]),
blanchet@35280
  1030
             Func (Atom (_, nat_j0), Opt (Atom (int_k, int_j0)))) =>
blanchet@33192
  1031
        if nat_j0 = int_j0 then
blanchet@34126
  1032
          kk_intersect KK.Iden
blanchet@34126
  1033
              (kk_product (KK.AtomSeq (max_int_for_card int_k + 1, nat_j0))
blanchet@34126
  1034
                          KK.Univ)
blanchet@33192
  1035
        else
blanchet@33232
  1036
          raise BAD ("Nitpick_Kodkod.to_r (NatToInt)", "\"nat_j0 <> int_j0\"")
blanchet@35665
  1037
      | Cst (NatToInt, T as Type (_, [@{typ "unsigned_bit word"}, _]), R) =>
blanchet@34124
  1038
        to_bit_word_unary_op T R I
blanchet@35665
  1039
      | Cst (IntToNat, Type (_, [@{typ int}, _]),
blanchet@34124
  1040
             Func (Atom (int_k, int_j0), nat_R)) =>
blanchet@33192
  1041
        let
blanchet@33192
  1042
          val abs_card = max_int_for_card int_k + 1
blanchet@33192
  1043
          val (nat_k, nat_j0) = the_single (atom_schema_of_rep nat_R)
blanchet@33192
  1044
          val overlap = Int.min (nat_k, abs_card)
blanchet@33192
  1045
        in
blanchet@33192
  1046
          if nat_j0 = int_j0 then
blanchet@34126
  1047
            kk_union (kk_product (KK.AtomSeq (int_k - abs_card,
blanchet@34126
  1048
                                              int_j0 + abs_card))
blanchet@34126
  1049
                                 (KK.Atom nat_j0))
blanchet@34126
  1050
                     (kk_intersect KK.Iden
blanchet@34126
  1051
                          (kk_product (KK.AtomSeq (overlap, int_j0)) KK.Univ))
blanchet@33192
  1052
          else
blanchet@33232
  1053
            raise BAD ("Nitpick_Kodkod.to_r (IntToNat)", "\"nat_j0 <> int_j0\"")
blanchet@33192
  1054
        end
blanchet@35665
  1055
      | Cst (IntToNat, T as Type (_, [@{typ "signed_bit word"}, _]), R) =>
blanchet@34124
  1056
        to_bit_word_unary_op T R
blanchet@34126
  1057
            (fn i => KK.IntIf (KK.LE (i, KK.Num 0), KK.Num 0, i))
blanchet@33192
  1058
      | Op1 (Not, _, R, u1) => kk_not3 (to_rep R u1)
blanchet@34126
  1059
      | Op1 (Finite, _, Opt (Atom _), _) => KK.None
blanchet@33192
  1060
      | Op1 (Converse, T, R, u1) =>
blanchet@33192
  1061
        let
blanchet@46744
  1062
          val (b_T, a_T) = HOLogic.dest_prodT (pseudo_domain_type T)
blanchet@33192
  1063
          val (b_R, a_R) =
blanchet@33192
  1064
            case R of
blanchet@33192
  1065
              Func (Struct [R1, R2], _) => (R1, R2)
blanchet@33192
  1066
            | Func (R1, _) =>
blanchet@33192
  1067
              if card_of_rep R1 <> 1 then
blanchet@33232
  1068
                raise REP ("Nitpick_Kodkod.to_r (Converse)", [R])
blanchet@33192
  1069
              else
blanchet@33192
  1070
                pairself (Atom o pair 1 o offset_of_type ofs) (b_T, a_T)
blanchet@33232
  1071
            | _ => raise REP ("Nitpick_Kodkod.to_r (Converse)", [R])
blanchet@33192
  1072
          val body_R = body_rep R
blanchet@33192
  1073
          val a_arity = arity_of_rep a_R
blanchet@33192
  1074
          val b_arity = arity_of_rep b_R
blanchet@33192
  1075
          val ab_arity = a_arity + b_arity
blanchet@33192
  1076
          val body_arity = arity_of_rep body_R
blanchet@33192
  1077
        in
blanchet@33192
  1078
          kk_project (to_rep (Func (Struct [a_R, b_R], body_R)) u1)
blanchet@34126
  1079
                     (map KK.Num (index_seq a_arity b_arity @
blanchet@34126
  1080
                                  index_seq 0 a_arity @
blanchet@34126
  1081
                                  index_seq ab_arity body_arity))
blanchet@33192
  1082
          |> rel_expr_from_rel_expr kk R (Func (Struct [b_R, a_R], body_R))
blanchet@33192
  1083
        end
blanchet@33192
  1084
      | Op1 (Closure, _, R, u1) =>
blanchet@33192
  1085
        if is_opt_rep R then
blanchet@33192
  1086
          let
blanchet@33192
  1087
            val T1 = type_of u1
blanchet@33192
  1088
            val R' = rep_to_binary_rel_rep ofs T1 (unopt_rep (rep_of u1))
blanchet@33192
  1089
            val R'' = opt_rep ofs T1 R'
blanchet@33192
  1090
          in
blanchet@34124
  1091
            single_rel_rel_let kk
blanchet@33192
  1092
                (fn r =>
blanchet@33192
  1093
                    let
blanchet@33192
  1094
                      val true_r = kk_closure (kk_join r true_atom)
blanchet@33192
  1095
                      val full_r = full_rel_for_rep R'
blanchet@33192
  1096
                      val false_r = kk_difference full_r
blanchet@33192
  1097
                                        (kk_closure (kk_difference full_r
blanchet@33192
  1098
                                                        (kk_join r false_atom)))
blanchet@33192
  1099
                    in
blanchet@33192
  1100
                      rel_expr_from_rel_expr kk R R''
blanchet@33192
  1101
                          (kk_union (kk_product true_r true_atom)
blanchet@33192
  1102
                                    (kk_product false_r false_atom))
blanchet@33192
  1103
                    end) (to_rep R'' u1)
blanchet@33192
  1104
          end
blanchet@33192
  1105
        else
blanchet@33192
  1106
          let val R' = rep_to_binary_rel_rep ofs (type_of u1) (rep_of u1) in
blanchet@33192
  1107
            rel_expr_from_rel_expr kk R R' (kk_closure (to_rep R' u1))
blanchet@33192
  1108
          end
blanchet@33192
  1109
      | Op1 (SingletonSet, _, Func (R1, Opt _), Cst (Unrep, _, _)) =>
blanchet@38190
  1110
        kk_product (full_rel_for_rep R1) false_atom
blanchet@33192
  1111
      | Op1 (SingletonSet, _, R, u1) =>
blanchet@33192
  1112
        (case R of
blanchet@33192
  1113
           Func (R1, Formula Neut) => to_rep R1 u1
blanchet@35280
  1114
         | Func (R1, Opt _) =>
blanchet@34124
  1115
           single_rel_rel_let kk
blanchet@33192
  1116
               (fn r => kk_rel_if (kk_no r) (empty_rel_for_rep R)
blanchet@33192
  1117
                            (rel_expr_to_func kk R1 bool_atom_R
blanchet@33192
  1118
                                              (Func (R1, Formula Neut)) r))
blanchet@33192
  1119
               (to_opt R1 u1)
blanchet@33232
  1120
         | _ => raise NUT ("Nitpick_Kodkod.to_r (SingletonSet)", [u]))
blanchet@35671
  1121
      | Op1 (SafeThe, _, R, u1) =>
blanchet@33192
  1122
        if is_opt_rep R then
blanchet@33192
  1123
          kk_join (to_rep (Func (unopt_rep R, Opt bool_atom_R)) u1) true_atom
blanchet@33192
  1124
        else
blanchet@33192
  1125
          to_rep (Func (R, Formula Neut)) u1
blanchet@39345
  1126
      | Op1 (First, _, R, u1) => to_nth_pair_sel 0 R u1
blanchet@39345
  1127
      | Op1 (Second, _, R, u1) => to_nth_pair_sel 1 R u1
blanchet@33192
  1128
      | Op1 (Cast, _, R, u1) =>
blanchet@33192
  1129
        ((case rep_of u1 of
blanchet@33192
  1130
            Formula _ =>
blanchet@33192
  1131
            (case unopt_rep R of
blanchet@33192
  1132
               Atom (2, j0) => atom_from_formula kk j0 (to_f u1)
blanchet@33192
  1133
             | _ => raise SAME ())
blanchet@33192
  1134
          | _ => raise SAME ())
blanchet@33192
  1135
         handle SAME () => rel_expr_from_rel_expr kk R (rep_of u1) (to_r u1))
blanchet@33192
  1136
      | Op2 (All, T, R as Opt _, u1, u2) =>
blanchet@33192
  1137
        to_r (Op1 (Not, T, R,
blanchet@33192
  1138
                   Op2 (Exist, T, R, u1, Op1 (Not, T, rep_of u2, u2))))
blanchet@35280
  1139
      | Op2 (Exist, _, Opt _, u1, u2) =>
blanchet@33192
  1140
        let val rs1 = untuple to_decl u1 in
blanchet@33192
  1141
          if not (is_opt_rep (rep_of u2)) then
blanchet@34126
  1142
            kk_rel_if (kk_exist rs1 (to_f u2)) true_atom KK.None
blanchet@33192
  1143
          else
blanchet@33192
  1144
            let val r2 = to_r u2 in
blanchet@33192
  1145
              kk_union (kk_rel_if (kk_exist rs1 (kk_rel_eq r2 true_atom))
blanchet@34126
  1146
                                  true_atom KK.None)
blanchet@33192
  1147
                       (kk_rel_if (kk_all rs1 (kk_rel_eq r2 false_atom))
blanchet@34126
  1148
                                  false_atom KK.None)
blanchet@33192
  1149
            end
blanchet@33192
  1150
        end
blanchet@33192
  1151
      | Op2 (Or, _, _, u1, u2) =>
blanchet@33192
  1152
        if is_opt_rep (rep_of u1) then kk_rel_if (to_f u2) true_atom (to_r u1)
blanchet@33192
  1153
        else kk_rel_if (to_f u1) true_atom (to_r u2)
blanchet@33192
  1154
      | Op2 (And, _, _, u1, u2) =>
blanchet@33192
  1155
        if is_opt_rep (rep_of u1) then kk_rel_if (to_f u2) (to_r u1) false_atom
blanchet@33192
  1156
        else kk_rel_if (to_f u1) (to_r u2) false_atom
blanchet@33192
  1157
      | Op2 (Less, _, _, u1, u2) =>
blanchet@34124
  1158
        (case type_of u1 of
blanchet@34124
  1159
           @{typ nat} =>
blanchet@34124
  1160
           if is_Cst Unrep u1 then to_compare_with_unrep u2 false_atom
blanchet@34124
  1161
           else if is_Cst Unrep u2 then to_compare_with_unrep u1 true_atom
blanchet@34124
  1162
           else kk_nat_less (to_integer u1) (to_integer u2)
blanchet@34124
  1163
         | @{typ int} => kk_int_less (to_integer u1) (to_integer u2)
blanchet@36127
  1164
         | _ =>
blanchet@36127
  1165
           let
blanchet@36127
  1166
             val R1 = Opt (Atom (card_of_rep (rep_of u1),
blanchet@36127
  1167
                                 offset_of_type ofs (type_of u1)))
blanchet@36127
  1168
           in
blanchet@36127
  1169
             double_rel_rel_let kk
blanchet@36127
  1170
                 (fn r1 => fn r2 =>
blanchet@36127
  1171
                     kk_rel_if
blanchet@36127
  1172
                         (fold kk_and (map_filter (fn (u, r) =>
blanchet@36127
  1173
                              if is_opt_rep (rep_of u) then SOME (kk_some r)
blanchet@36127
  1174
                              else NONE) [(u1, r1), (u2, r2)]) KK.True)
blanchet@36127
  1175
                         (atom_from_formula kk bool_j0 (KK.LT (pairself
blanchet@36127
  1176
                             (int_expr_from_atom kk (type_of u1)) (r1, r2))))
blanchet@36127
  1177
                         KK.None)
blanchet@36127
  1178
                 (to_rep R1 u1) (to_rep R1 u2)
blanchet@36127
  1179
            end)
blanchet@35280
  1180
      | Op2 (Triad, _, Opt (Atom (2, j0)), u1, u2) =>
blanchet@33192
  1181
        let
blanchet@33192
  1182
          val f1 = to_f u1
blanchet@33192
  1183
          val f2 = to_f u2
blanchet@33192
  1184
        in
blanchet@33192
  1185
          if f1 = f2 then
blanchet@33192
  1186
            atom_from_formula kk j0 f1
blanchet@33192
  1187
          else
blanchet@34126
  1188
            kk_union (kk_rel_if f1 true_atom KK.None)
blanchet@34126
  1189
                     (kk_rel_if f2 KK.None false_atom)
blanchet@33192
  1190
        end
blanchet@33192
  1191
      | Op2 (Composition, _, R, u1, u2) =>
blanchet@33192
  1192
        let
blanchet@46744
  1193
          val (a_T, b_T) = HOLogic.dest_prodT (pseudo_domain_type (type_of u1))
blanchet@46744
  1194
          val (_, c_T) = HOLogic.dest_prodT (pseudo_domain_type (type_of u2))
blanchet@33863
  1195
          val ab_k = card_of_domain_from_rep 2 (rep_of u1)
blanchet@33863
  1196
          val bc_k = card_of_domain_from_rep 2 (rep_of u2)
blanchet@33192
  1197
          val ac_k = card_of_domain_from_rep 2 R
blanchet@33192
  1198
          val a_k = exact_root 2 (ac_k * ab_k div bc_k)
blanchet@33192
  1199
          val b_k = exact_root 2 (ab_k * bc_k div ac_k)
blanchet@33192
  1200
          val c_k = exact_root 2 (bc_k * ac_k div ab_k)
blanchet@33192
  1201
          val a_R = Atom (a_k, offset_of_type ofs a_T)
blanchet@33192
  1202
          val b_R = Atom (b_k, offset_of_type ofs b_T)
blanchet@33192
  1203
          val c_R = Atom (c_k, offset_of_type ofs c_T)
blanchet@33192
  1204
          val body_R = body_rep R
blanchet@33192
  1205
        in
blanchet@33192
  1206
          (case body_R of
blanchet@33192
  1207
             Formula Neut =>
blanchet@33863
  1208
             kk_join (to_rep (Func (Struct [a_R, b_R], Formula Neut)) u1)
blanchet@33863
  1209
                     (to_rep (Func (Struct [b_R, c_R], Formula Neut)) u2)
blanchet@33192
  1210
           | Opt (Atom (2, _)) =>
blanchet@33192
  1211
             let
blanchet@33886
  1212
               (* FIXME: merge with similar code above *)
blanchet@33886
  1213
               fun must R1 R2 u =
blanchet@33886
  1214
                 kk_join (to_rep (Func (Struct [R1, R2], body_R)) u) true_atom
blanchet@33886
  1215
               fun may R1 R2 u =
blanchet@33886
  1216
                 kk_difference
blanchet@33886
  1217
                     (full_rel_for_rep (Struct [R1, R2]))
blanchet@33886
  1218
                     (kk_join (to_rep (Func (Struct [R1, R2], body_R)) u)
blanchet@33886
  1219
                              false_atom)
blanchet@33886
  1220
             in
blanchet@33886
  1221
               kk_union
blanchet@33886
  1222
                   (kk_product (kk_join (must a_R b_R u1) (must b_R c_R u2))
blanchet@33886
  1223
                               true_atom)
blanchet@33886
  1224
                   (kk_product (kk_difference
blanchet@33886
  1225
                                   (full_rel_for_rep (Struct [a_R, c_R]))
blanchet@33886
  1226
                                   (kk_join (may a_R b_R u1) (may b_R c_R u2)))
blanchet@33886
  1227
                               false_atom)
blanchet@33886
  1228
             end
blanchet@33232
  1229
           | _ => raise NUT ("Nitpick_Kodkod.to_r (Composition)", [u]))
blanchet@33192
  1230
          |> rel_expr_from_rel_expr kk R (Func (Struct [a_R, c_R], body_R))
blanchet@33192
  1231
        end
blanchet@33192
  1232
      | Op2 (Apply, @{typ nat}, _,
blanchet@33192
  1233
             Op2 (Apply, _, _, Cst (Subtract, _, _), u1), u2) =>
blanchet@33192
  1234
        if is_Cst Unrep u2 andalso not (is_opt_rep (rep_of u1)) then
blanchet@34126
  1235
          KK.Atom (offset_of_type ofs nat_T)
blanchet@33192
  1236
        else
blanchet@34126
  1237
          fold kk_join (map to_integer [u1, u2]) (KK.Rel nat_subtract_rel)
blanchet@35312
  1238
      | Op2 (Apply, _, R, u1, u2) => to_apply R u1 u2
blanchet@35280
  1239
      | Op2 (Lambda, _, R as Opt (Atom (1, j0)), u1, u2) =>
blanchet@34126
  1240
        to_guard [u1, u2] R (KK.Atom j0)
blanchet@35280
  1241
      | Op2 (Lambda, _, Func (_, Formula Neut), u1, u2) =>
blanchet@33192
  1242
        kk_comprehension (untuple to_decl u1) (to_f u2)
blanchet@35280
  1243
      | Op2 (Lambda, _, Func (_, R2), u1, u2) =>
blanchet@33192
  1244
        let
blanchet@33192
  1245
          val dom_decls = untuple to_decl u1
blanchet@33192
  1246
          val ran_schema = atom_schema_of_rep R2
blanchet@33192
  1247
          val ran_decls = decls_for_atom_schema ~1 ran_schema
blanchet@33192
  1248
          val ran_vars = unary_var_seq ~1 (length ran_decls)
blanchet@33192
  1249
        in
blanchet@33192
  1250
          kk_comprehension (dom_decls @ ran_decls)
blanchet@33192
  1251
                           (kk_subset (fold1 kk_product ran_vars)
blanchet@33192
  1252
                                      (to_rep R2 u2))
blanchet@33192
  1253
        end
blanchet@33192
  1254
      | Op3 (Let, _, R, u1, u2, u3) =>
blanchet@33192
  1255
        kk_rel_let [to_expr_assign u1 u2] (to_rep R u3)
blanchet@33192
  1256
      | Op3 (If, _, R, u1, u2, u3) =>
blanchet@33192
  1257
        if is_opt_rep (rep_of u1) then
blanchet@35386
  1258
          triple_rel_rel_let kk
blanchet@33192
  1259
              (fn r1 => fn r2 => fn r3 =>
blanchet@33192
  1260
                  let val empty_r = empty_rel_for_rep R in
blanchet@33192
  1261
                    fold1 kk_union
blanchet@33192
  1262
                          [kk_rel_if (kk_rel_eq r1 true_atom) r2 empty_r,
blanchet@33192
  1263
                           kk_rel_if (kk_rel_eq r1 false_atom) r3 empty_r,
blanchet@33192
  1264
                           kk_rel_if (kk_rel_eq r2 r3)
blanchet@33192
  1265
                                (if inline_rel_expr r2 then r2 else r3) empty_r]
blanchet@33192
  1266
                  end)
blanchet@33192
  1267
              (to_r u1) (to_rep R u2) (to_rep R u3)
blanchet@33192
  1268
        else
blanchet@33192
  1269
          kk_rel_if (to_f u1) (to_rep R u2) (to_rep R u3)
blanchet@33192
  1270
      | Tuple (_, R, us) =>
blanchet@33192
  1271
        (case unopt_rep R of
blanchet@33192
  1272
           Struct Rs => to_product Rs us
blanchet@33192
  1273
         | Vect (k, R) => to_product (replicate k R) us
blanchet@33192
  1274
         | Atom (1, j0) =>
blanchet@38190
  1275
           kk_rel_if (kk_some (fold1 kk_product (map to_r us)))
blanchet@38190
  1276
                     (KK.Atom j0) KK.None
blanchet@33232
  1277
         | _ => raise NUT ("Nitpick_Kodkod.to_r (Tuple)", [u]))
blanchet@33192
  1278
      | Construct ([u'], _, _, []) => to_r u'
blanchet@35280
  1279
      | Construct (discr_u :: sel_us, _, _, arg_us) =>
blanchet@33192
  1280
        let
blanchet@33192
  1281
          val set_rs =
blanchet@33192
  1282
            map2 (fn sel_u => fn arg_u =>
blanchet@33192
  1283
                     let
blanchet@33192
  1284
                       val (R1, R2) = dest_Func (rep_of sel_u)
blanchet@33192
  1285
                       val sel_r = to_r sel_u
blanchet@33192
  1286
                       val arg_r = to_opt R2 arg_u
blanchet@33192
  1287
                     in
blanchet@33192
  1288
                       if is_one_rep R2 then
blanchet@33192
  1289
                         kk_n_fold_join kk true R2 R1 arg_r
blanchet@33192
  1290
                              (kk_project sel_r (flip_nums (arity_of_rep R2)))
blanchet@33192
  1291
                       else
blanchet@34288
  1292
                         kk_comprehension [KK.DeclOne ((1, ~1), to_r discr_u)]
blanchet@34126
  1293
                             (kk_rel_eq (kk_join (KK.Var (1, ~1)) sel_r) arg_r)
blanchet@35695
  1294
                         |> is_opt_rep (rep_of arg_u) ? to_guard [arg_u] R1
blanchet@33192
  1295
                     end) sel_us arg_us
blanchet@33192
  1296
        in fold1 kk_intersect set_rs end
blanchet@34126
  1297
      | BoundRel (x, _, _, _) => KK.Var x
blanchet@34126
  1298
      | FreeRel (x, _, _, _) => KK.Rel x
blanchet@34126
  1299
      | RelReg (j, _, R) => KK.RelReg (arity_of_rep R, j)
blanchet@33232
  1300
      | u => raise NUT ("Nitpick_Kodkod.to_r", [u])
blanchet@33192
  1301
    and to_decl (BoundRel (x, _, R, _)) =
blanchet@34126
  1302
        KK.DeclOne (x, KK.AtomSeq (the_single (atom_schema_of_rep R)))
blanchet@33232
  1303
      | to_decl u = raise NUT ("Nitpick_Kodkod.to_decl", [u])
blanchet@35280
  1304
    and to_expr_assign (FormulaReg (j, _, _)) u =
blanchet@34126
  1305
        KK.AssignFormulaReg (j, to_f u)
blanchet@33192
  1306
      | to_expr_assign (RelReg (j, _, R)) u =
blanchet@34126
  1307
        KK.AssignRelReg ((arity_of_rep R, j), to_r u)
blanchet@33232
  1308
      | to_expr_assign u1 _ = raise NUT ("Nitpick_Kodkod.to_expr_assign", [u1])
blanchet@39345
  1309
    and to_atom (x as (_, j0)) u =
blanchet@33192
  1310
      case rep_of u of
blanchet@33192
  1311
        Formula _ => atom_from_formula kk j0 (to_f u)
blanchet@33192
  1312
      | R => atom_from_rel_expr kk x R (to_r u)
blanchet@38190
  1313
    and to_struct Rs u = struct_from_rel_expr kk Rs (rep_of u) (to_r u)
blanchet@38190
  1314
    and to_vect k R u = vect_from_rel_expr kk k R (rep_of u) (to_r u)
blanchet@38190
  1315
    and to_func R1 R2 u = rel_expr_to_func kk R1 R2 (rep_of u) (to_r u)
blanchet@33192
  1316
    and to_opt R u =
blanchet@33192
  1317
      let val old_R = rep_of u in
blanchet@33192
  1318
        if is_opt_rep old_R then
blanchet@33192
  1319
          rel_expr_from_rel_expr kk (Opt R) old_R (to_r u)
blanchet@33192
  1320
        else
blanchet@33192
  1321
          to_rep R u
blanchet@33192
  1322
      end
blanchet@33192
  1323
    and to_rep (Atom x) u = to_atom x u
blanchet@33192
  1324
      | to_rep (Struct Rs) u = to_struct Rs u
blanchet@33192
  1325
      | to_rep (Vect (k, R)) u = to_vect k R u
blanchet@33192
  1326
      | to_rep (Func (R1, R2)) u = to_func R1 R2 u
blanchet@33192
  1327
      | to_rep (Opt R) u = to_opt R u
blanchet@33232
  1328
      | to_rep R _ = raise REP ("Nitpick_Kodkod.to_rep", [R])
blanchet@33192
  1329
    and to_integer u = to_opt (one_rep ofs (type_of u) (rep_of u)) u
blanchet@33192
  1330
    and to_guard guard_us R r =
blanchet@33192
  1331
      let
blanchet@33192
  1332
        val unpacked_rs = unpack_joins r
blanchet@33192
  1333
        val plain_guard_rs =
blanchet@33192
  1334
          map to_r (filter (is_Opt o rep_of) guard_us)
blanchet@33192
  1335
          |> filter_out (member (op =) unpacked_rs)
blanchet@33192
  1336
        val func_guard_us =
blanchet@33192
  1337
          filter ((is_Func andf is_opt_rep) o rep_of) guard_us
blanchet@33192
  1338
        val func_guard_rs = map to_r func_guard_us
blanchet@33192
  1339
        val guard_fs =
blanchet@33192
  1340
          map kk_no plain_guard_rs @
blanchet@33192
  1341
          map2 (kk_not oo kk_n_ary_function kk)
blanchet@33192
  1342
               (map (unopt_rep o rep_of) func_guard_us) func_guard_rs
blanchet@33192
  1343
      in
blanchet@35695
  1344
        if null guard_fs then r
blanchet@35695
  1345
        else kk_rel_if (fold1 kk_or guard_fs) (empty_rel_for_rep R) r
blanchet@33192
  1346
      end
blanchet@33192
  1347
    and to_project new_R old_R r j0 =
blanchet@33192
  1348
      rel_expr_from_rel_expr kk new_R old_R
blanchet@33192
  1349
                             (kk_project_seq r j0 (arity_of_rep old_R))
blanchet@38190
  1350
    and to_product Rs us = fold1 kk_product (map (uncurry to_opt) (Rs ~~ us))
blanchet@39345
  1351
    and to_nth_pair_sel n res_R u =
blanchet@33192
  1352
      case u of
blanchet@33192
  1353
        Tuple (_, _, us) => to_rep res_R (nth us n)
blanchet@33192
  1354
      | _ => let
blanchet@33192
  1355
               val R = rep_of u
blanchet@33192
  1356
               val (a_T, b_T) = HOLogic.dest_prodT (type_of u)
blanchet@33192
  1357
               val Rs =
blanchet@33192
  1358
                 case unopt_rep R of
blanchet@33192
  1359
                   Struct (Rs as [_, _]) => Rs
blanchet@33192
  1360
                 | _ =>
blanchet@33192
  1361
                   let
blanchet@33192
  1362
                     val res_card = card_of_rep res_R
blanchet@33192
  1363
                     val other_card = card_of_rep R div res_card
blanchet@33192
  1364
                     val (a_card, b_card) = (res_card, other_card)
blanchet@33192
  1365
                                            |> n = 1 ? swap
blanchet@33192
  1366
                   in
blanchet@33192
  1367
                     [Atom (a_card, offset_of_type ofs a_T),
blanchet@33192
  1368
                      Atom (b_card, offset_of_type ofs b_T)]
blanchet@33192
  1369
                   end
blanchet@33192
  1370
               val nth_R = nth Rs n
blanchet@33192
  1371
               val j0 = if n = 0 then 0 else arity_of_rep (hd Rs)
blanchet@38190
  1372
             in to_project res_R nth_R (to_rep (Opt (Struct Rs)) u) j0 end
blanchet@33192
  1373
    and to_set_bool_op connective set_oper u1 u2 =
blanchet@33192
  1374
      let
blanchet@33192
  1375
        val min_R = min_rep (rep_of u1) (rep_of u2)
blanchet@33192
  1376
        val r1 = to_rep min_R u1
blanchet@33192
  1377
        val r2 = to_rep min_R u2
blanchet@33192
  1378
      in
blanchet@33192
  1379
        case min_R of
blanchet@33192
  1380
          Vect (k, Atom _) => kk_vect_set_bool_op connective k r1 r2
blanchet@51928
  1381
        | Func (_, R') =>
blanchet@51928
  1382
          (case body_rep R' of
blanchet@51928
  1383
             Formula Neut => set_oper r1 r2
blanchet@51928
  1384
           | Atom _ => set_oper (kk_join r1 true_atom) (kk_join r2 true_atom)
blanchet@51928
  1385
           | _ => raise REP ("Nitpick_Kodkod.to_set_bool_op", [min_R]))
blanchet@33232
  1386
        | _ => raise REP ("Nitpick_Kodkod.to_set_bool_op", [min_R])
blanchet@33192
  1387
      end
blanchet@34124
  1388
    and to_bit_word_unary_op T R oper =
blanchet@34124
  1389
      let
blanchet@34124
  1390
        val Ts = strip_type T ||> single |> op @
blanchet@34126
  1391
        fun int_arg j = int_expr_from_atom kk (nth Ts j) (KK.Var (1, j))
blanchet@34124
  1392
      in
blanchet@34124
  1393
        kk_comprehension (decls_for_atom_schema 0 (atom_schema_of_rep R))
blanchet@34126
  1394
            (KK.FormulaLet
blanchet@34126
  1395
                 (map (fn j => KK.AssignIntReg (j, int_arg j)) (0 upto 1),
blanchet@34126
  1396
                  KK.IntEq (KK.IntReg 1, oper (KK.IntReg 0))))
blanchet@34124
  1397
      end
blanchet@34124
  1398
    and to_bit_word_binary_op T R opt_guard opt_oper =
blanchet@34124
  1399
      let
blanchet@34124
  1400
        val Ts = strip_type T ||> single |> op @
blanchet@34126
  1401
        fun int_arg j = int_expr_from_atom kk (nth Ts j) (KK.Var (1, j))
blanchet@34124
  1402
      in
blanchet@34124
  1403
        kk_comprehension (decls_for_atom_schema 0 (atom_schema_of_rep R))
blanchet@34126
  1404
            (KK.FormulaLet
blanchet@34126
  1405
                 (map (fn j => KK.AssignIntReg (j, int_arg j)) (0 upto 2),
blanchet@34124
  1406
                  fold1 kk_and
blanchet@34124
  1407
                        ((case opt_guard of
blanchet@34124
  1408
                            NONE => []
blanchet@34124
  1409
                          | SOME guard =>
blanchet@34126
  1410
                            [guard (KK.IntReg 0) (KK.IntReg 1) (KK.IntReg 2)]) @
blanchet@34124
  1411
                         (case opt_oper of
blanchet@34124
  1412
                            NONE => []
blanchet@34124
  1413
                          | SOME oper =>
blanchet@34126
  1414
                            [KK.IntEq (KK.IntReg 2,
blanchet@34126
  1415
                                       oper (KK.IntReg 0) (KK.IntReg 1))]))))
blanchet@34124
  1416
      end
blanchet@39345
  1417
    and to_apply (R as Formula _) _ _ =
blanchet@36127
  1418
        raise REP ("Nitpick_Kodkod.to_apply", [R])
blanchet@36127
  1419
      | to_apply res_R func_u arg_u =
blanchet@36127
  1420
        case unopt_rep (rep_of func_u) of
blanchet@38190
  1421
          Atom (1, j0) =>
blanchet@33192
  1422
          to_guard [arg_u] res_R
blanchet@36127
  1423
                   (rel_expr_from_rel_expr kk res_R (Atom (1, j0)) (to_r func_u))
blanchet@36127
  1424
        | Atom (k, _) =>
blanchet@36127
  1425
          let
blanchet@36127
  1426
            val dom_card = card_of_rep (rep_of arg_u)
blanchet@46085
  1427
            val ran_R =
blanchet@46085
  1428
              Atom (exact_root dom_card k,
blanchet@46085
  1429
                    offset_of_type ofs (pseudo_range_type (type_of func_u)))
blanchet@36127
  1430
          in
blanchet@36127
  1431
            to_apply_vect dom_card ran_R res_R (to_vect dom_card ran_R func_u)
blanchet@36127
  1432
                          arg_u
blanchet@36127
  1433
          end
blanchet@36127
  1434
        | Vect (1, R') =>
blanchet@36127
  1435
          to_guard [arg_u] res_R
blanchet@36127
  1436
                   (rel_expr_from_rel_expr kk res_R R' (to_r func_u))
blanchet@36127
  1437
        | Vect (k, R') => to_apply_vect k R' res_R (to_r func_u) arg_u
blanchet@36127
  1438
        | Func (R, Formula Neut) =>
blanchet@36127
  1439
          to_guard [arg_u] res_R (rel_expr_from_formula kk res_R
blanchet@36127
  1440
                                      (kk_subset (to_opt R arg_u) (to_r func_u)))
blanchet@36127
  1441
        | Func (R1, R2) =>
blanchet@36127
  1442
          rel_expr_from_rel_expr kk res_R R2
blanchet@36127
  1443
              (kk_n_fold_join kk true R1 R2 (to_opt R1 arg_u) (to_r func_u))
blanchet@36127
  1444
          |> body_rep R2 = Formula Neut ? to_guard [arg_u] res_R
blanchet@36127
  1445
        | _ => raise NUT ("Nitpick_Kodkod.to_apply", [func_u])
blanchet@33192
  1446
    and to_apply_vect k R' res_R func_r arg_u =
blanchet@33192
  1447
      let
blanchet@33192
  1448
        val arg_R = one_rep ofs (type_of arg_u) (unopt_rep (rep_of arg_u))
blanchet@33192
  1449
        val vect_r = vect_from_rel_expr kk k res_R (Vect (k, R')) func_r
blanchet@33192
  1450
        val vect_rs = unpack_vect_in_chunks kk (arity_of_rep res_R) k vect_r
blanchet@33192
  1451
      in
blanchet@33192
  1452
        kk_case_switch kk arg_R res_R (to_opt arg_R arg_u)
blanchet@33192
  1453
                       (all_singletons_for_rep arg_R) vect_rs
blanchet@33192
  1454
      end
blanchet@33192
  1455
    and to_could_be_unrep neg u =
blanchet@34126
  1456
      if neg andalso is_opt_rep (rep_of u) then kk_no (to_r u) else KK.False
blanchet@33192
  1457
    and to_compare_with_unrep u r =
blanchet@33892
  1458
      if is_opt_rep (rep_of u) then
blanchet@33892
  1459
        kk_rel_if (kk_some (to_r u)) r (empty_rel_for_rep (rep_of u))
blanchet@33892
  1460
      else
blanchet@33892
  1461
        r
blanchet@33192
  1462
  in to_f_with_polarity Pos u end
blanchet@33192
  1463
blanchet@41802
  1464
fun declarative_axiom_for_plain_rel kk (FreeRel (x, _, R as Func _, nick)) =
blanchet@41802
  1465
    kk_n_ary_function kk (R |> nick = @{const_name List.set} ? unopt_rep)
blanchet@41802
  1466
                      (KK.Rel x)
blanchet@41802
  1467
  | declarative_axiom_for_plain_rel ({kk_lone, kk_one, ...} : kodkod_constrs)
blanchet@41802
  1468
                                    (FreeRel (x, _, R, _)) =
blanchet@41802
  1469
    if is_one_rep R then kk_one (KK.Rel x)
blanchet@41802
  1470
    else if is_lone_rep R andalso card_of_rep R > 1 then kk_lone (KK.Rel x)
blanchet@41802
  1471
    else KK.True
blanchet@41802
  1472
  | declarative_axiom_for_plain_rel _ u =
blanchet@41802
  1473
    raise NUT ("Nitpick_Kodkod.declarative_axiom_for_plain_rel", [u])
blanchet@41802
  1474
blanchet@41802
  1475
fun const_triple rel_table (x as (s, T)) =
blanchet@41802
  1476
  case the_name rel_table (ConstName (s, T, Any)) of
blanchet@41802
  1477
    FreeRel ((n, j), _, R, _) => (KK.Rel (n, j), R, n)
blanchet@41802
  1478
  | _ => raise TERM ("Nitpick_Kodkod.const_triple", [Const x])
blanchet@41802
  1479
blanchet@41802
  1480
fun discr_rel_expr rel_table = #1 o const_triple rel_table o discr_for_constr
blanchet@41802
  1481
blanchet@41802
  1482
fun nfa_transitions_for_sel hol_ctxt binarize
blanchet@41802
  1483
                            ({kk_project, ...} : kodkod_constrs) rel_table
blanchet@41802
  1484
                            (dtypes : datatype_spec list) constr_x n =
blanchet@41802
  1485
  let
blanchet@41802
  1486
    val x as (_, T) =
blanchet@41802
  1487
      binarized_and_boxed_nth_sel_for_constr hol_ctxt binarize constr_x n
blanchet@41802
  1488
    val (r, R, arity) = const_triple rel_table x
blanchet@41802
  1489
    val type_schema = type_schema_of_rep T R
blanchet@41802
  1490
  in
blanchet@41802
  1491
    map_filter (fn (j, T) =>
blanchet@41802
  1492
                   if forall (not_equal T o #typ) dtypes then NONE
blanchet@41802
  1493
                   else SOME ((x, kk_project r (map KK.Num [0, j])), T))
blanchet@41802
  1494
               (index_seq 1 (arity - 1) ~~ tl type_schema)
blanchet@41802
  1495
  end
blanchet@41802
  1496
fun nfa_transitions_for_constr hol_ctxt binarize kk rel_table dtypes
blanchet@41802
  1497
                               (x as (_, T)) =
blanchet@41802
  1498
  maps (nfa_transitions_for_sel hol_ctxt binarize kk rel_table dtypes x)
blanchet@41802
  1499
       (index_seq 0 (num_sels_for_constr_type T))
blanchet@41802
  1500
fun nfa_entry_for_datatype _ _ _ _ _ ({co = true, ...} : datatype_spec) = NONE
blanchet@41802
  1501
  | nfa_entry_for_datatype _ _ _ _ _ {deep = false, ...} = NONE
blanchet@41802
  1502
  | nfa_entry_for_datatype hol_ctxt binarize kk rel_table dtypes
blanchet@41802
  1503
                           {typ, constrs, ...} =
blanchet@41802
  1504
    SOME (typ, maps (nfa_transitions_for_constr hol_ctxt binarize kk rel_table
blanchet@41802
  1505
                                                dtypes o #const) constrs)
blanchet@41802
  1506
blanchet@41802
  1507
val empty_rel = KK.Product (KK.None, KK.None)
blanchet@41802
  1508
blanchet@41802
  1509
fun direct_path_rel_exprs nfa start_T final_T =
blanchet@41802
  1510
  case AList.lookup (op =) nfa final_T of
blanchet@41802
  1511
    SOME trans => map (snd o fst) (filter (curry (op =) start_T o snd) trans)
blanchet@41802
  1512
  | NONE => []
blanchet@41802
  1513
and any_path_rel_expr ({kk_union, ...} : kodkod_constrs) nfa [] start_T
blanchet@41802
  1514
                      final_T =
blanchet@41802
  1515
    fold kk_union (direct_path_rel_exprs nfa start_T final_T)
blanchet@41802
  1516
         (if start_T = final_T then KK.Iden else empty_rel)
blanchet@41802
  1517
  | any_path_rel_expr (kk as {kk_union, ...}) nfa (T :: Ts) start_T final_T =
blanchet@41802
  1518
    kk_union (any_path_rel_expr kk nfa Ts start_T final_T)
blanchet@41802
  1519
             (knot_path_rel_expr kk nfa Ts start_T T final_T)
blanchet@41802
  1520
and knot_path_rel_expr (kk as {kk_join, kk_reflexive_closure, ...}) nfa Ts
blanchet@41802
  1521
                       start_T knot_T final_T =
blanchet@41802
  1522
  kk_join (kk_join (any_path_rel_expr kk nfa Ts knot_T final_T)
blanchet@41802
  1523
                   (kk_reflexive_closure (loop_path_rel_expr kk nfa Ts knot_T)))
blanchet@41802
  1524
          (any_path_rel_expr kk nfa Ts start_T knot_T)
blanchet@41802
  1525
and loop_path_rel_expr ({kk_union, ...} : kodkod_constrs) nfa [] start_T =
blanchet@41802
  1526
    fold kk_union (direct_path_rel_exprs nfa start_T start_T) empty_rel
blanchet@41802
  1527
  | loop_path_rel_expr (kk as {kk_union, kk_closure, ...}) nfa (T :: Ts)
blanchet@41802
  1528
                       start_T =
blanchet@41802
  1529
    if start_T = T then
blanchet@41802
  1530
      kk_closure (loop_path_rel_expr kk nfa Ts start_T)
blanchet@41802
  1531
    else
blanchet@41802
  1532
      kk_union (loop_path_rel_expr kk nfa Ts start_T)
blanchet@41802
  1533
               (knot_path_rel_expr kk nfa Ts start_T T start_T)
blanchet@41802
  1534
blanchet@41802
  1535
fun add_nfa_to_graph [] = I
blanchet@41802
  1536
  | add_nfa_to_graph ((_, []) :: nfa) = add_nfa_to_graph nfa
blanchet@41802
  1537
  | add_nfa_to_graph ((T, ((_, T') :: transitions)) :: nfa) =
blanchet@41802
  1538
    add_nfa_to_graph ((T, transitions) :: nfa) o Typ_Graph.add_edge (T, T') o
blanchet@41802
  1539
    Typ_Graph.default_node (T', ()) o Typ_Graph.default_node (T, ())
blanchet@41802
  1540
blanchet@41802
  1541
fun strongly_connected_sub_nfas nfa =
blanchet@41802
  1542
  add_nfa_to_graph nfa Typ_Graph.empty
blanchet@41802
  1543
  |> Typ_Graph.strong_conn
blanchet@41802
  1544
  |> map (fn keys => filter (member (op =) keys o fst) nfa)
blanchet@41802
  1545
blanchet@41802
  1546
(* Cycle breaking in the bounds takes care of singly recursive datatypes, hence
blanchet@41802
  1547
   the first equation. *)
blanchet@54632
  1548
fun acyclicity_axioms_for_datatype _ [_] _ = []
blanchet@54632
  1549
  | acyclicity_axioms_for_datatype (kk as {kk_no, kk_intersect, ...}) nfa
blanchet@54632
  1550
                                   start_T =
blanchet@54632
  1551
    [kk_no (kk_intersect
blanchet@54632
  1552
                (loop_path_rel_expr kk nfa (pull start_T (map fst nfa)) start_T)
blanchet@54632
  1553
                KK.Iden)]
blanchet@54632
  1554
fun acyclicity_axioms_for_datatypes kk =
blanchet@54632
  1555
  maps (fn nfa => maps (acyclicity_axioms_for_datatype kk nfa o fst) nfa)
blanchet@41802
  1556
blanchet@41802
  1557
fun atom_equation_for_nut ofs kk (u, j) =
blanchet@41802
  1558
  let val dummy_u = RelReg (0, type_of u, rep_of u) in
blanchet@41802
  1559
    case Op2 (DefEq, bool_T, Formula Pos, dummy_u, u)
blanchet@41802
  1560
         |> kodkod_formula_from_nut ofs kk of
blanchet@42001
  1561
      KK.RelEq (KK.RelReg _, r) => SOME (KK.RelEq (KK.Atom j, r))
blanchet@41802
  1562
    | _ => raise BAD ("Nitpick_Kodkod.atom_equation_for_nut",
blanchet@41802
  1563
                      "malformed Kodkod formula")
blanchet@41802
  1564
  end
blanchet@41802
  1565
blanchet@41995
  1566
fun needed_values_for_datatype [] _ _ = SOME []
blanchet@41995
  1567
  | needed_values_for_datatype need_us ofs
blanchet@42001
  1568
                               ({typ, card, constrs, ...} : datatype_spec) =
blanchet@41802
  1569
    let
blanchet@41802
  1570
      fun aux (u as Construct (FreeRel (_, _, _, s) :: _, T, _, us)) =
blanchet@41802
  1571
          fold aux us
blanchet@41802
  1572
          #> (fn NONE => NONE
blanchet@41802
  1573
               | accum as SOME (loose, fixed) =>
blanchet@41802
  1574
                 if T = typ then
blanchet@41802
  1575
                   case AList.lookup (op =) fixed u of
blanchet@41802
  1576
                     SOME _ => accum
blanchet@41802
  1577
                   | NONE =>
blanchet@41802
  1578
                     let
blanchet@41802
  1579
                       val constr_s = constr_name_for_sel_like s
blanchet@41802
  1580
                       val {delta, epsilon, ...} =
blanchet@41802
  1581
                         constrs
blanchet@41802
  1582
                         |> List.find (fn {const, ...} => fst const = constr_s)
blanchet@41802
  1583
                         |> the
blanchet@41802
  1584
                       val j0 = offset_of_type ofs T
blanchet@41802
  1585
                     in
blanchet@41802
  1586
                       case find_first (fn j => j >= delta andalso
blanchet@41802
  1587
                                        j < delta + epsilon) loose of
blanchet@41802
  1588
                         SOME j =>
blanchet@41802
  1589
                         SOME (remove (op =) j loose, (u, j0 + j) :: fixed)
blanchet@41802
  1590
                       | NONE => NONE
blanchet@41802
  1591
                     end
blanchet@41802
  1592
                 else
blanchet@41802
  1593
                   accum)
blanchet@41985
  1594
        | aux _ = I
blanchet@41996
  1595
    in
blanchet@42001
  1596
      SOME (index_seq 0 card, []) |> fold aux need_us |> Option.map (rev o snd)
blanchet@41996
  1597
    end
blanchet@41995
  1598
blanchet@42001
  1599
fun needed_value_axioms_for_datatype _ _ _ (_, NONE) = [KK.False]
blanchet@42001
  1600
  | needed_value_axioms_for_datatype ofs kk dtypes (T, SOME fixed) =
blanchet@42001
  1601
    if is_datatype_nat_like (the (datatype_spec dtypes T)) then []
blanchet@42001
  1602
    else fixed |> map_filter (atom_equation_for_nut ofs kk)
blanchet@41802
  1603
blanchet@41802
  1604
fun all_ge ({kk_join, kk_reflexive_closure, ...} : kodkod_constrs) z r =
blanchet@41802
  1605
  kk_join r (kk_reflexive_closure (KK.Rel (suc_rel_for_atom_seq z)))
blanchet@41802
  1606
fun gt ({kk_subset, kk_join, kk_closure, ...} : kodkod_constrs) z r1 r2 =
blanchet@41802
  1607
  kk_subset r1 (kk_join r2 (kk_closure (KK.Rel (suc_rel_for_atom_seq z))))
blanchet@41802
  1608
blanchet@41802
  1609
fun constr_quadruple ({const = (s, T), delta, epsilon, ...} : constr_spec) =
blanchet@41802
  1610
  (delta, (epsilon, (num_binder_types T, s)))
blanchet@41802
  1611
val constr_ord =
blanchet@41802
  1612
  prod_ord int_ord (prod_ord int_ord (prod_ord int_ord string_ord))
blanchet@41802
  1613
  o pairself constr_quadruple
blanchet@41802
  1614
blanchet@41802
  1615
fun datatype_ord (({card = card1, self_rec = self_rec1, constrs = constr1, ...},
blanchet@41802
  1616
                   {card = card2, self_rec = self_rec2, constrs = constr2, ...})
blanchet@41802
  1617
                  : datatype_spec * datatype_spec) =
blanchet@41802
  1618
  prod_ord int_ord (prod_ord bool_ord int_ord)
blanchet@41802
  1619
           ((card1, (self_rec1, length constr1)),
blanchet@41802
  1620
            (card2, (self_rec2, length constr2)))
blanchet@41802
  1621
blanchet@41802
  1622
(* We must absolutely tabulate "suc" for all datatypes whose selector bounds
blanchet@41802
  1623
   break cycles; otherwise, we may end up with two incompatible symmetry
blanchet@41802
  1624
   breaking orders, leading to spurious models. *)
blanchet@41802
  1625
fun should_tabulate_suc_for_type dtypes T =
blanchet@41802
  1626
  is_asymmetric_nondatatype T orelse
blanchet@41802
  1627
  case datatype_spec dtypes T of
blanchet@41802
  1628
    SOME {self_rec, ...} => self_rec
blanchet@41802
  1629
  | NONE => false
blanchet@41802
  1630
blanchet@41802
  1631
fun lex_order_rel_expr (kk as {kk_implies, kk_and, kk_subset, kk_join, ...})
blanchet@41802
  1632
                       dtypes sel_quadruples =
blanchet@41802
  1633
  case sel_quadruples of
blanchet@41802
  1634
    [] => KK.True
blanchet@41802
  1635
  | ((r, Func (Atom _, Atom x), 2), (_, Type (_, [_, T]))) :: sel_quadruples' =>
blanchet@41802
  1636
    let val z = (x, should_tabulate_suc_for_type dtypes T) in
blanchet@41802
  1637
      if null sel_quadruples' then
blanchet@41802
  1638
        gt kk z (kk_join (KK.Var (1, 1)) r) (kk_join (KK.Var (1, 0)) r)
blanchet@41802
  1639
      else
blanchet@41802
  1640
        kk_and (kk_subset (kk_join (KK.Var (1, 1)) r)
blanchet@41802
  1641
                          (all_ge kk z (kk_join (KK.Var (1, 0)) r)))
blanchet@41802
  1642
               (kk_implies (kk_subset (kk_join (KK.Var (1, 1)) r)
blanchet@41802
  1643
                                      (kk_join (KK.Var (1, 0)) r))
blanchet@41802
  1644
                           (lex_order_rel_expr kk dtypes sel_quadruples'))
blanchet@41802
  1645
    end
blanchet@41802
  1646
    (* Skip constructors components that aren't atoms, since we cannot compare
blanchet@41802
  1647
       these easily. *)
blanchet@41802
  1648
  | _ :: sel_quadruples' => lex_order_rel_expr kk dtypes sel_quadruples'
blanchet@41802
  1649
blanchet@41802
  1650
fun is_nil_like_constr_type dtypes T =
blanchet@41802
  1651
  case datatype_spec dtypes T of
blanchet@41802
  1652
    SOME {constrs, ...} =>
blanchet@41802
  1653
    (case filter_out (is_self_recursive_constr_type o snd o #const) constrs of
blanchet@41802
  1654
       [{const = (_, T'), ...}] => T = T'
blanchet@41802
  1655
     | _ => false)
blanchet@41802
  1656
  | NONE => false
blanchet@41802
  1657
blanchet@41802
  1658
fun sym_break_axioms_for_constr_pair hol_ctxt binarize
blanchet@41802
  1659
       (kk as {kk_all, kk_or, kk_implies, kk_and, kk_some, kk_intersect,
blanchet@41802
  1660
               kk_join, ...}) rel_table nfas dtypes
blanchet@41802
  1661
       (constr_ord,
blanchet@41802
  1662
        ({const = const1 as (_, T1), delta = delta1, epsilon = epsilon1, ...},
blanchet@41802
  1663
         {const = const2 as (_, _), delta = delta2, epsilon = epsilon2, ...})
blanchet@41802
  1664
        : constr_spec * constr_spec) =
blanchet@41802
  1665
  let
blanchet@41802
  1666
    val dataT = body_type T1
blanchet@41802
  1667
    val nfa = nfas |> find_first (exists (curry (op =) dataT o fst)) |> these
blanchet@41802
  1668
    val rec_Ts = nfa |> map fst
blanchet@41802
  1669
    fun rec_and_nonrec_sels (x as (_, T)) =
blanchet@41802
  1670
      index_seq 0 (num_sels_for_constr_type T)
blanchet@41802
  1671
      |> map (binarized_and_boxed_nth_sel_for_constr hol_ctxt binarize x)
blanchet@41802
  1672
      |> List.partition (member (op =) rec_Ts o range_type o snd)
blanchet@41802
  1673
    val sel_xs1 = rec_and_nonrec_sels const1 |> op @
blanchet@41802
  1674
  in
blanchet@41802
  1675
    if constr_ord = EQUAL andalso null sel_xs1 then
blanchet@41802
  1676
      []
blanchet@41802
  1677
    else
blanchet@41802
  1678
      let
blanchet@41802
  1679
        val z =
blanchet@41802
  1680
          (case #2 (const_triple rel_table (discr_for_constr const1)) of
blanchet@41802
  1681
             Func (Atom x, Formula _) => x
blanchet@41802
  1682
           | R => raise REP ("Nitpick_Kodkod.sym_break_axioms_for_constr_pair",
blanchet@41802
  1683
                             [R]), should_tabulate_suc_for_type dtypes dataT)
blanchet@41802
  1684
        val (rec_sel_xs2, nonrec_sel_xs2) = rec_and_nonrec_sels const2
blanchet@41802
  1685
        val sel_xs2 = rec_sel_xs2 @ nonrec_sel_xs2
blanchet@41802
  1686
        fun sel_quadruples2 () = sel_xs2 |> map (`(const_triple rel_table))
blanchet@41802
  1687
        (* If the two constructors are the same, we drop the first selector
blanchet@41802
  1688
           because that one is always checked by the lexicographic order.
blanchet@41802
  1689
           We sometimes also filter out direct subterms, because those are
blanchet@41802
  1690
           already handled by the acyclicity breaking in the bound
blanchet@41802
  1691
           declarations. *)
blanchet@41802
  1692
        fun filter_out_sels no_direct sel_xs =
blanchet@41802
  1693
          apsnd (filter_out
blanchet@41802
  1694
                     (fn ((x, _), T) =>
blanchet@41802
  1695
                         (constr_ord = EQUAL andalso x = hd sel_xs) orelse
blanchet@41802
  1696
                         (T = dataT andalso
blanchet@41802
  1697
                          (no_direct orelse not (member (op =) sel_xs x)))))
blanchet@41802
  1698
        fun subterms_r no_direct sel_xs j =
blanchet@41802
  1699
          loop_path_rel_expr kk (map (filter_out_sels no_direct sel_xs) nfa)
blanchet@41802
  1700
                           (filter_out (curry (op =) dataT) (map fst nfa)) dataT
blanchet@41802
  1701
          |> kk_join (KK.Var (1, j))
blanchet@41802
  1702
      in
blanchet@41802
  1703
        [kk_all [KK.DeclOne ((1, 0), discr_rel_expr rel_table const1),
blanchet@41802
  1704
                 KK.DeclOne ((1, 1), discr_rel_expr rel_table const2)]
blanchet@41802
  1705
             (kk_implies
blanchet@41802
  1706
                 (if delta2 >= epsilon1 then KK.True
blanchet@41802
  1707
                  else if delta1 >= epsilon2 - 1 then KK.False
blanchet@41802
  1708
                  else gt kk z (KK.Var (1, 1)) (KK.Var (1, 0)))
blanchet@41802
  1709
                 (kk_or
blanchet@41802
  1710
                      (if is_nil_like_constr_type dtypes T1 then
blanchet@41802
  1711
                         KK.True
blanchet@41802
  1712
                       else
blanchet@41802
  1713
                         kk_some (kk_intersect (subterms_r false sel_xs2 1)
blanchet@41802
  1714
                                               (all_ge kk z (KK.Var (1, 0)))))
blanchet@41802
  1715
                      (case constr_ord of
blanchet@41802
  1716
                         EQUAL =>
blanchet@41802
  1717
                         kk_and
blanchet@41802
  1718
                             (lex_order_rel_expr kk dtypes (sel_quadruples2 ()))
blanchet@41802
  1719
                             (kk_all [KK.DeclOne ((1, 2),
blanchet@41802
  1720
                                                  subterms_r true sel_xs1 0)]
blanchet@41802
  1721
                                     (gt kk z (KK.Var (1, 1)) (KK.Var (1, 2))))
blanchet@41802
  1722
                       | LESS =>
blanchet@41802
  1723
                         kk_all [KK.DeclOne ((1, 2),
blanchet@41802
  1724
                                 subterms_r false sel_xs1 0)]
blanchet@41802
  1725
                                (gt kk z (KK.Var (1, 1)) (KK.Var (1, 2)))
blanchet@41802
  1726
                       | GREATER => KK.False)))]
blanchet@41802
  1727
      end
blanchet@41802
  1728
  end
blanchet@41802
  1729
blanchet@41802
  1730
fun sym_break_axioms_for_datatype hol_ctxt binarize kk rel_table nfas dtypes
blanchet@41802
  1731
                                  ({constrs, ...} : datatype_spec) =
blanchet@41802
  1732
  let
blanchet@41802
  1733
    val constrs = sort constr_ord constrs
blanchet@41802
  1734
    val constr_pairs = all_distinct_unordered_pairs_of constrs
blanchet@41802
  1735
  in
blanchet@41802
  1736
    map (pair EQUAL) (constrs ~~ constrs) @
blanchet@41802
  1737
    map (pair LESS) constr_pairs @
blanchet@41802
  1738
    map (pair GREATER) (map swap constr_pairs)
blanchet@41802
  1739
    |> maps (sym_break_axioms_for_constr_pair hol_ctxt binarize kk rel_table
blanchet@41802
  1740
                                              nfas dtypes)
blanchet@41802
  1741
  end
blanchet@41802
  1742
blanchet@41875
  1743
fun is_datatype_in_needed_value T (Construct (_, T', _, us)) =
blanchet@41875
  1744
    T = T' orelse exists (is_datatype_in_needed_value T) us
blanchet@41875
  1745
  | is_datatype_in_needed_value _ _ = false
blanchet@41802
  1746
blanchet@41802
  1747
val min_sym_break_card = 7
blanchet@41802
  1748
blanchet@41875
  1749
fun sym_break_axioms_for_datatypes hol_ctxt binarize need_us datatype_sym_break
blanchet@41875
  1750
                                   kk rel_table nfas dtypes =
blanchet@41802
  1751
  if datatype_sym_break = 0 then
blanchet@41802
  1752
    []
blanchet@41802
  1753
  else
blanchet@41803
  1754
    dtypes |> filter is_datatype_acyclic
blanchet@41803
  1755
           |> filter (fn {constrs = [_], ...} => false
blanchet@41803
  1756
                       | {card, constrs, ...} =>
blanchet@41803
  1757
                         card >= min_sym_break_card andalso
blanchet@41803
  1758
                         forall (forall (not o is_higher_order_type)
blanchet@41803
  1759
                                 o binder_types o snd o #const) constrs)
blanchet@41803
  1760
           |> filter_out
blanchet@41803
  1761
                  (fn {typ, ...} =>
blanchet@41875
  1762
                      exists (is_datatype_in_needed_value typ) need_us)
blanchet@41803
  1763
           |> (fn dtypes' =>
blanchet@41803
  1764
                  dtypes' |> length dtypes' > datatype_sym_break
blanchet@41803
  1765
                             ? (sort (datatype_ord o swap)
blanchet@41803
  1766
                                #> take datatype_sym_break))
blanchet@41803
  1767
           |> maps (sym_break_axioms_for_datatype hol_ctxt binarize kk rel_table
blanchet@41803
  1768
                                                  nfas dtypes)
blanchet@41803
  1769
blanchet@41998
  1770
fun sel_axioms_for_sel hol_ctxt binarize j0
blanchet@42001
  1771
        (kk as {kk_all, kk_formula_if, kk_subset, kk_no, kk_join, ...})
blanchet@42001
  1772
        need_vals rel_table dom_r (dtype as {typ, ...})
blanchet@41998
  1773
        ({const, delta, epsilon, exclusive, ...} : constr_spec) n =
blanchet@41802
  1774
  let
blanchet@41802
  1775
    val x = binarized_and_boxed_nth_sel_for_constr hol_ctxt binarize const n
blanchet@41802
  1776
    val (r, R, _) = const_triple rel_table x
blanchet@41998
  1777
    val rel_x =
blanchet@41998
  1778
      case r of
blanchet@41998
  1779
        KK.Rel x => x
blanchet@41998
  1780
      | _ => raise BAD ("Nitpick_Kodkod.sel_axioms_for_sel", "non-Rel")
blanchet@41802
  1781
    val R2 = dest_Func R |> snd
blanchet@41802
  1782
    val z = (epsilon - delta, delta + j0)
blanchet@41802
  1783
  in
blanchet@41802
  1784
    if exclusive then
blanchet@41998
  1785
      [kk_n_ary_function kk (Func (Atom z, R2)) r]
blanchet@41998
  1786
    else if all_values_are_needed need_vals dtype then
blanchet@41998
  1787
      typ |> needed_values need_vals
blanchet@41998
  1788
          |> filter (is_sel_of_constr rel_x)
blanchet@41998
  1789
          |> map (fn (_, j) => kk_n_ary_function kk R2 (kk_join (KK.Atom j) r))
blanchet@41802
  1790
    else
blanchet@41802
  1791
      let val r' = kk_join (KK.Var (1, 0)) r in
blanchet@41998
  1792
        [kk_all [KK.DeclOne ((1, 0), KK.AtomSeq z)]
blanchet@41998
  1793
                (kk_formula_if (kk_subset (KK.Var (1, 0)) dom_r)
blanchet@41998
  1794
                               (kk_n_ary_function kk R2 r') (kk_no r'))]
blanchet@41802
  1795
      end
blanchet@41802
  1796
  end
blanchet@41998
  1797
fun sel_axioms_for_constr hol_ctxt binarize bits j0 kk need_vals rel_table
blanchet@41998
  1798
        dtype (constr as {const, delta, epsilon, explicit_max, ...}) =
blanchet@41802
  1799
  let
blanchet@41802
  1800
    val honors_explicit_max =
blanchet@41802
  1801
      explicit_max < 0 orelse epsilon - delta <= explicit_max
blanchet@41802
  1802
  in
blanchet@41802
  1803
    if explicit_max = 0 then
blanchet@41802
  1804
      [formula_for_bool honors_explicit_max]
blanchet@41802
  1805
    else
blanchet@41802
  1806
      let
blanchet@41802
  1807
        val dom_r = discr_rel_expr rel_table const
blanchet@41802
  1808
        val max_axiom =
blanchet@41802
  1809
          if honors_explicit_max then
blanchet@41802
  1810
            KK.True
blanchet@41802
  1811
          else if bits = 0 orelse
blanchet@41802
  1812
               is_twos_complement_representable bits (epsilon - delta) then
blanchet@41802
  1813
            KK.LE (KK.Cardinality dom_r, KK.Num explicit_max)
blanchet@41802
  1814
          else
blanchet@41802
  1815
            raise TOO_SMALL ("Nitpick_Kodkod.sel_axioms_for_constr",
blanchet@41802
  1816
                             "\"bits\" value " ^ string_of_int bits ^
blanchet@41802
  1817
                             " too small for \"max\"")
blanchet@41802
  1818
      in
blanchet@41802
  1819
        max_axiom ::
blanchet@41998
  1820
        maps (sel_axioms_for_sel hol_ctxt binarize j0 kk need_vals rel_table
blanchet@41998
  1821
                                 dom_r dtype constr)
blanchet@41998
  1822
             (index_seq 0 (num_sels_for_constr_type (snd const)))
blanchet@41802
  1823
      end
blanchet@41802
  1824
  end
blanchet@41998
  1825
fun sel_axioms_for_datatype hol_ctxt binarize bits j0 kk rel_table need_vals
blanchet@41998
  1826
                            (dtype as {constrs, ...}) =
blanchet@41998
  1827
  maps (sel_axioms_for_constr hol_ctxt binarize bits j0 kk rel_table need_vals
blanchet@41998
  1828
                              dtype) constrs
blanchet@41802
  1829
blanchet@41998
  1830
fun uniqueness_axioms_for_constr hol_ctxt binarize
blanchet@41802
  1831
        ({kk_all, kk_implies, kk_and, kk_rel_eq, kk_lone, kk_join, ...}
blanchet@41998
  1832
         : kodkod_constrs) need_vals rel_table dtype
blanchet@41998
  1833
        ({const, ...} : constr_spec) =
blanchet@41802
  1834
  let
blanchet@41802
  1835
    fun conjunct_for_sel r =
blanchet@41802
  1836
      kk_rel_eq (kk_join (KK.Var (1, 0)) r) (kk_join (KK.Var (1, 1)) r)
blanchet@41802
  1837
    val num_sels = num_sels_for_constr_type (snd const)
blanchet@41802
  1838
    val triples =
blanchet@41802
  1839
      map (const_triple rel_table
blanchet@41802
  1840
           o binarized_and_boxed_nth_sel_for_constr hol_ctxt binarize const)
blanchet@41802
  1841
          (~1 upto num_sels - 1)
blanchet@41802
  1842
    val set_r = triples |> hd |> #1
blanchet@41802
  1843
  in
blanchet@41802
  1844
    if num_sels = 0 then
blanchet@41998
  1845
      [kk_lone set_r]
blanchet@41998
  1846
    else if all_values_are_needed need_vals dtype then
blanchet@41998
  1847
      []
blanchet@41802
  1848
    else
blanchet@41998
  1849
      [kk_all (map (KK.DeclOne o rpair set_r o pair 1) [0, 1])
blanchet@41998
  1850
              (kk_implies
blanchet@41998
  1851
                   (fold1 kk_and (map (conjunct_for_sel o #1) (tl triples)))
blanchet@41998
  1852
                   (kk_rel_eq (KK.Var (1, 0)) (KK.Var (1, 1))))]
blanchet@41802
  1853
  end
blanchet@41998
  1854
fun uniqueness_axioms_for_datatype hol_ctxt binarize kk need_vals rel_table
blanchet@41998
  1855
                                   (dtype as {constrs, ...}) =
blanchet@41998
  1856
  maps (uniqueness_axioms_for_constr hol_ctxt binarize kk need_vals rel_table
blanchet@41998
  1857
                                     dtype) constrs
blanchet@41802
  1858
blanchet@41802
  1859
fun effective_constr_max ({delta, epsilon, ...} : constr_spec) = epsilon - delta
blanchet@41802
  1860
fun partition_axioms_for_datatype j0 (kk as {kk_rel_eq, kk_union, ...})
blanchet@41998
  1861
        need_vals rel_table (dtype as {card, constrs, ...}) =
blanchet@41802
  1862
  if forall #exclusive constrs then
blanchet@41802
  1863
    [Integer.sum (map effective_constr_max constrs) = card |> formula_for_bool]
blanchet@41998
  1864
  else if all_values_are_needed need_vals dtype then
blanchet@41998
  1865
    []
blanchet@41802
  1866
  else
blanchet@41802
  1867
    let val rs = map (discr_rel_expr rel_table o #const) constrs in
blanchet@41802
  1868
      [kk_rel_eq (fold1 kk_union rs) (KK.AtomSeq (card, j0)),
blanchet@41802
  1869
       kk_disjoint_sets kk rs]
blanchet@41802
  1870
    end
blanchet@41802
  1871
blanchet@41998
  1872
fun other_axioms_for_datatype _ _ _ _ _ _ _ {deep = false, ...} = []
blanchet@41998
  1873
  | other_axioms_for_datatype hol_ctxt binarize need_vals bits ofs kk rel_table
blanchet@41802
  1874
                              (dtype as {typ, ...}) =
blanchet@41802
  1875
    let val j0 = offset_of_type ofs typ in
blanchet@41998
  1876
      sel_axioms_for_datatype hol_ctxt binarize bits j0 kk need_vals rel_table
blanchet@41998
  1877
                              dtype @
blanchet@41998
  1878
      uniqueness_axioms_for_datatype hol_ctxt binarize kk need_vals rel_table
blanchet@41998
  1879
                                     dtype @
blanchet@41998
  1880
      partition_axioms_for_datatype j0 kk need_vals rel_table dtype
blanchet@41802
  1881
    end
blanchet@41802
  1882
blanchet@41995
  1883
fun declarative_axioms_for_datatypes hol_ctxt binarize need_us need_vals
blanchet@41802
  1884
        datatype_sym_break bits ofs kk rel_table dtypes =
blanchet@41802
  1885
  let
blanchet@41802
  1886
    val nfas =
blanchet@41802
  1887
      dtypes |> map_filter (nfa_entry_for_datatype hol_ctxt binarize kk
blanchet@41802
  1888
                                                   rel_table dtypes)
blanchet@41802
  1889
             |> strongly_connected_sub_nfas
blanchet@41802
  1890
  in
blanchet@41802
  1891
    acyclicity_axioms_for_datatypes kk nfas @
blanchet@42001
  1892
    maps (needed_value_axioms_for_datatype ofs kk dtypes) need_vals @
blanchet@41875
  1893
    sym_break_axioms_for_datatypes hol_ctxt binarize need_us datatype_sym_break
blanchet@41875
  1894
                                   kk rel_table nfas dtypes @
blanchet@41998
  1895
    maps (other_axioms_for_datatype hol_ctxt binarize need_vals bits ofs kk
blanchet@41998
  1896
                                    rel_table) dtypes
blanchet@41802
  1897
  end
blanchet@41802
  1898
blanchet@33192
  1899
end;