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