src/HOL/Tools/SMT/smt_normalize.ML
 author boehmes Fri Oct 29 18:17:04 2010 +0200 (2010-10-29) changeset 40274 6486c610a549 parent 40162 7f58a9a843c2 child 40275 eed48b11abdb permissions -rw-r--r--
introduced SMT.distinct as a representation of the solvers' built-in predicate; check that SMT.distinct is always applied to an explicit list
```     1 (*  Title:      HOL/Tools/SMT/smt_normalize.ML
```
```     2     Author:     Sascha Boehme, TU Muenchen
```
```     3
```
```     4 Normalization steps on theorems required by SMT solvers:
```
```     5   * simplify trivial distincts (those with less than three elements),
```
```     6   * rewrite bool case expressions as if expressions,
```
```     7   * normalize numerals (e.g. replace negative numerals by negated positive
```
```     8     numerals),
```
```     9   * embed natural numbers into integers,
```
```    10   * add extra rules specifying types and constants which occur frequently,
```
```    11   * fully translate into object logic, add universal closure,
```
```    12   * monomorphize (create instances of schematic rules),
```
```    13   * lift lambda terms,
```
```    14   * make applications explicit for functions with varying number of arguments.
```
```    15   * add (hypothetical definitions for) missing datatype selectors,
```
```    16 *)
```
```    17
```
```    18 signature SMT_NORMALIZE =
```
```    19 sig
```
```    20   type extra_norm = bool -> (int * thm) list -> Proof.context ->
```
```    21     (int * thm) list * Proof.context
```
```    22   val normalize: extra_norm -> bool -> (int * thm) list -> Proof.context ->
```
```    23     (int * thm) list * Proof.context
```
```    24   val atomize_conv: Proof.context -> conv
```
```    25   val eta_expand_conv: (Proof.context -> conv) -> Proof.context -> conv
```
```    26 end
```
```    27
```
```    28 structure SMT_Normalize: SMT_NORMALIZE =
```
```    29 struct
```
```    30
```
```    31 infix 2 ??
```
```    32 fun (test ?? f) x = if test x then f x else x
```
```    33
```
```    34 fun if_conv c cv1 cv2 ct = (if c (Thm.term_of ct) then cv1 else cv2) ct
```
```    35 fun if_true_conv c cv = if_conv c cv Conv.all_conv
```
```    36
```
```    37
```
```    38
```
```    39 (* simplification of trivial distincts (distinct should have at least
```
```    40    three elements in the argument list) *)
```
```    41
```
```    42 local
```
```    43   fun is_trivial_distinct (Const (@{const_name SMT.distinct}, _) \$ t) =
```
```    44        (length (HOLogic.dest_list t) <= 2
```
```    45         handle TERM _ => error ("SMT: constant " ^
```
```    46           quote @{const_name SMT.distinct} ^ " must be applied to " ^
```
```    47           "an explicit list."))
```
```    48     | is_trivial_distinct _ = false
```
```    49
```
```    50   val thms = map mk_meta_eq @{lemma
```
```    51     "SMT.distinct [] = True"
```
```    52     "SMT.distinct [x] = True"
```
```    53     "SMT.distinct [x, y] = (x ~= y)"
```
```    54     by (simp_all add: distinct_def)}
```
```    55   fun distinct_conv _ =
```
```    56     if_true_conv is_trivial_distinct (Conv.rewrs_conv thms)
```
```    57 in
```
```    58 fun trivial_distinct ctxt =
```
```    59   map (apsnd ((Term.exists_subterm is_trivial_distinct o Thm.prop_of) ??
```
```    60     Conv.fconv_rule (Conv.top_conv distinct_conv ctxt)))
```
```    61 end
```
```    62
```
```    63
```
```    64
```
```    65 (* rewrite bool case expressions as if expressions *)
```
```    66
```
```    67 local
```
```    68   val is_bool_case = (fn
```
```    69       Const (@{const_name "bool.bool_case"}, _) \$ _ \$ _ \$ _ => true
```
```    70     | _ => false)
```
```    71
```
```    72   val thms = map mk_meta_eq @{lemma
```
```    73     "(case P of True => x | False => y) = (if P then x else y)"
```
```    74     "(case P of False => y | True => x) = (if P then x else y)"
```
```    75     by simp_all}
```
```    76   val unfold_conv = if_true_conv is_bool_case (Conv.rewrs_conv thms)
```
```    77 in
```
```    78 fun rewrite_bool_cases ctxt =
```
```    79   map (apsnd ((Term.exists_subterm is_bool_case o Thm.prop_of) ??
```
```    80     Conv.fconv_rule (Conv.top_conv (K unfold_conv) ctxt)))
```
```    81 end
```
```    82
```
```    83
```
```    84
```
```    85 (* normalization of numerals: rewriting of negative integer numerals into
```
```    86    positive numerals, Numeral0 into 0, Numeral1 into 1 *)
```
```    87
```
```    88 local
```
```    89   fun is_number_sort ctxt T =
```
```    90     Sign.of_sort (ProofContext.theory_of ctxt) (T, @{sort number_ring})
```
```    91
```
```    92   fun is_strange_number ctxt (t as Const (@{const_name number_of}, _) \$ _) =
```
```    93         (case try HOLogic.dest_number t of
```
```    94           SOME (T, i) => is_number_sort ctxt T andalso i < 2
```
```    95         | NONE => false)
```
```    96     | is_strange_number _ _ = false
```
```    97
```
```    98   val pos_numeral_ss = HOL_ss
```
```    99     addsimps [@{thm Int.number_of_minus}, @{thm Int.number_of_Min}]
```
```   100     addsimps [@{thm Int.number_of_Pls}, @{thm Int.numeral_1_eq_1}]
```
```   101     addsimps @{thms Int.pred_bin_simps}
```
```   102     addsimps @{thms Int.normalize_bin_simps}
```
```   103     addsimps @{lemma
```
```   104       "Int.Min = - Int.Bit1 Int.Pls"
```
```   105       "Int.Bit0 (- Int.Pls) = - Int.Pls"
```
```   106       "Int.Bit0 (- k) = - Int.Bit0 k"
```
```   107       "Int.Bit1 (- k) = - Int.Bit1 (Int.pred k)"
```
```   108       by simp_all (simp add: pred_def)}
```
```   109
```
```   110   fun pos_conv ctxt = if_conv (is_strange_number ctxt)
```
```   111     (Simplifier.rewrite (Simplifier.context ctxt pos_numeral_ss))
```
```   112     Conv.no_conv
```
```   113 in
```
```   114 fun normalize_numerals ctxt =
```
```   115   map (apsnd ((Term.exists_subterm (is_strange_number ctxt) o Thm.prop_of) ??
```
```   116     Conv.fconv_rule (Conv.top_sweep_conv pos_conv ctxt)))
```
```   117 end
```
```   118
```
```   119
```
```   120
```
```   121 (* embedding of standard natural number operations into integer operations *)
```
```   122
```
```   123 local
```
```   124   val nat_embedding = map (pair ~1) @{lemma
```
```   125     "nat (int n) = n"
```
```   126     "i >= 0 --> int (nat i) = i"
```
```   127     "i < 0 --> int (nat i) = 0"
```
```   128     by simp_all}
```
```   129
```
```   130   val nat_rewriting = @{lemma
```
```   131     "0 = nat 0"
```
```   132     "1 = nat 1"
```
```   133     "number_of i = nat (number_of i)"
```
```   134     "int (nat 0) = 0"
```
```   135     "int (nat 1) = 1"
```
```   136     "a < b = (int a < int b)"
```
```   137     "a <= b = (int a <= int b)"
```
```   138     "Suc a = nat (int a + 1)"
```
```   139     "a + b = nat (int a + int b)"
```
```   140     "a - b = nat (int a - int b)"
```
```   141     "a * b = nat (int a * int b)"
```
```   142     "a div b = nat (int a div int b)"
```
```   143     "a mod b = nat (int a mod int b)"
```
```   144     "min a b = nat (min (int a) (int b))"
```
```   145     "max a b = nat (max (int a) (int b))"
```
```   146     "int (nat (int a + int b)) = int a + int b"
```
```   147     "int (nat (int a * int b)) = int a * int b"
```
```   148     "int (nat (int a div int b)) = int a div int b"
```
```   149     "int (nat (int a mod int b)) = int a mod int b"
```
```   150     "int (nat (min (int a) (int b))) = min (int a) (int b)"
```
```   151     "int (nat (max (int a) (int b))) = max (int a) (int b)"
```
```   152     by (simp_all add: nat_mult_distrib nat_div_distrib nat_mod_distrib
```
```   153       int_mult[symmetric] zdiv_int[symmetric] zmod_int[symmetric])}
```
```   154
```
```   155   fun on_positive num f x =
```
```   156     (case try HOLogic.dest_number (Thm.term_of num) of
```
```   157       SOME (_, i) => if i >= 0 then SOME (f x) else NONE
```
```   158     | NONE => NONE)
```
```   159
```
```   160   val cancel_int_nat_ss = HOL_ss
```
```   161     addsimps [@{thm Nat_Numeral.nat_number_of}]
```
```   162     addsimps [@{thm Nat_Numeral.int_nat_number_of}]
```
```   163     addsimps @{thms neg_simps}
```
```   164
```
```   165   fun cancel_int_nat_simproc _ ss ct =
```
```   166     let
```
```   167       val num = Thm.dest_arg (Thm.dest_arg ct)
```
```   168       val goal = Thm.mk_binop @{cterm "op == :: int => _"} ct num
```
```   169       val simpset = Simplifier.inherit_context ss cancel_int_nat_ss
```
```   170       fun tac _ = Simplifier.simp_tac simpset 1
```
```   171     in on_positive num (Goal.prove_internal [] goal) tac end
```
```   172
```
```   173   val nat_ss = HOL_ss
```
```   174     addsimps nat_rewriting
```
```   175     addsimprocs [Simplifier.make_simproc {
```
```   176       name = "cancel_int_nat_num", lhss = [@{cpat "int (nat _)"}],
```
```   177       proc = cancel_int_nat_simproc, identifier = [] }]
```
```   178
```
```   179   fun conv ctxt = Simplifier.rewrite (Simplifier.context ctxt nat_ss)
```
```   180
```
```   181   val uses_nat_type = Term.exists_type (Term.exists_subtype (equal @{typ nat}))
```
```   182   val uses_nat_int =
```
```   183     Term.exists_subterm (member (op aconv) [@{term int}, @{term nat}])
```
```   184 in
```
```   185 fun nat_as_int ctxt =
```
```   186   map (apsnd ((uses_nat_type o Thm.prop_of) ?? Conv.fconv_rule (conv ctxt))) #>
```
```   187   exists (uses_nat_int o Thm.prop_of o snd) ?? append nat_embedding
```
```   188 end
```
```   189
```
```   190
```
```   191
```
```   192 (* further normalizations: beta/eta, universal closure, atomize *)
```
```   193
```
```   194 val eta_expand_eq = @{lemma "f == (%x. f x)" by (rule reflexive)}
```
```   195
```
```   196 fun eta_expand_conv cv ctxt =
```
```   197   Conv.rewr_conv eta_expand_eq then_conv Conv.abs_conv (cv o snd) ctxt
```
```   198
```
```   199 local
```
```   200   val eta_conv = eta_expand_conv
```
```   201
```
```   202   fun keep_conv ctxt = Conv.binder_conv (norm_conv o snd) ctxt
```
```   203   and eta_binder_conv ctxt = Conv.arg_conv (eta_conv norm_conv ctxt)
```
```   204   and keep_let_conv ctxt = Conv.combination_conv
```
```   205     (Conv.arg_conv (norm_conv ctxt)) (Conv.abs_conv (norm_conv o snd) ctxt)
```
```   206   and unfold_let_conv ctxt = Conv.combination_conv
```
```   207     (Conv.arg_conv (norm_conv ctxt)) (eta_conv norm_conv ctxt)
```
```   208   and unfold_conv thm ctxt = Conv.rewr_conv thm then_conv keep_conv ctxt
```
```   209   and unfold_ex1_conv ctxt = unfold_conv @{thm Ex1_def} ctxt
```
```   210   and unfold_ball_conv ctxt = unfold_conv (mk_meta_eq @{thm Ball_def}) ctxt
```
```   211   and unfold_bex_conv ctxt = unfold_conv (mk_meta_eq @{thm Bex_def}) ctxt
```
```   212   and norm_conv ctxt ct =
```
```   213     (case Thm.term_of ct of
```
```   214       Const (@{const_name All}, _) \$ Abs _ => keep_conv
```
```   215     | Const (@{const_name All}, _) \$ _ => eta_binder_conv
```
```   216     | Const (@{const_name All}, _) => eta_conv eta_binder_conv
```
```   217     | Const (@{const_name Ex}, _) \$ Abs _ => keep_conv
```
```   218     | Const (@{const_name Ex}, _) \$ _ => eta_binder_conv
```
```   219     | Const (@{const_name Ex}, _) => eta_conv eta_binder_conv
```
```   220     | Const (@{const_name Let}, _) \$ _ \$ Abs _ => keep_let_conv
```
```   221     | Const (@{const_name Let}, _) \$ _ \$ _ => unfold_let_conv
```
```   222     | Const (@{const_name Let}, _) \$ _ => eta_conv unfold_let_conv
```
```   223     | Const (@{const_name Let}, _) => eta_conv (eta_conv unfold_let_conv)
```
```   224     | Const (@{const_name Ex1}, _) \$ _ => unfold_ex1_conv
```
```   225     | Const (@{const_name Ex1}, _) => eta_conv unfold_ex1_conv
```
```   226     | Const (@{const_name Ball}, _) \$ _ \$ _ => unfold_ball_conv
```
```   227     | Const (@{const_name Ball}, _) \$ _ => eta_conv unfold_ball_conv
```
```   228     | Const (@{const_name Ball}, _) => eta_conv (eta_conv unfold_ball_conv)
```
```   229     | Const (@{const_name Bex}, _) \$ _ \$ _ => unfold_bex_conv
```
```   230     | Const (@{const_name Bex}, _) \$ _ => eta_conv unfold_bex_conv
```
```   231     | Const (@{const_name Bex}, _) => eta_conv (eta_conv unfold_bex_conv)
```
```   232     | Abs _ => Conv.abs_conv (norm_conv o snd)
```
```   233     | _ \$ _ => Conv.comb_conv o norm_conv
```
```   234     | _ => K Conv.all_conv) ctxt ct
```
```   235
```
```   236   fun is_normed t =
```
```   237     (case t of
```
```   238       Const (@{const_name All}, _) \$ Abs (_, _, u) => is_normed u
```
```   239     | Const (@{const_name All}, _) \$ _ => false
```
```   240     | Const (@{const_name All}, _) => false
```
```   241     | Const (@{const_name Ex}, _) \$ Abs (_, _, u) => is_normed u
```
```   242     | Const (@{const_name Ex}, _) \$ _ => false
```
```   243     | Const (@{const_name Ex}, _) => false
```
```   244     | Const (@{const_name Let}, _) \$ u1 \$ Abs (_, _, u2) =>
```
```   245         is_normed u1 andalso is_normed u2
```
```   246     | Const (@{const_name Let}, _) \$ _ \$ _ => false
```
```   247     | Const (@{const_name Let}, _) \$ _ => false
```
```   248     | Const (@{const_name Let}, _) => false
```
```   249     | Const (@{const_name Ex1}, _) => false
```
```   250     | Const (@{const_name Ball}, _) => false
```
```   251     | Const (@{const_name Bex}, _) => false
```
```   252     | Abs (_, _, u) => is_normed u
```
```   253     | u1 \$ u2 => is_normed u1 andalso is_normed u2
```
```   254     | _ => true)
```
```   255 in
```
```   256 fun norm_binder_conv ctxt = if_conv is_normed Conv.all_conv (norm_conv ctxt)
```
```   257 end
```
```   258
```
```   259 fun norm_def ctxt thm =
```
```   260   (case Thm.prop_of thm of
```
```   261     @{term Trueprop} \$ (Const (@{const_name HOL.eq}, _) \$ _ \$ Abs _) =>
```
```   262       norm_def ctxt (thm RS @{thm fun_cong})
```
```   263   | Const (@{const_name "=="}, _) \$ _ \$ Abs _ =>
```
```   264       norm_def ctxt (thm RS @{thm meta_eq_to_obj_eq})
```
```   265   | _ => thm)
```
```   266
```
```   267 fun atomize_conv ctxt ct =
```
```   268   (case Thm.term_of ct of
```
```   269     @{term "op ==>"} \$ _ \$ _ =>
```
```   270       Conv.binop_conv (atomize_conv ctxt) then_conv
```
```   271       Conv.rewr_conv @{thm atomize_imp}
```
```   272   | Const (@{const_name "=="}, _) \$ _ \$ _ =>
```
```   273       Conv.binop_conv (atomize_conv ctxt) then_conv
```
```   274       Conv.rewr_conv @{thm atomize_eq}
```
```   275   | Const (@{const_name all}, _) \$ Abs _ =>
```
```   276       Conv.binder_conv (atomize_conv o snd) ctxt then_conv
```
```   277       Conv.rewr_conv @{thm atomize_all}
```
```   278   | _ => Conv.all_conv) ct
```
```   279
```
```   280 fun normalize_rule ctxt =
```
```   281   Conv.fconv_rule (
```
```   282     (* reduce lambda abstractions, except at known binders: *)
```
```   283     Thm.beta_conversion true then_conv
```
```   284     Thm.eta_conversion then_conv
```
```   285     norm_binder_conv ctxt) #>
```
```   286   norm_def ctxt #>
```
```   287   Drule.forall_intr_vars #>
```
```   288   Conv.fconv_rule (atomize_conv ctxt)
```
```   289
```
```   290
```
```   291
```
```   292 (* lift lambda terms into additional rules *)
```
```   293
```
```   294 local
```
```   295   val meta_eq = @{cpat "op =="}
```
```   296   val meta_eqT = hd (Thm.dest_ctyp (Thm.ctyp_of_term meta_eq))
```
```   297   fun inst_meta cT = Thm.instantiate_cterm ([(meta_eqT, cT)], []) meta_eq
```
```   298   fun mk_meta_eq ct cu = Thm.mk_binop (inst_meta (Thm.ctyp_of_term ct)) ct cu
```
```   299
```
```   300   fun cert ctxt = Thm.cterm_of (ProofContext.theory_of ctxt)
```
```   301
```
```   302   fun used_vars cvs ct =
```
```   303     let
```
```   304       val lookup = AList.lookup (op aconv) (map (` Thm.term_of) cvs)
```
```   305       val add = (fn SOME ct => insert (op aconvc) ct | _ => I)
```
```   306     in Term.fold_aterms (add o lookup) (Thm.term_of ct) [] end
```
```   307
```
```   308   fun apply cv thm =
```
```   309     let val thm' = Thm.combination thm (Thm.reflexive cv)
```
```   310     in Thm.transitive thm' (Thm.beta_conversion false (Thm.rhs_of thm')) end
```
```   311   fun apply_def cvs eq = Thm.symmetric (fold apply cvs eq)
```
```   312
```
```   313   fun replace_lambda cvs ct (cx as (ctxt, defs)) =
```
```   314     let
```
```   315       val cvs' = used_vars cvs ct
```
```   316       val ct' = fold_rev Thm.cabs cvs' ct
```
```   317     in
```
```   318       (case Termtab.lookup defs (Thm.term_of ct') of
```
```   319         SOME eq => (apply_def cvs' eq, cx)
```
```   320       | NONE =>
```
```   321           let
```
```   322             val {T, ...} = Thm.rep_cterm ct' and n = Name.uu
```
```   323             val (n', ctxt') = yield_singleton Variable.variant_fixes n ctxt
```
```   324             val cu = mk_meta_eq (cert ctxt (Free (n', T))) ct'
```
```   325             val (eq, ctxt'') = yield_singleton Assumption.add_assumes cu ctxt'
```
```   326             val defs' = Termtab.update (Thm.term_of ct', eq) defs
```
```   327           in (apply_def cvs' eq, (ctxt'', defs')) end)
```
```   328     end
```
```   329
```
```   330   fun none ct cx = (Thm.reflexive ct, cx)
```
```   331   fun in_comb f g ct cx =
```
```   332     let val (cu1, cu2) = Thm.dest_comb ct
```
```   333     in cx |> f cu1 ||>> g cu2 |>> uncurry Thm.combination end
```
```   334   fun in_arg f = in_comb none f
```
```   335   fun in_abs f cvs ct (ctxt, defs) =
```
```   336     let
```
```   337       val (n, ctxt') = yield_singleton Variable.variant_fixes Name.uu ctxt
```
```   338       val (cv, cu) = Thm.dest_abs (SOME n) ct
```
```   339     in  (ctxt', defs) |> f (cv :: cvs) cu |>> Thm.abstract_rule n cv end
```
```   340
```
```   341   fun traverse cvs ct =
```
```   342     (case Thm.term_of ct of
```
```   343       Const (@{const_name All}, _) \$ Abs _ => in_arg (in_abs traverse cvs)
```
```   344     | Const (@{const_name Ex}, _) \$ Abs _ => in_arg (in_abs traverse cvs)
```
```   345     | Const (@{const_name Let}, _) \$ _ \$ Abs _ =>
```
```   346         in_comb (in_arg (traverse cvs)) (in_abs traverse cvs)
```
```   347     | Abs _ => at_lambda cvs
```
```   348     | _ \$ _ => in_comb (traverse cvs) (traverse cvs)
```
```   349     | _ => none) ct
```
```   350
```
```   351   and at_lambda cvs ct =
```
```   352     in_abs traverse cvs ct #-> (fn thm =>
```
```   353     replace_lambda cvs (Thm.rhs_of thm) #>> Thm.transitive thm)
```
```   354
```
```   355   fun has_free_lambdas t =
```
```   356     (case t of
```
```   357       Const (@{const_name All}, _) \$ Abs (_, _, u) => has_free_lambdas u
```
```   358     | Const (@{const_name Ex}, _) \$ Abs (_, _, u) => has_free_lambdas u
```
```   359     | Const (@{const_name Let}, _) \$ u1 \$ Abs (_, _, u2) =>
```
```   360         has_free_lambdas u1 orelse has_free_lambdas u2
```
```   361     | Abs _ => true
```
```   362     | u1 \$ u2 => has_free_lambdas u1 orelse has_free_lambdas u2
```
```   363     | _ => false)
```
```   364
```
```   365   fun lift_lm f thm cx =
```
```   366     if not (has_free_lambdas (Thm.prop_of thm)) then (thm, cx)
```
```   367     else cx |> f (Thm.cprop_of thm) |>> (fn thm' => Thm.equal_elim thm' thm)
```
```   368 in
```
```   369 fun lift_lambdas irules ctxt =
```
```   370   let
```
```   371     val cx = (ctxt, Termtab.empty)
```
```   372     val (idxs, thms) = split_list irules
```
```   373     val (thms', (ctxt', defs)) = fold_map (lift_lm (traverse [])) thms cx
```
```   374     val eqs = Termtab.fold (cons o normalize_rule ctxt' o snd) defs []
```
```   375   in (map (pair ~1) eqs @ (idxs ~~ thms'), ctxt') end
```
```   376 end
```
```   377
```
```   378
```
```   379
```
```   380 (* make application explicit for functions with varying number of arguments *)
```
```   381
```
```   382 local
```
```   383   val const = prefix "c" and free = prefix "f"
```
```   384   fun min i (e as (_, j)) = if i <> j then (true, Int.min (i, j)) else e
```
```   385   fun add t i = Symtab.map_default (t, (false, i)) (min i)
```
```   386   fun traverse t =
```
```   387     (case Term.strip_comb t of
```
```   388       (Const (n, _), ts) => add (const n) (length ts) #> fold traverse ts
```
```   389     | (Free (n, _), ts) => add (free n) (length ts) #> fold traverse ts
```
```   390     | (Abs (_, _, u), ts) => fold traverse (u :: ts)
```
```   391     | (_, ts) => fold traverse ts)
```
```   392   fun prune tab = Symtab.fold (fn (n, (true, i)) =>
```
```   393     Symtab.update (n, i) | _ => I) tab Symtab.empty
```
```   394
```
```   395   fun binop_conv cv1 cv2 = Conv.combination_conv (Conv.arg_conv cv1) cv2
```
```   396   fun nary_conv conv1 conv2 ct =
```
```   397     (Conv.combination_conv (nary_conv conv1 conv2) conv2 else_conv conv1) ct
```
```   398   fun abs_conv conv tb = Conv.abs_conv (fn (cv, cx) =>
```
```   399     let val n = fst (Term.dest_Free (Thm.term_of cv))
```
```   400     in conv (Symtab.update (free n, 0) tb) cx end)
```
```   401   val fun_app_rule = @{lemma "f x == fun_app f x" by (simp add: fun_app_def)}
```
```   402 in
```
```   403 fun explicit_application ctxt irules =
```
```   404   let
```
```   405     fun sub_conv tb ctxt ct =
```
```   406       (case Term.strip_comb (Thm.term_of ct) of
```
```   407         (Const (n, _), ts) => app_conv tb (const n) (length ts) ctxt
```
```   408       | (Free (n, _), ts) => app_conv tb (free n) (length ts) ctxt
```
```   409       | (Abs _, _) => nary_conv (abs_conv sub_conv tb ctxt) (sub_conv tb ctxt)
```
```   410       | (_, _) => nary_conv Conv.all_conv (sub_conv tb ctxt)) ct
```
```   411     and app_conv tb n i ctxt =
```
```   412       (case Symtab.lookup tb n of
```
```   413         NONE => nary_conv Conv.all_conv (sub_conv tb ctxt)
```
```   414       | SOME j => fun_app_conv tb ctxt (i - j))
```
```   415     and fun_app_conv tb ctxt i ct = (
```
```   416       if i = 0 then nary_conv Conv.all_conv (sub_conv tb ctxt)
```
```   417       else
```
```   418         Conv.rewr_conv fun_app_rule then_conv
```
```   419         binop_conv (fun_app_conv tb ctxt (i-1)) (sub_conv tb ctxt)) ct
```
```   420
```
```   421     fun needs_exp_app tab = Term.exists_subterm (fn
```
```   422         Bound _ \$ _ => true
```
```   423       | Const (n, _) => Symtab.defined tab (const n)
```
```   424       | Free (n, _) => Symtab.defined tab (free n)
```
```   425       | _ => false)
```
```   426
```
```   427     fun rewrite tab ctxt thm =
```
```   428       if not (needs_exp_app tab (Thm.prop_of thm)) then thm
```
```   429       else Conv.fconv_rule (sub_conv tab ctxt) thm
```
```   430
```
```   431     val tab = prune (fold (traverse o Thm.prop_of o snd) irules Symtab.empty)
```
```   432   in map (apsnd (rewrite tab ctxt)) irules end
```
```   433 end
```
```   434
```
```   435
```
```   436
```
```   437 (* add missing datatype selectors via hypothetical definitions *)
```
```   438
```
```   439 local
```
```   440   val add = (fn Type (n, _) => Symtab.update (n, ()) | _ => I)
```
```   441
```
```   442   fun collect t =
```
```   443     (case Term.strip_comb t of
```
```   444       (Abs (_, T, t), _) => add T #> collect t
```
```   445     | (Const (_, T), ts) => collects T ts
```
```   446     | (Free (_, T), ts) => collects T ts
```
```   447     | _ => I)
```
```   448   and collects T ts =
```
```   449     let val ((Ts, Us), U) = Term.strip_type T |> apfst (chop (length ts))
```
```   450     in fold add Ts #> add (Us ---> U) #> fold collect ts end
```
```   451
```
```   452   fun add_constructors thy n =
```
```   453     (case Datatype.get_info thy n of
```
```   454       NONE => I
```
```   455     | SOME {descr, ...} => fold (fn (_, (_, _, cs)) => fold (fn (n, ds) =>
```
```   456         fold (insert (op =) o pair n) (1 upto length ds)) cs) descr)
```
```   457
```
```   458   fun add_selector (c as (n, i)) ctxt =
```
```   459     (case Datatype_Selectors.lookup_selector ctxt c of
```
```   460       SOME _ => ctxt
```
```   461     | NONE =>
```
```   462         let
```
```   463           val T = Sign.the_const_type (ProofContext.theory_of ctxt) n
```
```   464           val U = Term.body_type T --> nth (Term.binder_types T) (i-1)
```
```   465         in
```
```   466           ctxt
```
```   467           |> yield_singleton Variable.variant_fixes Name.uu
```
```   468           |>> pair ((n, T), i) o rpair U
```
```   469           |-> Context.proof_map o Datatype_Selectors.add_selector
```
```   470         end)
```
```   471 in
```
```   472
```
```   473 fun datatype_selectors irules ctxt =
```
```   474   let
```
```   475     val ns = Symtab.keys (fold (collect o Thm.prop_of o snd) irules Symtab.empty)
```
```   476     val cs = fold (add_constructors (ProofContext.theory_of ctxt)) ns []
```
```   477   in (irules, fold add_selector cs ctxt) end
```
```   478     (* FIXME: also generate hypothetical definitions for the selectors *)
```
```   479
```
```   480 end
```
```   481
```
```   482
```
```   483
```
```   484 (* combined normalization *)
```
```   485
```
```   486 type extra_norm = bool -> (int * thm) list -> Proof.context ->
```
```   487   (int * thm) list * Proof.context
```
```   488
```
```   489 fun with_context f irules ctxt = (f ctxt irules, ctxt)
```
```   490
```
```   491 fun normalize extra_norm with_datatypes irules ctxt =
```
```   492   irules
```
```   493   |> trivial_distinct ctxt
```
```   494   |> rewrite_bool_cases ctxt
```
```   495   |> normalize_numerals ctxt
```
```   496   |> nat_as_int ctxt
```
```   497   |> rpair ctxt
```
```   498   |-> extra_norm with_datatypes
```
```   499   |-> with_context (fn cx => map (apsnd (normalize_rule cx)))
```
```   500   |-> SMT_Monomorph.monomorph
```
```   501   |-> lift_lambdas
```
```   502   |-> with_context explicit_application
```
```   503   |-> (if with_datatypes then datatype_selectors else pair)
```
```   504
```
```   505 end
```