src/HOL/Tools/Nitpick/nitpick_peephole.ML
author blanchet
Sat Apr 24 16:33:01 2010 +0200 (2010-04-24)
changeset 36385 ff5f88702590
parent 35385 29f81babefd7
child 36390 eee4ee6a5cbe
permissions -rw-r--r--
remove type annotations as comments;
Nitpick is now 1136 lines shorter
     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 fun atom_for_bool j0 = Atom o Integer.add j0 o int_from_bool
   129 fun formula_for_bool b = if b then True else False
   130 
   131 fun atom_for_nat (k, j0) n = if n < 0 orelse n >= k then ~1 else n + j0
   132 fun min_int_for_card k = ~k div 2 + 1
   133 fun max_int_for_card k = k div 2
   134 fun int_for_atom (k, j0) j =
   135   let val j = j - j0 in if j <= max_int_for_card k then j else j - k end
   136 fun atom_for_int (k, j0) n =
   137   if n < min_int_for_card k orelse n > max_int_for_card k then ~1
   138   else if n < 0 then n + k + j0
   139   else n + j0
   140 fun is_twos_complement_representable bits n =
   141   let val max = reasonable_power 2 bits in n >= ~ max andalso n < max end
   142 
   143 fun is_none_product (Product (r1, r2)) =
   144     is_none_product r1 orelse is_none_product r2
   145   | is_none_product None = true
   146   | is_none_product _ = false
   147 
   148 fun is_one_rel_expr (Atom _) = true
   149   | is_one_rel_expr (AtomSeq (1, _)) = true
   150   | is_one_rel_expr (Var _) = true
   151   | is_one_rel_expr _ = false
   152 
   153 fun inline_rel_expr (Product (r1, r2)) =
   154     inline_rel_expr r1 andalso inline_rel_expr r2
   155   | inline_rel_expr Iden = true
   156   | inline_rel_expr Ints = true
   157   | inline_rel_expr None = true
   158   | inline_rel_expr Univ = true
   159   | inline_rel_expr (Atom _) = true
   160   | inline_rel_expr (AtomSeq _) = true
   161   | inline_rel_expr (Rel _) = true
   162   | inline_rel_expr (Var _) = true
   163   | inline_rel_expr (RelReg _) = true
   164   | inline_rel_expr _ = false
   165 
   166 fun rel_expr_equal None (Atom _) = SOME false
   167   | rel_expr_equal None (AtomSeq (k, _)) = SOME (k = 0)
   168   | rel_expr_equal (Atom _) None = SOME false
   169   | rel_expr_equal (AtomSeq (k, _)) None = SOME (k = 0)
   170   | rel_expr_equal (Atom j1) (Atom j2) = SOME (j1 = j2)
   171   | rel_expr_equal (Atom j) (AtomSeq (k, j0)) = SOME (j = j0 andalso k = 1)
   172   | rel_expr_equal (AtomSeq (k, j0)) (Atom j) = SOME (j = j0 andalso k = 1)
   173   | rel_expr_equal (AtomSeq x1) (AtomSeq x2) = SOME (x1 = x2)
   174   | rel_expr_equal r1 r2 = if r1 = r2 then SOME true else NONE
   175 
   176 fun rel_expr_intersects (Atom j1) (Atom j2) = SOME (j1 = j2)
   177   | rel_expr_intersects (Atom j) (AtomSeq (k, j0)) = SOME (j < j0 + k)
   178   | rel_expr_intersects (AtomSeq (k, j0)) (Atom j) = SOME (j < j0 + k)
   179   | rel_expr_intersects (AtomSeq (k1, j01)) (AtomSeq (k2, j02)) =
   180     SOME (k1 > 0 andalso k2 > 0 andalso j01 + k1 > j02 andalso j02 + k2 > j01)
   181   | rel_expr_intersects r1 r2 =
   182     if is_none_product r1 orelse is_none_product r2 then SOME false else NONE
   183 
   184 fun empty_n_ary_rel 0 = raise ARG ("Nitpick_Peephole.empty_n_ary_rel", "0")
   185   | empty_n_ary_rel n = funpow (n - 1) (curry Product None) None
   186 
   187 fun decl_one_set (DeclOne (_, r)) = r
   188   | decl_one_set _ =
   189     raise ARG ("Nitpick_Peephole.decl_one_set", "not \"DeclOne\"")
   190 
   191 fun is_Num (Num _) = true
   192   | is_Num _ = false
   193 fun dest_Num (Num k) = k
   194   | dest_Num _ = raise ARG ("Nitpick_Peephole.dest_Num", "not \"Num\"")
   195 fun num_seq j0 n = map Num (index_seq j0 n)
   196 
   197 fun occurs_in_union r (Union (r1, r2)) =
   198     occurs_in_union r r1 orelse occurs_in_union r r2
   199   | occurs_in_union r r' = (r = r')
   200 
   201 fun s_and True f2 = f2
   202   | s_and False _ = False
   203   | s_and f1 True = f1
   204   | s_and _ False = False
   205   | s_and f1 f2 = And (f1, f2)
   206 
   207 type kodkod_constrs = {
   208   kk_all: decl list -> formula -> formula,
   209   kk_exist: decl list -> formula -> formula,
   210   kk_formula_let: expr_assign list -> formula -> formula,
   211   kk_formula_if: formula -> formula -> formula -> formula,
   212   kk_or: formula -> formula -> formula,
   213   kk_not: formula -> formula,
   214   kk_iff: formula -> formula -> formula,
   215   kk_implies: formula -> formula -> formula,
   216   kk_and: formula -> formula -> formula,
   217   kk_subset: rel_expr -> rel_expr -> formula,
   218   kk_rel_eq: rel_expr -> rel_expr -> formula,
   219   kk_no: rel_expr -> formula,
   220   kk_lone: rel_expr -> formula,
   221   kk_one: rel_expr -> formula,
   222   kk_some: rel_expr -> formula,
   223   kk_rel_let: expr_assign list -> rel_expr -> rel_expr,
   224   kk_rel_if: formula -> rel_expr -> rel_expr -> rel_expr,
   225   kk_union: rel_expr -> rel_expr -> rel_expr,
   226   kk_difference: rel_expr -> rel_expr -> rel_expr,
   227   kk_override: rel_expr -> rel_expr -> rel_expr,
   228   kk_intersect: rel_expr -> rel_expr -> rel_expr,
   229   kk_product: rel_expr -> rel_expr -> rel_expr,
   230   kk_join: rel_expr -> rel_expr -> rel_expr,
   231   kk_closure: rel_expr -> rel_expr,
   232   kk_reflexive_closure: rel_expr -> rel_expr,
   233   kk_comprehension: decl list -> formula -> rel_expr,
   234   kk_project: rel_expr -> int_expr list -> rel_expr,
   235   kk_project_seq: rel_expr -> int -> int -> rel_expr,
   236   kk_not3: rel_expr -> rel_expr,
   237   kk_nat_less: rel_expr -> rel_expr -> rel_expr,
   238   kk_int_less: rel_expr -> rel_expr -> rel_expr
   239 }
   240 
   241 (* We assume throughout that Kodkod variables have a "one" constraint. This is
   242    always the case if Kodkod's skolemization is disabled. *)
   243 fun kodkod_constrs optim nat_card int_card main_j0 =
   244   let
   245     val from_bool = atom_for_bool main_j0
   246     fun from_nat n = Atom (n + main_j0)
   247     fun to_nat j = j - main_j0
   248     val to_int = int_for_atom (int_card, main_j0)
   249 
   250     fun s_all _ True = True
   251       | s_all _ False = False
   252       | s_all [] f = f
   253       | s_all ds (All (ds', f)) = All (ds @ ds', f)
   254       | s_all ds f = All (ds, f)
   255     fun s_exist _ True = True
   256       | s_exist _ False = False
   257       | s_exist [] f = f
   258       | s_exist ds (Exist (ds', f)) = Exist (ds @ ds', f)
   259       | s_exist ds f = Exist (ds, f)
   260 
   261     fun s_formula_let _ True = True
   262       | s_formula_let _ False = False
   263       | s_formula_let assigns f = FormulaLet (assigns, f)
   264 
   265     fun s_not True = False
   266       | s_not False = True
   267       | s_not (All (ds, f)) = Exist (ds, s_not f)
   268       | s_not (Exist (ds, f)) = All (ds, s_not f)
   269       | s_not (Or (f1, f2)) = And (s_not f1, s_not f2)
   270       | s_not (Implies (f1, f2)) = And (f1, s_not f2)
   271       | s_not (And (f1, f2)) = Or (s_not f1, s_not f2)
   272       | s_not (Not f) = f
   273       | s_not (No r) = Some r
   274       | s_not (Some r) = No r
   275       | s_not f = Not f
   276 
   277     fun s_or True _ = True
   278       | s_or False f2 = f2
   279       | s_or _ True = True
   280       | s_or f1 False = f1
   281       | s_or f1 f2 = if f1 = f2 then f1 else Or (f1, f2)
   282     fun s_iff True f2 = f2
   283       | s_iff False f2 = s_not f2
   284       | s_iff f1 True = f1
   285       | s_iff f1 False = s_not f1
   286       | s_iff f1 f2 = if f1 = f2 then True else Iff (f1, f2)
   287     fun s_implies True f2 = f2
   288       | s_implies False _ = True
   289       | s_implies _ True = True
   290       | s_implies f1 False = s_not f1
   291       | s_implies f1 f2 = if f1 = f2 then True else Implies (f1, f2)
   292 
   293     fun s_formula_if True f2 _ = f2
   294       | s_formula_if False _ f3 = f3
   295       | s_formula_if f1 True f3 = s_or f1 f3
   296       | s_formula_if f1 False f3 = s_and (s_not f1) f3
   297       | s_formula_if f1 f2 True = s_implies f1 f2
   298       | s_formula_if f1 f2 False = s_and f1 f2
   299       | s_formula_if f f1 f2 = FormulaIf (f, f1, f2)
   300 
   301     fun s_project r is =
   302       (case r of
   303          Project (r1, is') =>
   304          if forall is_Num is then
   305            s_project r1 (map (nth is' o dest_Num) is)
   306          else
   307            raise SAME ()
   308        | _ => raise SAME ())
   309       handle SAME () =>
   310              let val n = length is in
   311                if arity_of_rel_expr r = n andalso is = num_seq 0 n then r
   312                else Project (r, is)
   313              end
   314 
   315     fun s_xone xone r =
   316       if is_one_rel_expr r then
   317         True
   318       else case arity_of_rel_expr r of
   319         1 => xone r
   320       | arity => foldl1 And (map (xone o s_project r o single o Num)
   321                                  (index_seq 0 arity))
   322     fun s_no None = True
   323       | s_no (Product (r1, r2)) = s_or (s_no r1) (s_no r2)
   324       | s_no (Intersect (Closure (Rel x), Iden)) = Acyclic x
   325       | s_no r = if is_one_rel_expr r then False else No r
   326     fun s_lone None = True
   327       | s_lone r = s_xone Lone r
   328     fun s_one None = False
   329       | s_one r = s_xone One r
   330     fun s_some None = False
   331       | s_some (Atom _) = True
   332       | s_some (Product (r1, r2)) = s_and (s_some r1) (s_some r2)
   333       | s_some r = if is_one_rel_expr r then True else Some r
   334 
   335     fun s_not3 (Atom j) = Atom (if j = main_j0 then j + 1 else j - 1)
   336       | s_not3 (r as Join (r1, r2)) =
   337         if r2 = Rel not3_rel then r1 else Join (r, Rel not3_rel)
   338       | s_not3 r = Join (r, Rel not3_rel)
   339 
   340     fun s_rel_eq r1 r2 =
   341       (case (r1, r2) of
   342          (Join (r11, Rel x), _) =>
   343          if x = not3_rel then s_rel_eq r11 (s_not3 r2) else raise SAME ()
   344        | (_, Join (r21, Rel x)) =>
   345          if x = not3_rel then s_rel_eq r21 (s_not3 r1) else raise SAME ()
   346        | (RelIf (f, r11, r12), _) =>
   347          if inline_rel_expr r2 then
   348            s_formula_if f (s_rel_eq r11 r2) (s_rel_eq r12 r2)
   349          else
   350            raise SAME ()
   351        | (_, RelIf (f, r21, r22)) =>
   352          if inline_rel_expr r1 then
   353            s_formula_if f (s_rel_eq r1 r21) (s_rel_eq r1 r22)
   354          else
   355            raise SAME ()
   356        | (RelLet (bs, r1'), Atom _) => s_formula_let bs (s_rel_eq r1' r2)
   357        | (Atom _, RelLet (bs, r2')) => s_formula_let bs (s_rel_eq r1 r2')
   358        | _ => raise SAME ())
   359       handle SAME () =>
   360              case rel_expr_equal r1 r2 of
   361                SOME true => True
   362              | SOME false => False
   363              | NONE =>
   364                case (r1, r2) of
   365                  (_, RelIf (f, r21, r22)) =>
   366                   if inline_rel_expr r1 then
   367                     s_formula_if f (s_rel_eq r1 r21) (s_rel_eq r1 r22)
   368                   else
   369                     RelEq (r1, r2)
   370                | (RelIf (f, r11, r12), _) =>
   371                   if inline_rel_expr r2 then
   372                     s_formula_if f (s_rel_eq r11 r2) (s_rel_eq r12 r2)
   373                   else
   374                     RelEq (r1, r2)
   375                | (_, None) => s_no r1
   376                | (None, _) => s_no r2
   377                | _ => RelEq (r1, r2)
   378     fun s_subset (Atom j1) (Atom j2) = formula_for_bool (j1 = j2)
   379       | s_subset (Atom j) (AtomSeq (k, j0)) =
   380         formula_for_bool (j >= j0 andalso j < j0 + k)
   381       | s_subset (Union (r11, r12)) r2 =
   382         s_and (s_subset r11 r2) (s_subset r12 r2)
   383       | s_subset r1 (r2 as Union (r21, r22)) =
   384         if is_one_rel_expr r1 then
   385           s_or (s_subset r1 r21) (s_subset r1 r22)
   386         else
   387           if s_subset r1 r21 = True orelse s_subset r1 r22 = True orelse
   388              r1 = r2 then
   389             True
   390           else
   391             Subset (r1, r2)
   392       | s_subset r1 r2 =
   393         if r1 = r2 orelse is_none_product r1 then True
   394         else if is_none_product r2 then s_no r1
   395         else if forall is_one_rel_expr [r1, r2] then s_rel_eq r1 r2
   396         else Subset (r1, r2)
   397 
   398     fun s_rel_let [b as AssignRelReg (x', r')] (r as RelReg x) =
   399         if x = x' then r' else RelLet ([b], r)
   400       | s_rel_let bs r = RelLet (bs, r)
   401 
   402     fun s_rel_if f r1 r2 =
   403       (case (f, r1, r2) of
   404          (True, _, _) => r1
   405        | (False, _, _) => r2
   406        | (No r1', None, RelIf (One r2', r3', r4')) =>
   407          if r1' = r2' andalso r2' = r3' then s_rel_if (Lone r1') r1' r4'
   408          else raise SAME ()
   409        | _ => raise SAME ())
   410       handle SAME () => if r1 = r2 then r1 else RelIf (f, r1, r2)
   411 
   412     fun s_union r1 (Union (r21, r22)) = s_union (s_union r1 r21) r22
   413       | s_union r1 r2 =
   414         if is_none_product r1 then r2
   415         else if is_none_product r2 then r1
   416         else if r1 = r2 then r1
   417         else if occurs_in_union r2 r1 then r1
   418         else Union (r1, r2)
   419     fun s_difference r1 r2 =
   420       if is_none_product r1 orelse is_none_product r2 then r1
   421       else if r1 = r2 then empty_n_ary_rel (arity_of_rel_expr r1)
   422       else Difference (r1, r2)
   423     fun s_override r1 r2 =
   424       if is_none_product r2 then r1
   425       else if is_none_product r1 then r2
   426       else Override (r1, r2)
   427     fun s_intersect r1 r2 =
   428       case rel_expr_intersects r1 r2 of
   429         SOME true => if r1 = r2 then r1 else Intersect (r1, r2)
   430       | SOME false => empty_n_ary_rel (arity_of_rel_expr r1)
   431       | NONE => if is_none_product r1 then r1
   432                 else if is_none_product r2 then r2
   433                 else Intersect (r1, r2)
   434     fun s_product r1 r2 =
   435       if is_none_product r1 then
   436         Product (r1, empty_n_ary_rel (arity_of_rel_expr r2))
   437       else if is_none_product r2 then
   438         Product (empty_n_ary_rel (arity_of_rel_expr r1), r2)
   439       else
   440         Product (r1, r2)
   441     fun s_join r1 (Product (Product (r211, r212), r22)) =
   442         Product (s_join r1 (Product (r211, r212)), r22)
   443       | s_join (Product (r11, Product (r121, r122))) r2 =
   444         Product (r11, s_join (Product (r121, r122)) r2)
   445       | s_join None r = empty_n_ary_rel (arity_of_rel_expr r - 1)
   446       | s_join r None = empty_n_ary_rel (arity_of_rel_expr r - 1)
   447       | s_join (Product (None, None)) r = empty_n_ary_rel (arity_of_rel_expr r)
   448       | s_join r (Product (None, None)) = empty_n_ary_rel (arity_of_rel_expr r)
   449       | s_join Iden r2 = r2
   450       | s_join r1 Iden = r1
   451       | s_join (Product (r1, r2)) Univ =
   452         if arity_of_rel_expr r2 = 1 then r1
   453         else Product (r1, s_join r2 Univ)
   454       | s_join Univ (Product (r1, r2)) =
   455         if arity_of_rel_expr r1 = 1 then r2
   456         else Product (s_join Univ r1, r2)
   457       | s_join r1 (r2 as Product (r21, r22)) =
   458         if arity_of_rel_expr r1 = 1 then
   459           case rel_expr_intersects r1 r21 of
   460             SOME true => r22
   461           | SOME false => empty_n_ary_rel (arity_of_rel_expr r2 - 1)
   462           | NONE => Join (r1, r2)
   463         else
   464           Join (r1, r2)
   465       | s_join (r1 as Product (r11, r12)) r2 =
   466         if arity_of_rel_expr r2 = 1 then
   467           case rel_expr_intersects r2 r12 of
   468             SOME true => r11
   469           | SOME false => empty_n_ary_rel (arity_of_rel_expr r1 - 1)
   470           | NONE => Join (r1, r2)
   471         else
   472           Join (r1, r2)
   473       | s_join r1 (r2 as RelIf (f, r21, r22)) =
   474         if inline_rel_expr r1 then s_rel_if f (s_join r1 r21) (s_join r1 r22)
   475         else Join (r1, r2)
   476       | s_join (r1 as RelIf (f, r11, r12)) r2 =
   477         if inline_rel_expr r2 then s_rel_if f (s_join r11 r2) (s_join r12 r2)
   478         else Join (r1, r2)
   479       | s_join (r1 as Atom j1) (r2 as Rel (x as (2, _))) =
   480         if x = suc_rel then
   481           let val n = to_nat j1 + 1 in
   482             if n < nat_card then from_nat n else None
   483           end
   484         else
   485           Join (r1, r2)
   486       | s_join r1 (r2 as Project (r21, Num k :: is)) =
   487         if k = arity_of_rel_expr r21 - 1 andalso arity_of_rel_expr r1 = 1 then
   488           s_project (s_join r21 r1) is
   489         else
   490           Join (r1, r2)
   491       | s_join r1 (Join (r21, r22 as Rel (x as (3, _)))) =
   492         ((if x = nat_add_rel then
   493             case (r21, r1) of
   494               (Atom j1, Atom j2) =>
   495               let val n = to_nat j1 + to_nat j2 in
   496                 if n < nat_card then from_nat n else None
   497               end
   498             | (Atom j, r) =>
   499               (case to_nat j of
   500                  0 => r
   501                | 1 => s_join r (Rel suc_rel)
   502                | _ => raise SAME ())
   503             | (r, Atom j) =>
   504               (case to_nat j of
   505                  0 => r
   506                | 1 => s_join r (Rel suc_rel)
   507                | _ => raise SAME ())
   508             | _ => raise SAME ()
   509           else if x = nat_subtract_rel then
   510             case (r21, r1) of
   511               (Atom j1, Atom j2) => from_nat (nat_minus (to_nat j1) (to_nat j2))
   512             | _ => raise SAME ()
   513           else if x = nat_multiply_rel then
   514             case (r21, r1) of
   515               (Atom j1, Atom j2) =>
   516               let val n = to_nat j1 * to_nat j2 in
   517                 if n < nat_card then from_nat n else None
   518               end
   519             | (Atom j, r) =>
   520               (case to_nat j of 0 => Atom j | 1 => r | _ => raise SAME ())
   521             | (r, Atom j) =>
   522               (case to_nat j of 0 => Atom j | 1 => r | _ => raise SAME ())
   523             | _ => raise SAME ()
   524           else
   525             raise SAME ())
   526          handle SAME () => List.foldr Join r22 [r1, r21])
   527       | s_join r1 r2 = Join (r1, r2)
   528 
   529     fun s_closure Iden = Iden
   530       | s_closure r = if is_none_product r then r else Closure r
   531     fun s_reflexive_closure Iden = Iden
   532       | s_reflexive_closure r =
   533         if is_none_product r then Iden else ReflexiveClosure r
   534 
   535     fun s_comprehension ds False = empty_n_ary_rel (length ds)
   536       | s_comprehension ds True = fold1 s_product (map decl_one_set ds)
   537       | s_comprehension [d as DeclOne ((1, j1), r)]
   538                         (f as RelEq (Var (1, j2), Atom j)) =
   539         if j1 = j2 andalso rel_expr_intersects (Atom j) r = SOME true then
   540           Atom j
   541         else
   542           Comprehension ([d], f)
   543       | s_comprehension ds f = Comprehension (ds, f)
   544 
   545     fun s_project_seq r =
   546       let
   547         fun aux arity r j0 n =
   548           if j0 = 0 andalso arity = n then
   549             r
   550           else case r of
   551             RelIf (f, r1, r2) =>
   552             s_rel_if f (aux arity r1 j0 n) (aux arity r2 j0 n)
   553           | Product (r1, r2) =>
   554             let
   555               val arity2 = arity_of_rel_expr r2
   556               val arity1 = arity - arity2
   557               val n1 = Int.min (nat_minus arity1 j0, n)
   558               val n2 = n - n1
   559               fun one () = aux arity1 r1 j0 n1
   560               fun two () = aux arity2 r2 (nat_minus j0 arity1) n2
   561             in
   562               case (n1, n2) of
   563                 (0, _) => s_rel_if (s_some r1) (two ()) (empty_n_ary_rel n2)
   564               | (_, 0) => s_rel_if (s_some r2) (one ()) (empty_n_ary_rel n1)
   565               | _ => s_product (one ()) (two ())
   566             end
   567           | _ => s_project r (num_seq j0 n)
   568       in aux (arity_of_rel_expr r) r end
   569 
   570     fun s_nat_less (Atom j1) (Atom j2) = from_bool (j1 < j2)
   571       | s_nat_less r1 r2 = fold s_join [r1, r2] (Rel nat_less_rel)
   572     fun s_int_less (Atom j1) (Atom j2) = from_bool (to_int j1 < to_int j2)
   573       | s_int_less r1 r2 = fold s_join [r1, r2] (Rel int_less_rel)
   574 
   575     fun d_project_seq r j0 n = Project (r, num_seq j0 n)
   576     fun d_not3 r = Join (r, Rel not3_rel)
   577     fun d_nat_less r1 r2 = List.foldl Join (Rel nat_less_rel) [r1, r2]
   578     fun d_int_less r1 r2 = List.foldl Join (Rel int_less_rel) [r1, r2]
   579   in
   580     if optim then
   581       {kk_all = s_all, kk_exist = s_exist, kk_formula_let = s_formula_let,
   582        kk_formula_if = s_formula_if, kk_or = s_or, kk_not = s_not,
   583        kk_iff = s_iff, kk_implies = s_implies, kk_and = s_and,
   584        kk_subset = s_subset, kk_rel_eq = s_rel_eq, kk_no = s_no,
   585        kk_lone = s_lone, kk_one = s_one, kk_some = s_some,
   586        kk_rel_let = s_rel_let, kk_rel_if = s_rel_if, kk_union = s_union,
   587        kk_difference = s_difference, kk_override = s_override,
   588        kk_intersect = s_intersect, kk_product = s_product, kk_join = s_join,
   589        kk_closure = s_closure, kk_reflexive_closure = s_reflexive_closure,
   590        kk_comprehension = s_comprehension, kk_project = s_project,
   591        kk_project_seq = s_project_seq, kk_not3 = s_not3,
   592        kk_nat_less = s_nat_less, kk_int_less = s_int_less}
   593     else
   594       {kk_all = curry All, kk_exist = curry Exist,
   595        kk_formula_let = curry FormulaLet, kk_formula_if = curry3 FormulaIf,
   596        kk_or = curry Or,kk_not = Not, kk_iff = curry Iff, kk_implies = curry
   597        Implies, kk_and = curry And, kk_subset = curry Subset, kk_rel_eq = curry
   598        RelEq, kk_no = No, kk_lone = Lone, kk_one = One, kk_some = Some,
   599        kk_rel_let = curry RelLet, kk_rel_if = curry3 RelIf, kk_union = curry
   600        Union, kk_difference = curry Difference, kk_override = curry Override,
   601        kk_intersect = curry Intersect, kk_product = curry Product,
   602        kk_join = curry Join, kk_closure = Closure,
   603        kk_reflexive_closure = ReflexiveClosure, kk_comprehension = curry
   604        Comprehension, kk_project = curry Project,
   605        kk_project_seq = d_project_seq, kk_not3 = d_not3,
   606        kk_nat_less = d_nat_less, kk_int_less = d_int_less}
   607   end
   608 
   609 end;