src/HOL/Tools/Nitpick/nitpick_peephole.ML
author blanchet
Mon Feb 22 19:31:00 2010 +0100 (2010-02-22)
changeset 35284 9edc2bd6d2bd
parent 35280 54ab4921f826
child 35385 29f81babefd7
permissions -rw-r--r--
enabled Nitpick's support for quotient types + shortened the Nitpick tests a bit
     1 (*  Title:      HOL/Tools/Nitpick/nitpick_peephole.ML
     2     Author:     Jasmin Blanchette, TU Muenchen
     3     Copyright   2008, 2009, 2010
     4 
     5 Peephole optimizer for Nitpick.
     6 *)
     7 
     8 signature NITPICK_PEEPHOLE =
     9 sig
    10   type n_ary_index = Kodkod.n_ary_index
    11   type formula = Kodkod.formula
    12   type int_expr = Kodkod.int_expr
    13   type rel_expr = Kodkod.rel_expr
    14   type decl = Kodkod.decl
    15   type expr_assign = Kodkod.expr_assign
    16 
    17   type name_pool = {
    18     rels: n_ary_index list,
    19     vars: n_ary_index list,
    20     formula_reg: int,
    21     rel_reg: int}
    22 
    23   val initial_pool : name_pool
    24   val not3_rel : n_ary_index
    25   val suc_rel : n_ary_index
    26   val unsigned_bit_word_sel_rel : n_ary_index
    27   val signed_bit_word_sel_rel : n_ary_index
    28   val nat_add_rel : n_ary_index
    29   val int_add_rel : n_ary_index
    30   val nat_subtract_rel : n_ary_index
    31   val int_subtract_rel : n_ary_index
    32   val nat_multiply_rel : n_ary_index
    33   val int_multiply_rel : n_ary_index
    34   val nat_divide_rel : n_ary_index
    35   val int_divide_rel : n_ary_index
    36   val nat_less_rel : n_ary_index
    37   val int_less_rel : n_ary_index
    38   val gcd_rel : n_ary_index
    39   val lcm_rel : n_ary_index
    40   val norm_frac_rel : n_ary_index
    41   val atom_for_bool : int -> bool -> rel_expr
    42   val formula_for_bool : bool -> formula
    43   val atom_for_nat : int * int -> int -> int
    44   val min_int_for_card : int -> int
    45   val max_int_for_card : int -> int
    46   val int_for_atom : int * int -> int -> int
    47   val atom_for_int : int * int -> int -> int
    48   val is_twos_complement_representable : int -> int -> bool
    49   val inline_rel_expr : rel_expr -> bool
    50   val empty_n_ary_rel : int -> rel_expr
    51   val num_seq : int -> int -> int_expr list
    52   val s_and : formula -> formula -> formula
    53 
    54   type kodkod_constrs = {
    55     kk_all: decl list -> formula -> formula,
    56     kk_exist: decl list -> formula -> formula,
    57     kk_formula_let: expr_assign list -> formula -> formula,
    58     kk_formula_if: formula -> formula -> formula -> formula,
    59     kk_or: formula -> formula -> formula,
    60     kk_not: formula -> formula,
    61     kk_iff: formula -> formula -> formula,
    62     kk_implies: formula -> formula -> formula,
    63     kk_and: formula -> formula -> formula,
    64     kk_subset: rel_expr -> rel_expr -> formula,
    65     kk_rel_eq: rel_expr -> rel_expr -> formula,
    66     kk_no: rel_expr -> formula,
    67     kk_lone: rel_expr -> formula,
    68     kk_one: rel_expr -> formula,
    69     kk_some: rel_expr -> formula,
    70     kk_rel_let: expr_assign list -> rel_expr -> rel_expr,
    71     kk_rel_if: formula -> rel_expr -> rel_expr -> rel_expr,
    72     kk_union: rel_expr -> rel_expr -> rel_expr,
    73     kk_difference: rel_expr -> rel_expr -> rel_expr,
    74     kk_override: rel_expr -> rel_expr -> rel_expr,
    75     kk_intersect: rel_expr -> rel_expr -> rel_expr,
    76     kk_product: rel_expr -> rel_expr -> rel_expr,
    77     kk_join: rel_expr -> rel_expr -> rel_expr,
    78     kk_closure: rel_expr -> rel_expr,
    79     kk_reflexive_closure: rel_expr -> rel_expr,
    80     kk_comprehension: decl list -> formula -> rel_expr,
    81     kk_project: rel_expr -> int_expr list -> rel_expr,
    82     kk_project_seq: rel_expr -> int -> int -> rel_expr,
    83     kk_not3: rel_expr -> rel_expr,
    84     kk_nat_less: rel_expr -> rel_expr -> rel_expr,
    85     kk_int_less: rel_expr -> rel_expr -> rel_expr
    86   }
    87 
    88   val kodkod_constrs : bool -> int -> int -> int -> kodkod_constrs
    89 end;
    90 
    91 structure Nitpick_Peephole : NITPICK_PEEPHOLE =
    92 struct
    93 
    94 open Kodkod
    95 open Nitpick_Util
    96 
    97 type name_pool = {
    98   rels: n_ary_index list,
    99   vars: n_ary_index list,
   100   formula_reg: int,
   101   rel_reg: int}
   102 
   103 (* If you add new built-in relations, make sure to increment the counters here
   104    as well to avoid name clashes (which fortunately would be detected by
   105    Kodkodi). *)
   106 val initial_pool =
   107   {rels = [(2, 10), (3, 20), (4, 10)], vars = [], formula_reg = 10,
   108    rel_reg = 10}
   109 
   110 val not3_rel = (2, 0)
   111 val suc_rel = (2, 1)
   112 val unsigned_bit_word_sel_rel = (2, 2)
   113 val signed_bit_word_sel_rel = (2, 3)
   114 val nat_add_rel = (3, 0)
   115 val int_add_rel = (3, 1)
   116 val nat_subtract_rel = (3, 2)
   117 val int_subtract_rel = (3, 3)
   118 val nat_multiply_rel = (3, 4)
   119 val int_multiply_rel = (3, 5)
   120 val nat_divide_rel = (3, 6)
   121 val int_divide_rel = (3, 7)
   122 val nat_less_rel = (3, 8)
   123 val int_less_rel = (3, 9)
   124 val gcd_rel = (3, 10)
   125 val lcm_rel = (3, 11)
   126 val norm_frac_rel = (4, 0)
   127 
   128 (* int -> bool -> rel_expr *)
   129 fun atom_for_bool j0 = Atom o Integer.add j0 o int_for_bool
   130 (* bool -> formula *)
   131 fun formula_for_bool b = if b then True else False
   132 
   133 (* int * int -> int -> int *)
   134 fun atom_for_nat (k, j0) n = if n < 0 orelse n >= k then ~1 else n + j0
   135 (* int -> int *)
   136 fun min_int_for_card k = ~k div 2 + 1
   137 fun max_int_for_card k = k div 2
   138 (* int * int -> int -> int *)
   139 fun int_for_atom (k, j0) j =
   140   let val j = j - j0 in if j <= max_int_for_card k then j else j - k end
   141 fun atom_for_int (k, j0) n =
   142   if n < min_int_for_card k orelse n > max_int_for_card k then ~1
   143   else if n < 0 then n + k + j0
   144   else n + j0
   145 (* int -> int -> bool *)
   146 fun is_twos_complement_representable bits n =
   147   let val max = reasonable_power 2 bits in n >= ~ max andalso n < max end
   148 
   149 (* rel_expr -> bool *)
   150 fun is_none_product (Product (r1, r2)) =
   151     is_none_product r1 orelse is_none_product r2
   152   | is_none_product None = true
   153   | is_none_product _ = false
   154 
   155 (* rel_expr -> bool *)
   156 fun is_one_rel_expr (Atom _) = true
   157   | is_one_rel_expr (AtomSeq (1, _)) = true
   158   | is_one_rel_expr (Var _) = true
   159   | is_one_rel_expr _ = false
   160 
   161 (* rel_expr -> bool *)
   162 fun inline_rel_expr (Product (r1, r2)) =
   163     inline_rel_expr r1 andalso inline_rel_expr r2
   164   | inline_rel_expr Iden = true
   165   | inline_rel_expr Ints = true
   166   | inline_rel_expr None = true
   167   | inline_rel_expr Univ = true
   168   | inline_rel_expr (Atom _) = true
   169   | inline_rel_expr (AtomSeq _) = true
   170   | inline_rel_expr (Rel _) = true
   171   | inline_rel_expr (Var _) = true
   172   | inline_rel_expr (RelReg _) = true
   173   | inline_rel_expr _ = false
   174 
   175 (* rel_expr -> rel_expr -> bool option *)
   176 fun rel_expr_equal None (Atom _) = SOME false
   177   | rel_expr_equal None (AtomSeq (k, _)) = SOME (k = 0)
   178   | rel_expr_equal (Atom _) None = SOME false
   179   | rel_expr_equal (AtomSeq (k, _)) None = SOME (k = 0)
   180   | rel_expr_equal (Atom j1) (Atom j2) = SOME (j1 = j2)
   181   | rel_expr_equal (Atom j) (AtomSeq (k, j0)) = SOME (j = j0 andalso k = 1)
   182   | rel_expr_equal (AtomSeq (k, j0)) (Atom j) = SOME (j = j0 andalso k = 1)
   183   | rel_expr_equal (AtomSeq x1) (AtomSeq x2) = SOME (x1 = x2)
   184   | rel_expr_equal r1 r2 = if r1 = r2 then SOME true else NONE
   185 
   186 (* rel_expr -> rel_expr -> bool option *)
   187 fun rel_expr_intersects (Atom j1) (Atom j2) = SOME (j1 = j2)
   188   | rel_expr_intersects (Atom j) (AtomSeq (k, j0)) = SOME (j < j0 + k)
   189   | rel_expr_intersects (AtomSeq (k, j0)) (Atom j) = SOME (j < j0 + k)
   190   | rel_expr_intersects (AtomSeq (k1, j01)) (AtomSeq (k2, j02)) =
   191     SOME (k1 > 0 andalso k2 > 0 andalso j01 + k1 > j02 andalso j02 + k2 > j01)
   192   | rel_expr_intersects r1 r2 =
   193     if is_none_product r1 orelse is_none_product r2 then SOME false else NONE
   194 
   195 (* int -> rel_expr *)
   196 fun empty_n_ary_rel 0 = raise ARG ("Nitpick_Peephole.empty_n_ary_rel", "0")
   197   | empty_n_ary_rel n = funpow (n - 1) (curry Product None) None
   198 
   199 (* decl -> rel_expr *)
   200 fun decl_one_set (DeclOne (_, r)) = r
   201   | decl_one_set _ =
   202     raise ARG ("Nitpick_Peephole.decl_one_set", "not \"DeclOne\"")
   203 
   204 (* int_expr -> bool *)
   205 fun is_Num (Num _) = true
   206   | is_Num _ = false
   207 (* int_expr -> int *)
   208 fun dest_Num (Num k) = k
   209   | dest_Num _ = raise ARG ("Nitpick_Peephole.dest_Num", "not \"Num\"")
   210 (* int -> int -> int_expr list *)
   211 fun num_seq j0 n = map Num (index_seq j0 n)
   212 
   213 (* rel_expr -> rel_expr -> bool *)
   214 fun occurs_in_union r (Union (r1, r2)) =
   215     occurs_in_union r r1 orelse occurs_in_union r r2
   216   | occurs_in_union r r' = (r = r')
   217 
   218 (* rel_expr -> rel_expr -> rel_expr *)
   219 fun s_and True f2 = f2
   220   | s_and False _ = False
   221   | s_and f1 True = f1
   222   | s_and _ False = False
   223   | s_and f1 f2 = And (f1, f2)
   224 
   225 type kodkod_constrs = {
   226   kk_all: decl list -> formula -> formula,
   227   kk_exist: decl list -> formula -> formula,
   228   kk_formula_let: expr_assign list -> formula -> formula,
   229   kk_formula_if: formula -> formula -> formula -> formula,
   230   kk_or: formula -> formula -> formula,
   231   kk_not: formula -> formula,
   232   kk_iff: formula -> formula -> formula,
   233   kk_implies: formula -> formula -> formula,
   234   kk_and: formula -> formula -> formula,
   235   kk_subset: rel_expr -> rel_expr -> formula,
   236   kk_rel_eq: rel_expr -> rel_expr -> formula,
   237   kk_no: rel_expr -> formula,
   238   kk_lone: rel_expr -> formula,
   239   kk_one: rel_expr -> formula,
   240   kk_some: rel_expr -> formula,
   241   kk_rel_let: expr_assign list -> rel_expr -> rel_expr,
   242   kk_rel_if: formula -> rel_expr -> rel_expr -> rel_expr,
   243   kk_union: rel_expr -> rel_expr -> rel_expr,
   244   kk_difference: rel_expr -> rel_expr -> rel_expr,
   245   kk_override: rel_expr -> rel_expr -> rel_expr,
   246   kk_intersect: rel_expr -> rel_expr -> rel_expr,
   247   kk_product: rel_expr -> rel_expr -> rel_expr,
   248   kk_join: rel_expr -> rel_expr -> rel_expr,
   249   kk_closure: rel_expr -> rel_expr,
   250   kk_reflexive_closure: rel_expr -> rel_expr,
   251   kk_comprehension: decl list -> formula -> rel_expr,
   252   kk_project: rel_expr -> int_expr list -> rel_expr,
   253   kk_project_seq: rel_expr -> int -> int -> rel_expr,
   254   kk_not3: rel_expr -> rel_expr,
   255   kk_nat_less: rel_expr -> rel_expr -> rel_expr,
   256   kk_int_less: rel_expr -> rel_expr -> rel_expr
   257 }
   258 
   259 (* We assume throughout that Kodkod variables have a "one" constraint. This is
   260    always the case if Kodkod's skolemization is disabled. *)
   261 (* bool -> int -> int -> int -> kodkod_constrs *)
   262 fun kodkod_constrs optim nat_card int_card main_j0 =
   263   let
   264     (* bool -> int *)
   265     val from_bool = atom_for_bool main_j0
   266     (* int -> rel_expr *)
   267     fun from_nat n = Atom (n + main_j0)
   268     (* int -> int *)
   269     fun to_nat j = j - main_j0
   270     val to_int = int_for_atom (int_card, main_j0)
   271 
   272     (* decl list -> formula -> formula *)
   273     fun s_all _ True = True
   274       | s_all _ False = False
   275       | s_all [] f = f
   276       | s_all ds (All (ds', f)) = All (ds @ ds', f)
   277       | s_all ds f = All (ds, f)
   278     fun s_exist _ True = True
   279       | s_exist _ False = False
   280       | s_exist [] f = f
   281       | s_exist ds (Exist (ds', f)) = Exist (ds @ ds', f)
   282       | s_exist ds f = Exist (ds, f)
   283 
   284     (* expr_assign list -> formula -> formula *)
   285     fun s_formula_let _ True = True
   286       | s_formula_let _ False = False
   287       | s_formula_let assigns f = FormulaLet (assigns, f)
   288 
   289     (* formula -> formula *)
   290     fun s_not True = False
   291       | s_not False = True
   292       | s_not (All (ds, f)) = Exist (ds, s_not f)
   293       | s_not (Exist (ds, f)) = All (ds, s_not f)
   294       | s_not (Or (f1, f2)) = And (s_not f1, s_not f2)
   295       | s_not (Implies (f1, f2)) = And (f1, s_not f2)
   296       | s_not (And (f1, f2)) = Or (s_not f1, s_not f2)
   297       | s_not (Not f) = f
   298       | s_not (No r) = Some r
   299       | s_not (Some r) = No r
   300       | s_not f = Not f
   301 
   302     (* formula -> formula -> formula *)
   303     fun s_or True _ = True
   304       | s_or False f2 = f2
   305       | s_or _ True = True
   306       | s_or f1 False = f1
   307       | s_or f1 f2 = if f1 = f2 then f1 else Or (f1, f2)
   308     fun s_iff True f2 = f2
   309       | s_iff False f2 = s_not f2
   310       | s_iff f1 True = f1
   311       | s_iff f1 False = s_not f1
   312       | s_iff f1 f2 = if f1 = f2 then True else Iff (f1, f2)
   313     fun s_implies True f2 = f2
   314       | s_implies False _ = True
   315       | s_implies _ True = True
   316       | s_implies f1 False = s_not f1
   317       | s_implies f1 f2 = if f1 = f2 then True else Implies (f1, f2)
   318 
   319     (* formula -> formula -> formula -> formula *)
   320     fun s_formula_if True f2 _ = f2
   321       | s_formula_if False _ f3 = f3
   322       | s_formula_if f1 True f3 = s_or f1 f3
   323       | s_formula_if f1 False f3 = s_and (s_not f1) f3
   324       | s_formula_if f1 f2 True = s_implies f1 f2
   325       | s_formula_if f1 f2 False = s_and f1 f2
   326       | s_formula_if f f1 f2 = FormulaIf (f, f1, f2)
   327 
   328     (* rel_expr -> int_expr list -> rel_expr *)
   329     fun s_project r is =
   330       (case r of
   331          Project (r1, is') =>
   332          if forall is_Num is then
   333            s_project r1 (map (nth is' o dest_Num) is)
   334          else
   335            raise SAME ()
   336        | _ => raise SAME ())
   337       handle SAME () =>
   338              let val n = length is in
   339                if arity_of_rel_expr r = n andalso is = num_seq 0 n then r
   340                else Project (r, is)
   341              end
   342 
   343     (* (rel_expr -> formula) -> rel_expr -> formula *)
   344     fun s_xone xone r =
   345       if is_one_rel_expr r then
   346         True
   347       else case arity_of_rel_expr r of
   348         1 => xone r
   349       | arity => foldl1 And (map (xone o s_project r o single o Num)
   350                                  (index_seq 0 arity))
   351     (* rel_expr -> formula *)
   352     fun s_no None = True
   353       | s_no (Product (r1, r2)) = s_or (s_no r1) (s_no r2)
   354       | s_no (Intersect (Closure (Rel x), Iden)) = Acyclic x
   355       | s_no r = if is_one_rel_expr r then False else No r
   356     fun s_lone None = True
   357       | s_lone r = s_xone Lone r
   358     fun s_one None = False
   359       | s_one r = s_xone One r
   360     fun s_some None = False
   361       | s_some (Atom _) = True
   362       | s_some (Product (r1, r2)) = s_and (s_some r1) (s_some r2)
   363       | s_some r = if is_one_rel_expr r then True else Some r
   364 
   365     (* rel_expr -> rel_expr *)
   366     fun s_not3 (Atom j) = Atom (if j = main_j0 then j + 1 else j - 1)
   367       | s_not3 (r as Join (r1, r2)) =
   368         if r2 = Rel not3_rel then r1 else Join (r, Rel not3_rel)
   369       | s_not3 r = Join (r, Rel not3_rel)
   370 
   371     (* rel_expr -> rel_expr -> formula *)
   372     fun s_rel_eq r1 r2 =
   373       (case (r1, r2) of
   374          (Join (r11, Rel x), _) =>
   375          if x = not3_rel then s_rel_eq r11 (s_not3 r2) else raise SAME ()
   376        | (_, Join (r21, Rel x)) =>
   377          if x = not3_rel then s_rel_eq r21 (s_not3 r1) else raise SAME ()
   378        | (RelIf (f, r11, r12), _) =>
   379          if inline_rel_expr r2 then
   380            s_formula_if f (s_rel_eq r11 r2) (s_rel_eq r12 r2)
   381          else
   382            raise SAME ()
   383        | (_, RelIf (f, r21, r22)) =>
   384          if inline_rel_expr r1 then
   385            s_formula_if f (s_rel_eq r1 r21) (s_rel_eq r1 r22)
   386          else
   387            raise SAME ()
   388        | (RelLet (bs, r1'), Atom _) => s_formula_let bs (s_rel_eq r1' r2)
   389        | (Atom _, RelLet (bs, r2')) => s_formula_let bs (s_rel_eq r1 r2')
   390        | _ => raise SAME ())
   391       handle SAME () =>
   392              case rel_expr_equal r1 r2 of
   393                SOME true => True
   394              | SOME false => False
   395              | NONE =>
   396                case (r1, r2) of
   397                  (_, RelIf (f, r21, r22)) =>
   398                   if inline_rel_expr r1 then
   399                     s_formula_if f (s_rel_eq r1 r21) (s_rel_eq r1 r22)
   400                   else
   401                     RelEq (r1, r2)
   402                | (RelIf (f, r11, r12), _) =>
   403                   if inline_rel_expr r2 then
   404                     s_formula_if f (s_rel_eq r11 r2) (s_rel_eq r12 r2)
   405                   else
   406                     RelEq (r1, r2)
   407                | (_, None) => s_no r1
   408                | (None, _) => s_no r2
   409                | _ => RelEq (r1, r2)
   410     fun s_subset (Atom j1) (Atom j2) = formula_for_bool (j1 = j2)
   411       | s_subset (Atom j) (AtomSeq (k, j0)) =
   412         formula_for_bool (j >= j0 andalso j < j0 + k)
   413       | s_subset (Union (r11, r12)) r2 =
   414         s_and (s_subset r11 r2) (s_subset r12 r2)
   415       | s_subset r1 (r2 as Union (r21, r22)) =
   416         if is_one_rel_expr r1 then
   417           s_or (s_subset r1 r21) (s_subset r1 r22)
   418         else
   419           if s_subset r1 r21 = True orelse s_subset r1 r22 = True orelse
   420              r1 = r2 then
   421             True
   422           else
   423             Subset (r1, r2)
   424       | s_subset r1 r2 =
   425         if r1 = r2 orelse is_none_product r1 then True
   426         else if is_none_product r2 then s_no r1
   427         else if forall is_one_rel_expr [r1, r2] then s_rel_eq r1 r2
   428         else Subset (r1, r2)
   429 
   430     (* expr_assign list -> rel_expr -> rel_expr *)
   431     fun s_rel_let [b as AssignRelReg (x', r')] (r as RelReg x) =
   432         if x = x' then r' else RelLet ([b], r)
   433       | s_rel_let bs r = RelLet (bs, r)
   434 
   435     (* formula -> rel_expr -> rel_expr -> rel_expr *)
   436     fun s_rel_if f r1 r2 =
   437       (case (f, r1, r2) of
   438          (True, _, _) => r1
   439        | (False, _, _) => r2
   440        | (No r1', None, RelIf (One r2', r3', r4')) =>
   441          if r1' = r2' andalso r2' = r3' then s_rel_if (Lone r1') r1' r4'
   442          else raise SAME ()
   443        | _ => raise SAME ())
   444       handle SAME () => if r1 = r2 then r1 else RelIf (f, r1, r2)
   445 
   446     (* rel_expr -> rel_expr -> rel_expr *)
   447     fun s_union r1 (Union (r21, r22)) = s_union (s_union r1 r21) r22
   448       | s_union r1 r2 =
   449         if is_none_product r1 then r2
   450         else if is_none_product r2 then r1
   451         else if r1 = r2 then r1
   452         else if occurs_in_union r2 r1 then r1
   453         else Union (r1, r2)
   454     fun s_difference r1 r2 =
   455       if is_none_product r1 orelse is_none_product r2 then r1
   456       else if r1 = r2 then empty_n_ary_rel (arity_of_rel_expr r1)
   457       else Difference (r1, r2)
   458     fun s_override r1 r2 =
   459       if is_none_product r2 then r1
   460       else if is_none_product r1 then r2
   461       else Override (r1, r2)
   462     fun s_intersect r1 r2 =
   463       case rel_expr_intersects r1 r2 of
   464         SOME true => if r1 = r2 then r1 else Intersect (r1, r2)
   465       | SOME false => empty_n_ary_rel (arity_of_rel_expr r1)
   466       | NONE => if is_none_product r1 then r1
   467                 else if is_none_product r2 then r2
   468                 else Intersect (r1, r2)
   469     fun s_product r1 r2 =
   470       if is_none_product r1 then
   471         Product (r1, empty_n_ary_rel (arity_of_rel_expr r2))
   472       else if is_none_product r2 then
   473         Product (empty_n_ary_rel (arity_of_rel_expr r1), r2)
   474       else
   475         Product (r1, r2)
   476     fun s_join r1 (Product (Product (r211, r212), r22)) =
   477         Product (s_join r1 (Product (r211, r212)), r22)
   478       | s_join (Product (r11, Product (r121, r122))) r2 =
   479         Product (r11, s_join (Product (r121, r122)) r2)
   480       | s_join None r = empty_n_ary_rel (arity_of_rel_expr r - 1)
   481       | s_join r None = empty_n_ary_rel (arity_of_rel_expr r - 1)
   482       | s_join (Product (None, None)) r = empty_n_ary_rel (arity_of_rel_expr r)
   483       | s_join r (Product (None, None)) = empty_n_ary_rel (arity_of_rel_expr r)
   484       | s_join Iden r2 = r2
   485       | s_join r1 Iden = r1
   486       | s_join (Product (r1, r2)) Univ =
   487         if arity_of_rel_expr r2 = 1 then r1
   488         else Product (r1, s_join r2 Univ)
   489       | s_join Univ (Product (r1, r2)) =
   490         if arity_of_rel_expr r1 = 1 then r2
   491         else Product (s_join Univ r1, r2)
   492       | s_join r1 (r2 as Product (r21, r22)) =
   493         if arity_of_rel_expr r1 = 1 then
   494           case rel_expr_intersects r1 r21 of
   495             SOME true => r22
   496           | SOME false => empty_n_ary_rel (arity_of_rel_expr r2 - 1)
   497           | NONE => Join (r1, r2)
   498         else
   499           Join (r1, r2)
   500       | s_join (r1 as Product (r11, r12)) r2 =
   501         if arity_of_rel_expr r2 = 1 then
   502           case rel_expr_intersects r2 r12 of
   503             SOME true => r11
   504           | SOME false => empty_n_ary_rel (arity_of_rel_expr r1 - 1)
   505           | NONE => Join (r1, r2)
   506         else
   507           Join (r1, r2)
   508       | s_join r1 (r2 as RelIf (f, r21, r22)) =
   509         if inline_rel_expr r1 then s_rel_if f (s_join r1 r21) (s_join r1 r22)
   510         else Join (r1, r2)
   511       | s_join (r1 as RelIf (f, r11, r12)) r2 =
   512         if inline_rel_expr r2 then s_rel_if f (s_join r11 r2) (s_join r12 r2)
   513         else Join (r1, r2)
   514       | s_join (r1 as Atom j1) (r2 as Rel (x as (2, _))) =
   515         if x = suc_rel then
   516           let val n = to_nat j1 + 1 in
   517             if n < nat_card then from_nat n else None
   518           end
   519         else
   520           Join (r1, r2)
   521       | s_join r1 (r2 as Project (r21, Num k :: is)) =
   522         if k = arity_of_rel_expr r21 - 1 andalso arity_of_rel_expr r1 = 1 then
   523           s_project (s_join r21 r1) is
   524         else
   525           Join (r1, r2)
   526       | s_join r1 (Join (r21, r22 as Rel (x as (3, _)))) =
   527         ((if x = nat_add_rel then
   528             case (r21, r1) of
   529               (Atom j1, Atom j2) =>
   530               let val n = to_nat j1 + to_nat j2 in
   531                 if n < nat_card then from_nat n else None
   532               end
   533             | (Atom j, r) =>
   534               (case to_nat j of
   535                  0 => r
   536                | 1 => s_join r (Rel suc_rel)
   537                | _ => raise SAME ())
   538             | (r, Atom j) =>
   539               (case to_nat j of
   540                  0 => r
   541                | 1 => s_join r (Rel suc_rel)
   542                | _ => raise SAME ())
   543             | _ => raise SAME ()
   544           else if x = nat_subtract_rel then
   545             case (r21, r1) of
   546               (Atom j1, Atom j2) => from_nat (nat_minus (to_nat j1) (to_nat j2))
   547             | _ => raise SAME ()
   548           else if x = nat_multiply_rel then
   549             case (r21, r1) of
   550               (Atom j1, Atom j2) =>
   551               let val n = to_nat j1 * to_nat j2 in
   552                 if n < nat_card then from_nat n else None
   553               end
   554             | (Atom j, r) =>
   555               (case to_nat j of 0 => Atom j | 1 => r | _ => raise SAME ())
   556             | (r, Atom j) =>
   557               (case to_nat j of 0 => Atom j | 1 => r | _ => raise SAME ())
   558             | _ => raise SAME ()
   559           else
   560             raise SAME ())
   561          handle SAME () => List.foldr Join r22 [r1, r21])
   562       | s_join r1 r2 = Join (r1, r2)
   563 
   564     (* rel_expr -> rel_expr *)
   565     fun s_closure Iden = Iden
   566       | s_closure r = if is_none_product r then r else Closure r
   567     fun s_reflexive_closure Iden = Iden
   568       | s_reflexive_closure r =
   569         if is_none_product r then Iden else ReflexiveClosure r
   570 
   571     (* decl list -> formula -> rel_expr *)
   572     fun s_comprehension ds False = empty_n_ary_rel (length ds)
   573       | s_comprehension ds True = fold1 s_product (map decl_one_set ds)
   574       | s_comprehension [d as DeclOne ((1, j1), r)]
   575                         (f as RelEq (Var (1, j2), Atom j)) =
   576         if j1 = j2 andalso rel_expr_intersects (Atom j) r = SOME true then
   577           Atom j
   578         else
   579           Comprehension ([d], f)
   580       | s_comprehension ds f = Comprehension (ds, f)
   581 
   582     (* rel_expr -> int -> int -> rel_expr *)
   583     fun s_project_seq r =
   584       let
   585         (* int -> rel_expr -> int -> int -> rel_expr *)
   586         fun aux arity r j0 n =
   587           if j0 = 0 andalso arity = n then
   588             r
   589           else case r of
   590             RelIf (f, r1, r2) =>
   591             s_rel_if f (aux arity r1 j0 n) (aux arity r2 j0 n)
   592           | Product (r1, r2) =>
   593             let
   594               val arity2 = arity_of_rel_expr r2
   595               val arity1 = arity - arity2
   596               val n1 = Int.min (nat_minus arity1 j0, n)
   597               val n2 = n - n1
   598               (* unit -> rel_expr *)
   599               fun one () = aux arity1 r1 j0 n1
   600               fun two () = aux arity2 r2 (nat_minus j0 arity1) n2
   601             in
   602               case (n1, n2) of
   603                 (0, _) => s_rel_if (s_some r1) (two ()) (empty_n_ary_rel n2)
   604               | (_, 0) => s_rel_if (s_some r2) (one ()) (empty_n_ary_rel n1)
   605               | _ => s_product (one ()) (two ())
   606             end
   607           | _ => s_project r (num_seq j0 n)
   608       in aux (arity_of_rel_expr r) r end
   609 
   610     (* rel_expr -> rel_expr -> rel_expr *)
   611     fun s_nat_less (Atom j1) (Atom j2) = from_bool (j1 < j2)
   612       | s_nat_less r1 r2 = fold s_join [r1, r2] (Rel nat_less_rel)
   613     fun s_int_less (Atom j1) (Atom j2) = from_bool (to_int j1 < to_int j2)
   614       | s_int_less r1 r2 = fold s_join [r1, r2] (Rel int_less_rel)
   615 
   616     (* rel_expr -> int -> int -> rel_expr *)
   617     fun d_project_seq r j0 n = Project (r, num_seq j0 n)
   618     (* rel_expr -> rel_expr *)
   619     fun d_not3 r = Join (r, Rel not3_rel)
   620     (* rel_expr -> rel_expr -> rel_expr *)
   621     fun d_nat_less r1 r2 = List.foldl Join (Rel nat_less_rel) [r1, r2]
   622     fun d_int_less r1 r2 = List.foldl Join (Rel int_less_rel) [r1, r2]
   623   in
   624     if optim then
   625       {kk_all = s_all, kk_exist = s_exist, kk_formula_let = s_formula_let,
   626        kk_formula_if = s_formula_if, kk_or = s_or, kk_not = s_not,
   627        kk_iff = s_iff, kk_implies = s_implies, kk_and = s_and,
   628        kk_subset = s_subset, kk_rel_eq = s_rel_eq, kk_no = s_no,
   629        kk_lone = s_lone, kk_one = s_one, kk_some = s_some,
   630        kk_rel_let = s_rel_let, kk_rel_if = s_rel_if, kk_union = s_union,
   631        kk_difference = s_difference, kk_override = s_override,
   632        kk_intersect = s_intersect, kk_product = s_product, kk_join = s_join,
   633        kk_closure = s_closure, kk_reflexive_closure = s_reflexive_closure,
   634        kk_comprehension = s_comprehension, kk_project = s_project,
   635        kk_project_seq = s_project_seq, kk_not3 = s_not3,
   636        kk_nat_less = s_nat_less, kk_int_less = s_int_less}
   637     else
   638       {kk_all = curry All, kk_exist = curry Exist,
   639        kk_formula_let = curry FormulaLet, kk_formula_if = curry3 FormulaIf,
   640        kk_or = curry Or,kk_not = Not, kk_iff = curry Iff, kk_implies = curry
   641        Implies, kk_and = curry And, kk_subset = curry Subset, kk_rel_eq = curry
   642        RelEq, kk_no = No, kk_lone = Lone, kk_one = One, kk_some = Some,
   643        kk_rel_let = curry RelLet, kk_rel_if = curry3 RelIf, kk_union = curry
   644        Union, kk_difference = curry Difference, kk_override = curry Override,
   645        kk_intersect = curry Intersect, kk_product = curry Product,
   646        kk_join = curry Join, kk_closure = Closure,
   647        kk_reflexive_closure = ReflexiveClosure, kk_comprehension = curry
   648        Comprehension, kk_project = curry Project,
   649        kk_project_seq = d_project_seq, kk_not3 = d_not3,
   650        kk_nat_less = d_nat_less, kk_int_less = d_int_less}
   651   end
   652 
   653 end;